-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing5.html
executable file
·1189 lines (916 loc) · 43.4 KB
/
listing5.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>QTExtractAndConvertToMovieFile - /MovieWriter.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/QuickTime/index.html">QuickTime</a> > <a href="../../samplecode/QuickTime/idxMusicAudio-date.html">Audio</a> > <A HREF="javascript:location.replace('index.html');">QTExtractAndConvertToMovieFile</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">QTExtractAndConvertToMovieFile</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/MovieWriter.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/AudioConverter.h</option>
<option value="listing2.html">/AudioConverter.m</option>
<option value="listing3.html">/main.m</option>
<option value="listing4.html">/MovieWriter.h</option>
<option value="listing5.html">/MovieWriter.m</option>
<option value="listing6.html">/MyController.h</option>
<option value="listing7.html">/MyController.m</option></select>
</p>
</form>
<p><strong><a href="QTExtractAndConvertToMovieFile.zip">Download Sample</a></strong> (“QTExtractAndConvertToMovieFile.zip”, 115.3K)<BR>
<strong><a href="QTExtractAndConvertToMovieFile.dmg">Download Sample</a></strong> (“QTExtractAndConvertToMovieFile.dmg”, 173.2K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
File: MovieWriter.m
Author: QuickTime DTS
Change History (most recent first):
<3> 09/19/06 modified to perform audio extraction/conversion for QTExtractAndConvertToMovie
<2> 03/24/06 must pass NSError objects to exportCompleted
<1> 11/10/05 initial release as part of ExtractMovieAudioToAIFF
© Copyright 2005 - 2006 Apple Computer, Inc. All rights reserved.
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
consideration of your agreement to the following terms, and your use, installation,
modification or redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject to these
terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in
this original Apple software (the "Apple Software"), to use, reproduce, modify and
redistribute the Apple Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the Apple Software in its entirety and without
modifications, you must retain this notice and the following text and disclaimers in all
such redistributions of the Apple Software. Neither the name, trademarks, service marks
or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
the Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied, are
granted by Apple herein, including but not limited to any patent rights that may be
infringed by your derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE
APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE
USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER
CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT
LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
QTExtractAndConvertToMovie contains two Objective-C objects that are used together to
implement audio extraction and audio conversion from a QuickTime Movie's sound track to
an movie file.
The first is a simple class called MovieWriter (this is a modified version of the
AIFFWriter class that was included with the ExtractMovieAudioToAIFF and
QTExtractAndConvertToAIFF samples). MovieWriter uses QuickTime's Movie Audio Extraction,
Movie Storage and Media Creation APIs. The second is another simple class called
AudioConverter which encapsulates Core Audio's Audio Converter API.
The sample uses an instance of the MovieWriter class to easily set up audio extraction
from a QTKit QTMovie to a new destination Movie and its associated movie file (or movie
storage as it's called in the API). MovieWriter uses an instance of the AudioConverter
class to perform the conversion to a user selected destination format which is
configured by the Standard Audio Dialog Component. The Audio Converter uses a Movie
Audio Extraction Session in the Read Input Procedure to pull audio out of the source
Movie.
QTExtractAndConvertToMovie demonstrates how to call AddMediaSample2 and supports VBR as
well as CBR audio encoding formats.
NOTE: This sample uses the default extraction channel layout which is the aggregate
channel layout of the Movie (for example, all Rights mixed together, all Left Surrounds
mixed together, etc).
References:
http://developer.apple.com/documentation/QuickTime/Conceptual/QT7UpdateGuide/Chapter02/chapter_2_section_6.html
http://developer.apple.com/documentation/MusicAudio/Conceptual/CoreAudioOverview/WhatsinCoreAudio/chapter_3_section_4.html
*/
#import "MovieWriter.h"
#pragma mark ---- MovieWriterProgressInfo ----
// MovieWriterProgressInfo is the object passed back to the progress callback
// if implemented by the client. It contains information regarding the current
// state of the export session which can be used to drive a UI.
@interface MovieWriterProgressInfo (Private)
- (BOOL)continueOperation;
- (void)setPhase:(MovieWriterExportOperationPhase)value;
- (void)setProgressValue:(NSNumber *)value;
- (void)setExportStatus:(NSError *)status;
@end
@implementation MovieWriterProgressInfo
- (MovieWriterExportOperationPhase)phase
{
return phase;
}
- (NSNumber *)progressValue
{
return [[progressValue retain] autorelease];
}
- (NSError *)exportStatus {
return [[exportStatus retain] autorelease];
}
- (BOOL)continueOperation;
{
return continueOperation;
}
- (void)setContinueOperation:(BOOL)value
{
continueOperation = value;
}
- (void)setPhase:(MovieWriterExportOperationPhase)value
{
phase = value;
}
- (void)setProgressValue:(NSNumber *)value
{
if (progressValue != value) {
[progressValue release];
progressValue = [value copy];
}
}
- (void)setExportStatus:(NSError *)status
{
if (exportStatus != status) {
[exportStatus release];
exportStatus = [status copy];
}
}
- (void)dealloc
{
[progressValue release];
[exportStatus release];
[super dealloc];
}
@end
#pragma mark ---- MovieWriter private interface ----
@interface MovieWriter (Private)
- (void)exportOnMainThreadCallBack:(id)inObject;
- (void)exportOnWorkerThread:(id)inObject;
- (OSStatus)convertAudioToFile:(SInt64 *)ioNumFrames;
- (OSStatus)configureExtractionSessionWithMovie:(Movie)inMovie;
- (OSStatus)createOutputFile:(AudioStreamBasicDescription *)inOutputASBD;
- (void)setMovieConversionDuration;
- (void)exportCompletedNotification:(NSError *)inError;
- (MovieAudioExtractionRef)audioExtractionSession;
- (AudioBufferList *)extractionBufferList;
- (UInt32)extractionBytesPerFrame;
- (BOOL)extractionComplete;
- (void)setExtractionComplete:(BOOL)flag;
@end
@implementation MovieWriter
#pragma mark ---- Audio Converter InputDataProc Implementation ----
// Read Input Procedure used to supply data to the Audio Converter
static OSStatus ReadInputProc(AudioConverterRef inAudioConverter,
UInt32 *ioNumberDataPackets,
AudioBufferList *ioData,
AudioStreamPacketDescription **outDataPacketDescription,
void *inUserData)
{
#pragma unused(inAudioConverter, outDataPacketDescription)
if (NULL == inUserData) return paramErr;
MovieWriter *theMovieWriter = (MovieWriter *)inUserData;
AudioBufferList *extractionBufferList;
UInt32 i, flags;
UInt32 numFrames = kMaxExtractionFrameCount;
UInt32 bytesPerFrame;
MovieAudioExtractionRef audioExtractionSession;
OSStatus err = noErr;
extractionBufferList = [theMovieWriter extractionBufferList];
bytesPerFrame = [theMovieWriter extractionBytesPerFrame];
audioExtractionSession = [theMovieWriter audioExtractionSession];
if (![theMovieWriter extractionComplete]) {
for (i = 0; i < extractionBufferList->mNumberBuffers; i++) {
extractionBufferList->mBuffers[i].mDataByteSize = numFrames * bytesPerFrame;
}
// read the number of requested samples from the movie
// we're using movie audio extraction therefore we know we're supplying pcm so packet descriptions are unnecessary
err = MovieAudioExtractionFillBuffer(audioExtractionSession, &numFrames, extractionBufferList, &flags);
if (flags & kQTMovieAudioExtractionComplete) {
[theMovieWriter setExtractionComplete:YES];
}
*ioNumberDataPackets = numFrames;
for (i = 0; i < extractionBufferList->mNumberBuffers; i++) {
ioData->mBuffers[i] = extractionBufferList->mBuffers[i];
}
} else {
*ioNumberDataPackets = 0;
}
return err;
}
#pragma mark ---- initialization/dealocation ----
- (id)init;
{
if (self = [super init]) {
mLock = [[NSLock alloc] init];
mProgressInfo = [[MovieWriterProgressInfo alloc] init];
}
return self;
}
- (void)dealloc
{
if (mFileName) {
[mFileName release];
}
if (mAudioExtractionSession){
MovieAudioExtractionEnd(mAudioExtractionSession);
}
if (mMyAudioConverter) {
[mMyAudioConverter release];
}
if (mQTMovie) {
[mQTMovie release];
}
if (mSoundDescription) {
DisposeHandle((Handle)mSoundDescription);
mSoundDescription = NULL;
}
if (mExtractionBuffList) {
free(mExtractionBuffList);
}
if (mExtractionBuffer) {
free(mExtractionBuffer);
}
if (mOutputBufferList) {
free(mOutputBufferList);
}
if (mOutputBuffer) {
free(mOutputBuffer);
}
if (mPacketDescriptions) {
free(mPacketDescriptions);
}
[mLock release];
[mProgressInfo release];
[super dealloc];
}
#pragma mark ---- public ----
// main method call that will produce an output movie file - it will try to
// export the source movie on a separate thread but if it can't will schedule
// callbacks on the main thread
- (OSStatus)exportFromMovie:(QTMovie *)inMovie toFile:(NSString *)inFullPath
{
BOOL extractionOnWorkerThread = NO;
BOOL continueExport = YES;
Handle cloneHandle = NULL;
FSRef fileRef;
NSString *directory;
OSStatus err = noErr;
// sanity
if (nil == inMovie || nil == inFullPath) return paramErr;
// if we're busy already doing an export return
if (![mLock tryLock]) return kObjectInUseErr;
mIsConverting = YES;
// if the client implemented a progress proc. call it now
if (TRUE == mDelegateShouldContinueOp) {
[mProgressInfo setPhase:MovieWriterExportBegin];
[mProgressInfo setProgressValue:nil];
[mProgressInfo setExportStatus:nil];
continueExport = [[self delegate] shouldContinueOperationWithProgressInfo:mProgressInfo];
if (NO == continueExport) goto bail;
}
directory = [inFullPath stringByDeletingLastPathComponent];
mFileName = [[NSString alloc] initWithString:[inFullPath lastPathComponent]];
// retain the QTMovie object passed in, we need it for the duration of
// the export regardless of what the client decides to do with it
mQTMovie = [inMovie retain];
// create a new Audio Converter object for this conversion operation
mMyAudioConverter = [AudioConverter newAudioConverterWithMovie:[mQTMovie quickTimeMovie] status:&err];
if (NULL == mMyAudioConverter) goto bail;
// set the Audio Converter Read Input Data Proc
[mMyAudioConverter setInputDataProc:ReadInputProc];
// if the file already exists, delete it
err = FSPathMakeRef((const UInt8*)[inFullPath fileSystemRepresentation], &fileRef, false);
if (err == noErr) {
err = FSDeleteObject(&fileRef);
if (err) goto bail;
}
err = FSPathMakeRef((const UInt8*)[directory fileSystemRepresentation], &mParentRef, NULL);
if (err) goto bail;
// set the movies duration in floating-point seconds
[self setMovieConversionDuration];
// clone the movie and see if we can migrate it to a worker thread for extraction
cloneHandle = NewHandle(0);
if (NULL == cloneHandle) { err = memFullErr; goto bail; }
err = PutMovieIntoHandle([mQTMovie quickTimeMovie], cloneHandle);
if (err) goto bail;
err = NewMovieFromHandle(&mCloneMovie, cloneHandle, newMovieActive, NULL);
if (err != noErr || mCloneMovie == NULL) goto bail;
// if we couldn't migrate this movie, export from the movie on the main thread
if (DetachMovieFromCurrentThread(mCloneMovie) == noErr) {
extractionOnWorkerThread = YES;
} else {
DisposeMovie(mCloneMovie);
mCloneMovie = NULL;
}
if (extractionOnWorkerThread == YES) {
// export on a worker thread if we can...
[NSThread detachNewThreadSelector:@selector(exportOnWorkerThread:) toTarget:self withObject:nil];
} else {
// ...if not, we're on the main thread so just call the main-thread worker method
[self exportOnMainThreadCallBack:nil];
}
bail:
if (cloneHandle) DisposeHandle(cloneHandle);
if (err) [self exportCompletedNotification:[NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]];
return err;
}
- (BOOL)isConverting
{
return mIsConverting;
}
#pragma mark ---- private ----
// this callback is scheduled on the main thread - In order to keep from locking up the UI,
// it does one slice of export, writes it to file and then reschedule itself
-(void)exportOnMainThreadCallBack:(id)inObject
{
#pragma unused(inObject)
BOOL continueExport = YES;
OSStatus err;
// prepare for extraction if this is the first entry
if (NULL == mAudioExtractionSession) {
err = [self configureExtractionSessionWithMovie:[mQTMovie quickTimeMovie]];
if (err) goto bail;
}
// create the file
// set the number of total samples to export
if (0 == mOutputMovieStorageDH) {
AudioStreamBasicDescription *outputASBD = [mMyAudioConverter outputFormat];
err = [self createOutputFile:outputASBD];
if (err) goto bail;
mTotalNumberOfOutputFrames = mMovieDuration ? (mMovieDuration * outputASBD->mSampleRate) : -1;
mOneSegmentOfOutputFrames = (0.50 * outputASBD->mSampleRate);
if (-1 == mTotalNumberOfOutputFrames) { mConversionComplete = YES; err = paramErr; }
}
// perform conversion
if (!mConversionComplete) {
// if the client implemented a progress proc. call it now
if (TRUE == mDelegateShouldContinueOp) {
NSNumber *progressValue = [NSNumber numberWithFloat:(float)((float)mOutputFramesCompleted / (float)mTotalNumberOfOutputFrames)];
[mProgressInfo setPhase:MovieWriterExportPercent];
[mProgressInfo setProgressValue:progressValue];
[mProgressInfo setExportStatus:nil];
continueExport = [[self delegate] shouldContinueOperationWithProgressInfo:mProgressInfo];
if (NO == continueExport) { err = userCanceledErr; goto bail; }
}
// convert and write a half-second's worth of data
SInt64 numFramesThisSlice = mOneSegmentOfOutputFrames;
// extract and convert the audio and write it to the file
err = [self convertAudioToFile:&numFramesThisSlice];
if (err) goto bail;
mOutputFramesCompleted += numFramesThisSlice;
}
bail:
if (err || mConversionComplete) {
// we're done so close the file if there was no error or delete the file if we errored out
if (mOutputMovieStorageDH) {
if (noErr == err) {
Track soundTrack = GetMediaTrack(mSoundMedia);
err = EndMediaEdits(mSoundMedia);
if (noErr == err)
err = InsertMediaIntoTrack(soundTrack, 0, 0, GetMediaDuration(mSoundMedia), fixed1);
if (noErr == err)
err = AddMovieToStorage(mOutputMovie, mOutputMovieStorageDH);
if (err) DataHDeleteFile(mOutputMovieStorageDH);
} else {
DataHDeleteFile(mOutputMovieStorageDH);
}
CloseMovieStorage(mOutputMovieStorageDH);
mOutputMovieStorageDH = 0;
if (mOutputMovie) { DisposeMovie(mOutputMovie); mOutputMovie = 0; }
}
// call the completion routine to clean up
[self exportCompletedNotification:[NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]];
} else {
// reschedule to perform this routine again on the next run loop cycle
[self performSelectorOnMainThread:@selector(exportOnMainThreadCallBack:)
withObject:(id)nil
waitUntilDone:NO];
}
}
// this method will be performed on a background thread
- (void)exportOnWorkerThread:(id)inObject
{
#pragma unused(inObject)
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BOOL continueExport = YES;
OSStatus err;
[NSThread setThreadPriority:[NSThread threadPriority]+.1];
// attach the movie to this thread
err = EnterMoviesOnThread(0);
if (err) goto bail;;
err = AttachMovieToCurrentThread(mCloneMovie);
if (err) goto bail;
// prepare extraction session
if (NULL == mAudioExtractionSession) {
err = [self configureExtractionSessionWithMovie:mCloneMovie];
if (err) goto done;
}
// create the file
if (0 == mOutputMovieStorageDH) {
AudioStreamBasicDescription *outputASBD = [mMyAudioConverter outputFormat];
err = [self createOutputFile:outputASBD];
if (err) goto bail;
mTotalNumberOfOutputFrames = mMovieDuration ? (mMovieDuration * outputASBD->mSampleRate) : -1;
mOneSegmentOfOutputFrames = (5.0 * outputASBD->mSampleRate); // five seconds of audio at a time
if (-1 == mTotalNumberOfOutputFrames) { mConversionComplete = YES; err = paramErr; }
}
// loop until stopped from an external event, or finished the entire operation
while (YES == continueExport && NO == mConversionComplete) {
if (!mConversionComplete) {
// if the client implemented a progress proc. call it now we wait for the
// progress fuction to return before continuing so we can check the return code
if (TRUE == mDelegateShouldContinueOp) {
NSNumber *progressValue = [NSNumber numberWithFloat:(float)((float)mOutputFramesCompleted / (float)mTotalNumberOfOutputFrames)];
[mProgressInfo setPhase:MovieWriterExportPercent];
[mProgressInfo setProgressValue:progressValue];
[mProgressInfo setExportStatus:nil];
[[self delegate] performSelectorOnMainThread:@selector(shouldContinueOperationWithProgressInfo:)
withObject:(id)mProgressInfo
waitUntilDone:YES];
continueExport = [mProgressInfo continueOperation];
if (NO == continueExport) { err = userCanceledErr; break; }
}
// read numSamplesThisSlice number of samples
SInt64 numFramesThisSlice = mOneSegmentOfOutputFrames;
// extract and convert the audio and write it to the file
err = [self convertAudioToFile:&numFramesThisSlice];
if (err) break;
mOutputFramesCompleted += numFramesThisSlice;
}
}
done:
// detach the exported movie from this thread
DetachMovieFromCurrentThread(mCloneMovie);
ExitMoviesOnThread();
if (mOutputMovieStorageDH) {
if (noErr == err) {
Track soundTrack = GetMediaTrack(mSoundMedia);
err = EndMediaEdits(mSoundMedia);
if (noErr == err)
err = InsertMediaIntoTrack(soundTrack, 0, 0, GetMediaDuration(mSoundMedia), fixed1);
if (noErr == err)
err = AddMovieToStorage(mOutputMovie, mOutputMovieStorageDH);
if (err) DataHDeleteFile(mOutputMovieStorageDH);
} else {
DataHDeleteFile(mOutputMovieStorageDH);
}
CloseMovieStorage(mOutputMovieStorageDH);
mOutputMovieStorageDH = 0;
if (mOutputMovie) { DisposeMovie(mOutputMovie); mOutputMovie = 0; }
}
bail:
// call the completion routine to clean up on the main thread
[self performSelectorOnMainThread:@selector(exportCompletedNotification:)
withObject:(id)[NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]
waitUntilDone:YES];
[pool release];
}
// convert a slice of PCM audio and write it to a movie file - we proceed serially
// from the last position, 'ploc' specifies the file offset that the converted buffer should be written to
- (OSStatus)convertAudioToFile:(SInt64 *)ioNumFrames
{
UInt32 i;
UInt32 numFrames, numPackets;
OSStatus err;
AudioStreamBasicDescription *extractionASBD = [mMyAudioConverter inputFormat];
AudioStreamBasicDescription *outputASBD = [mMyAudioConverter outputFormat];
// the AudioConverter doesn't seem to like to emit one packet at a time for QDesign/QualComm,
// so make sure there are at least 2 packets per buffer
numFrames = *ioNumFrames;
numPackets = 2 + (numFrames / outputASBD->mFramesPerPacket);
/* First time though we'll need to set up the Extraction Buffer and BufferList
This is the buffer Movie Audio Extraction is writing into, in other words the source
buffers for the Audio Converter
We're always pulling non-interleaved buffers of LPCM from Movie Audio Extraction
When working with non-interleaved audio, you need to allocate n buffers of bufferSize,
and assign each mData to one of them
NOTE - The extraction pull size will always be 4096 is this sample (kMaxExtractionFrameCount)
*/
if (NULL == mExtractionBuffList) {
mExtractionBufferSize = (kMaxExtractionFrameCount * extractionASBD->mBytesPerFrame);
mExtractionBuffer = (char *)malloc(mExtractionBufferSize * extractionASBD->mChannelsPerFrame);
if (NULL == mExtractionBuffer) {
err = memFullErr;
goto bail;
}
mExtractionBuffList = (AudioBufferList *)calloc(1, offsetof(AudioBufferList, mBuffers[extractionASBD->mChannelsPerFrame]));
if (NULL == mExtractionBuffList) {
err = memFullErr;
goto bail;
}
mExtractionBuffList->mNumberBuffers = extractionASBD->mChannelsPerFrame;
for (i = 0; i < extractionASBD->mChannelsPerFrame; i++) {
mExtractionBuffList->mBuffers[i].mNumberChannels = 1;
mExtractionBuffList->mBuffers[i].mDataByteSize = mExtractionBufferSize;
mExtractionBuffList->mBuffers[i].mData = &mExtractionBuffer[i * mExtractionBufferSize];
}
}
/* First time though we'll need to set up the Output BufferList
We're always converting to interleaved data since we're writing to a file
so one output buffer is all we need
*/
if (NULL == mOutputBufferList) {
// calculate the output buffer size
if (0 == outputASBD->mBytesPerPacket) {
// if bytes per packet value is 0 in the asbd, we will need to use the
// largest possible packet size - this information is available from the audio converter
UInt32 propertySize = sizeof(UInt32);
[mMyAudioConverter getProperty:kAudioConverterPropertyMaximumOutputPacketSize: &propertySize: &mMaxPacketSize];
mOutputBufferSize = (numPackets * mMaxPacketSize);
} else {
mOutputBufferSize = (numPackets * outputASBD->mBytesPerPacket);
}
mOutputBuffer = (char *)malloc(mOutputBufferSize);
if (NULL == mOutputBuffer) {
err = memFullErr;
goto bail;
}
mOutputBufferList = (AudioBufferList *)calloc(1, sizeof(AudioBufferList));
if (NULL == mOutputBufferList) {
err = memFullErr;
goto bail;
}
// externally framed formats requires packet descriptions
if ([mMyAudioConverter formatRequiresPacketDescriptions]) {
mPacketDescriptions = (AudioStreamPacketDescription*)calloc(numPackets, sizeof(AudioStreamPacketDescription));
if (NULL == mPacketDescriptions) {
err = memFullErr;
goto bail;
}
}
// tell out custom audio converter class about the output buffer, that's where it's going to put the converted audio
[mMyAudioConverter setOutputAudioBufferList:mOutputBufferList];
}
// make sure we don't try to convert more than we allocated room for
if (0 == outputASBD->mBytesPerPacket) {
if (numPackets > (mOutputBufferSize / mMaxPacketSize)) {
numPackets = mOutputBufferSize / mMaxPacketSize;
}
} else {
if (numPackets > (mOutputBufferSize / outputASBD->mBytesPerPacket)) {
numPackets = mOutputBufferSize / outputASBD->mBytesPerPacket;
}
}
// set up the buffer list each time through
mOutputBufferList->mNumberBuffers = 1;
mOutputBufferList->mBuffers[0].mNumberChannels = outputASBD->mChannelsPerFrame;
mOutputBufferList->mBuffers[0].mDataByteSize = mOutputBufferSize;
mOutputBufferList->mBuffers[0].mData = mOutputBuffer;
err = [mMyAudioConverter convert:&numPackets :mPacketDescriptions :self];
if (err) goto bail;
numFrames = numPackets * outputASBD->mFramesPerPacket;
// we have completed the conversion when AudioConverterFillComplexBuffer returns zero packets
mConversionComplete = (numPackets == 0);
// write it to the movie file
if (numPackets > 0) {
// if the format requires packet descriptions, we need to add them one at a time
// packet descriptions describe the packet layout of a buffer of data where the size of
// each packet may not be the same or where there is extraneous data between packets
if (mPacketDescriptions) {
for (i = 0; i < numPackets; i++) {
err = AddMediaSample2(mSoundMedia, // the Media
mOutputBufferList->mBuffers[0].mData + mPacketDescriptions[i].mStartOffset, // const UInt8 * dataIn
mPacketDescriptions[i].mDataByteSize, // ByteCount size
(mPacketDescriptions[i].mVariableFramesInPacket ? mPacketDescriptions[i].mVariableFramesInPacket : outputASBD->mFramesPerPacket), // TimeValue64 decodeDurationPerSample
0, // TimeValue64 displayOffset
(SampleDescriptionHandle)mSoundDescription, // SampleDescriptionHandle sampleDescriptionH
1, // ItemCount numberOfSamples
0, // MediaSampleFlags sampleFlags
NULL); // TimeValue64 * sampleDecodeTimeOut
if (err) goto bail;
}
} else {
// numSamples should be the same as numFrames calculated above
UInt32 numSamples = (mOutputBufferList->mBuffers[0].mDataByteSize / outputASBD->mBytesPerPacket) * outputASBD->mFramesPerPacket;
// make believe the frames in each packet are individually accessible (decodeDurationPerSample == 1)
// this is commonly known as "THE LIE" and while it is the truth for PCM it is a lie for all CBR compressed formats
err = AddMediaSample2(mSoundMedia, // the Media
mOutputBufferList->mBuffers[0].mData, // const UInt8 * dataIn
mOutputBufferList->mBuffers[0].mDataByteSize, // ByteCount size
1, // TimeValue64 decodeDurationPerSample
0, // TimeValue64 displayOffset
(SampleDescriptionHandle)mSoundDescription, // SampleDescriptionHandle sampleDescriptionH
numSamples, // ItemCount numberOfSamples
0, // MediaSampleFlags sampleFlags
NULL); // TimeValue64 * sampleDecodeTimeOut
if (err) goto bail;
}
mLocationInFile += numPackets;
}
bail:
if (err) numFrames = 0;
*ioNumFrames = numFrames;
return err;
}
// this method prepare the specified movie for extraction by opening an extraction session, configuring
// and setting the output ASBD and the output layout if one exists - it also sets the start time to 0
// and calculates the total number of samples to export
- (OSStatus) configureExtractionSessionWithMovie:(Movie)inMovie
{
OSStatus err;
// open a movie audio extraction session
err = MovieAudioExtractionBegin(inMovie, 0, &mAudioExtractionSession);
if (err) goto bail;
// set the extraction ASBD
err = MovieAudioExtractionSetProperty(mAudioExtractionSession,
kQTPropertyClass_MovieAudioExtraction_Audio,
kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
sizeof(AudioStreamBasicDescription),
[mMyAudioConverter inputFormat]);
if (err) goto bail;
// set the extraction channel layout
err = MovieAudioExtractionSetProperty(mAudioExtractionSession,
kQTPropertyClass_MovieAudioExtraction_Audio,
kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
[mMyAudioConverter channelLayoutSize],
[mMyAudioConverter channelLayout]);
if (err) goto bail;
// set the chosen render quality - this is the same quality value set on the Audio Converter
err = MovieAudioExtractionSetProperty(mAudioExtractionSession,
kQTPropertyClass_MovieAudioExtraction_Audio,
kQTMovieAudioExtractionAudioPropertyID_RenderQuality,
sizeof(UInt32), [mMyAudioConverter renderQuality]);
if (err) goto bail;
// set the extraction start time - we always start at zero, but you don't have to
// this is the default but we set it anyway for completeness
TimeRecord startTime = { 0, 0, GetMovieTimeScale(inMovie), GetMovieTimeBase(inMovie) };
err = MovieAudioExtractionSetProperty(mAudioExtractionSession,
kQTPropertyClass_MovieAudioExtraction_Movie,
kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
sizeof(TimeRecord), &startTime);
if (err) goto bail;
bail:
return err;
}
// create and configure the output file
- (OSStatus)createOutputFile:(AudioStreamBasicDescription *)inOutputASBD
{
Handle outputMovieDataRef;
OSType outputMovieDataRefType;
CFStringRef outputMovieFullPathString;
OSStatus err;
err = QTNewDataReferenceFromFSRefCFString(&mParentRef, (CFStringRef)mFileName, 0, &outputMovieDataRef, &outputMovieDataRefType);
if (err) goto bail;
// create a new movie file.
// If you're using CreateMovieFile, consider switching to CreateMovieStorage, which is long-file-name aware and besides, FSSpecs are dead
err = CreateMovieStorage(outputMovieDataRef, outputMovieDataRefType, 'TVOD', 0, createMovieFileDeleteCurFile, &mOutputMovieStorageDH, &mOutputMovie);
if (err) goto bail;
// remember a URL for the movie file so we can open it in QuickTime Player after export is complete
err = QTGetDataReferenceFullPathCFString(outputMovieDataRef, outputMovieDataRefType, kQTPOSIXPathStyle, &outputMovieFullPathString);
if (err) goto bail;
mOutputMovieFileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, outputMovieFullPathString, kCFURLPOSIXPathStyle, false);
err = QTSoundDescriptionCreate([mMyAudioConverter outputFormat],
[mMyAudioConverter channelLayout], [mMyAudioConverter channelLayoutSize],
[mMyAudioConverter magicCookie], [mMyAudioConverter magicCookieSize],
kQTSoundDescriptionKind_Movie_LowestPossibleVersion, &mSoundDescription);
if (err) goto bail;
// create the sound track
Track track = NewMovieTrack(mOutputMovie, 0, 0, kFullVolume);
if (err = GetMoviesError()) goto bail;
mSoundMedia = NewTrackMedia(track, SoundMediaType, (TimeScale)inOutputASBD->mSampleRate, NULL, 0);
if (err = GetMoviesError()) goto bail;
err = BeginMediaEdits(mSoundMedia);
bail:
if (outputMovieDataRef) DisposeHandle(outputMovieDataRef);
if (outputMovieFullPathString) CFRelease(outputMovieFullPathString);
return err;
}
// calculate the duration of the longest audio track in the movie
// if the audio tracks end at time N and the movie is much
// longer we don't want to keep converting - the Movie Audio Extration
// (the API we're using to provide source) will happily
// return zeroes until it reaches the movie duration
- (void)setMovieConversionDuration
{
TimeValue maxDuration = 0;
UInt8 i;
SInt32 trackCount = GetMovieTrackCount([mQTMovie quickTimeMovie]);
if (trackCount) {
for (i = 1; i < trackCount + 1; i++) {
Track aTrack = GetMovieIndTrackType([mQTMovie quickTimeMovie],
i,
SoundMediaType,
movieTrackMediaType);
if (aTrack) {
TimeValue aDuration = GetTrackDuration(aTrack);
if (aDuration > maxDuration) maxDuration = aDuration;
}
}
mMovieDuration = (Float64)maxDuration / (Float64)GetMovieTimeScale([mQTMovie quickTimeMovie]);
}
}
// this completion method gets called at the end of the extraction session or may be called
// earlier if an error has occured - its main purpose is to clean up the world so a MovieWriter