4a8a06134c827e5d25144d3938b3ee9548bba48d
[blender.git] / source / blender / quicktime / apple / qtkit_export.m
1 /*
2  * Code to create QuickTime Movies with Blender
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  *
20  * The Original Code is written by Rob Haarsma (phase)
21  *
22  * Contributor(s): Stefan Gartner (sgefant)
23  *                                 Damien Plisson 11/2009
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #ifdef WITH_QUICKTIME
29 #if defined(_WIN32) || defined(__APPLE__)
30
31 #include <stdio.h>
32 #include <string.h>
33
34 #include "DNA_scene_types.h"
35 #include "DNA_userdef_types.h"
36
37 #ifdef WITH_AUDASPACE
38 #  include "AUD_C-API.h"
39 #endif
40
41 #include "BKE_global.h"
42 #include "BKE_main.h"
43 #include "BKE_scene.h"
44 #include "BKE_report.h"
45
46 #include "BLI_blenlib.h"
47
48 #include "BLO_sys_types.h"
49
50 #include "IMB_imbuf.h"
51 #include "IMB_imbuf_types.h"
52
53 #include "MEM_guardedalloc.h"
54
55 #ifdef __APPLE__
56 /* evil */
57 #ifndef __AIFF__
58 #define __AIFF__
59 #endif
60 #import <Cocoa/Cocoa.h>
61 #import <QTKit/QTKit.h>
62 #include <AudioToolbox/AudioToolbox.h>
63
64 #if MAC_OS_X_VERSION_MIN_REQUIRED <= 1040
65 #error OSX 10.5 minimum is needed for QTKit
66 #endif
67
68 #include "quicktime_import.h"
69 #include "quicktime_export.h"
70
71 #endif /* __APPLE__ */
72
73 typedef struct QuicktimeExport {
74         QTMovie *movie;
75         
76         NSString *filename;
77
78         QTTime frameDuration;
79         NSDictionary *frameAttributes;
80         
81         NSString *videoTempFileName;
82         /* Audio section */
83         AUD_Device *audioInputDevice;
84         AudioFileID audioFile;
85         NSString *audioFileName;
86         AudioConverterRef audioConverter;
87         AudioBufferList audioBufferList;
88         AudioStreamBasicDescription audioInputFormat, audioOutputFormat;
89         AudioStreamPacketDescription *audioOutputPktDesc;
90         SInt64 audioFilePos;
91         char *audioInputBuffer;
92         char *audioOutputBuffer;
93         UInt32 audioCodecMaxOutputPacketSize;
94         UInt64 audioTotalExportedFrames, audioTotalSavedFrames;
95         UInt64 audioLastFrame;
96         SInt64 audioOutputPktPos;
97         
98 } QuicktimeExport;
99
100 static struct QuicktimeExport *qtexport;
101
102 #define AUDIOOUTPUTBUFFERSIZE 65536
103
104 #pragma mark rna helper functions
105
106 /* Video codec */
107 static QuicktimeCodecTypeDesc qtVideoCodecList[] = {
108         {kRawCodecType, 1, "Uncompressed"},
109         {k422YpCbCr8CodecType, 2, "Uncompressed 8-bit 4:2:2"},
110         {k422YpCbCr10CodecType, 3, "Uncompressed 10-bit 4:2:2"},
111         {kComponentVideoCodecType, 4, "Component Video"},
112         {kPixletCodecType, 5, "Pixlet"},
113         {kPNGCodecType, 6, "PNG"},
114         {kJPEGCodecType, 7, "JPEG"},
115         {kMotionJPEGACodecType, 8, "M-JPEG A"},
116         {kMotionJPEGBCodecType, 9, "M-JPEG B"},
117         {kDVCPALCodecType, 10, "DV PAL"},
118         {kDVCNTSCCodecType, 11, "DV/DVCPRO NTSC"},
119         {kDVCPROHD720pCodecType, 12, "DVCPRO HD 720p"},
120         {kDVCPROHD1080i50CodecType, 13, "DVCPRO HD 1080i50"},
121         {kDVCPROHD1080i60CodecType, 14, "DVCPRO HD 1080i60"},
122         {kMPEG4VisualCodecType, 15, "MPEG4"},
123         {kH263CodecType, 16, "H.263"},
124         {kH264CodecType, 17, "H.264"},
125         {kAnimationCodecType, 18, "Animation"},
126         {0,0,NULL}};
127
128 static int qtVideoCodecCount = 18;
129
130 int quicktime_get_num_videocodecs()
131 {
132         return qtVideoCodecCount;
133 }
134
135 QuicktimeCodecTypeDesc* quicktime_get_videocodecType_desc(int indexValue)
136 {
137         if ((indexValue>=0) && (indexValue < qtVideoCodecCount))
138                 return &qtVideoCodecList[indexValue];
139         else
140                 return NULL;
141 }
142
143 int quicktime_rnatmpvalue_from_videocodectype(int codecType)
144 {
145         int i;
146         for (i = 0; i < qtVideoCodecCount; i++) {
147                 if (qtVideoCodecList[i].codecType == codecType)
148                         return qtVideoCodecList[i].rnatmpvalue;
149         }
150
151         return 0;
152 }
153
154 int quicktime_videocodecType_from_rnatmpvalue(int rnatmpvalue)
155 {
156         int i;
157         for (i = 0; i < qtVideoCodecCount; i++) {
158                 if (qtVideoCodecList[i].rnatmpvalue == rnatmpvalue)
159                         return qtVideoCodecList[i].codecType;
160         }
161         
162         return 0;
163 }
164
165 /* Audio codec */
166 static QuicktimeCodecTypeDesc qtAudioCodecList[] = {
167         {0, 0, "No audio"},
168         {kAudioFormatLinearPCM, 1, "LPCM"},
169         {kAudioFormatAppleLossless, 2, "Apple Lossless"},
170         {kAudioFormatMPEG4AAC, 3, "AAC"},
171         {0,0,NULL}};
172
173 static int qtAudioCodecCount = 4;
174
175 int quicktime_get_num_audiocodecs()
176 {
177         return qtAudioCodecCount;
178 }
179
180 QuicktimeCodecTypeDesc* quicktime_get_audiocodecType_desc(int indexValue)
181 {
182         if ((indexValue>=0) && (indexValue < qtAudioCodecCount))
183                 return &qtAudioCodecList[indexValue];
184         else
185                 return NULL;
186 }
187
188 int quicktime_rnatmpvalue_from_audiocodectype(int codecType)
189 {
190         int i;
191         for (i = 0; i < qtAudioCodecCount; i++) {
192                 if (qtAudioCodecList[i].codecType == codecType)
193                         return qtAudioCodecList[i].rnatmpvalue;
194         }
195         
196         return 0;
197 }
198
199 int quicktime_audiocodecType_from_rnatmpvalue(int rnatmpvalue)
200 {
201         int i;
202         for (i = 0; i < qtAudioCodecCount; i++) {
203                 if (qtAudioCodecList[i].rnatmpvalue == rnatmpvalue)
204                         return qtAudioCodecList[i].codecType;
205         }
206         
207         return 0;
208 }
209
210
211 static NSString *stringWithCodecType(int codecType)
212 {
213         char str[5];
214         
215         *((int *)str) = EndianU32_NtoB(codecType);
216         str[4] = 0;
217         
218         return [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
219 }
220
221 void makeqtstring (RenderData *rd, char *string)
222 {
223         char txt[64];
224
225         strcpy(string, rd->pic);
226         BLI_path_abs(string, G.main->name);
227
228         BLI_make_existing_file(string);
229
230         if (BLI_strcasecmp(string + strlen(string) - 4, ".mov")) {
231                 sprintf(txt, "%04d-%04d.mov", (rd->sfra) , (rd->efra) );
232                 strcat(string, txt);
233         }
234 }
235
236 void filepath_qt(char *string, RenderData *rd)
237 {
238         if (string == NULL) return;
239         
240         strcpy(string, rd->pic);
241         BLI_path_abs(string, G.main->name);
242         
243         BLI_make_existing_file(string);
244         
245         if (!BLI_testextensie(string, ".mov")) {
246                 /* if we don't have any #'s to insert numbers into, use 4 numbers by default */
247                 if (strchr(string, '#')==NULL)
248                         strcat(string, "####"); /* 4 numbers */
249
250                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
251                 strcat(string, ".mov");
252         }
253 }
254
255
256 #pragma mark audio export functions
257
258 static OSStatus write_cookie(AudioConverterRef converter, AudioFileID outfile)
259 {
260         // grab the cookie from the converter and write it to the file
261         UInt32 cookieSize = 0;
262         OSStatus err = AudioConverterGetPropertyInfo(converter, kAudioConverterCompressionMagicCookie, &cookieSize, NULL);
263         // if there is an error here, then the format doesn't have a cookie, so on we go
264         if (!err && cookieSize) {
265                 char* cookie = malloc(cookieSize);
266                 
267                 err = AudioConverterGetProperty(converter, kAudioConverterCompressionMagicCookie, &cookieSize, cookie);
268                 
269                 if (!err)
270                         err = AudioFileSetProperty (outfile, kAudioFilePropertyMagicCookieData, cookieSize, cookie);
271                         // even though some formats have cookies, some files don't take them
272                 
273                 free(cookie);
274         }
275         return err;
276 }
277
278 /* AudioConverter input stream callback */
279 static OSStatus AudioConverterInputCallback(AudioConverterRef inAudioConverter, 
280                                                  UInt32* ioNumberDataPackets,
281                                                  AudioBufferList* ioData,
282                                                  AudioStreamPacketDescription** outDataPacketDescription,
283                                                  void* inUserData)
284 {       
285         if (qtexport->audioTotalExportedFrames >= qtexport->audioLastFrame) { /* EOF */
286                 *ioNumberDataPackets = 0;
287                 return noErr;
288         }
289
290         if (qtexport->audioInputFormat.mBytesPerPacket * *ioNumberDataPackets > AUDIOOUTPUTBUFFERSIZE)
291                 *ioNumberDataPackets = AUDIOOUTPUTBUFFERSIZE / qtexport->audioInputFormat.mBytesPerPacket;
292         
293         if ((qtexport->audioTotalExportedFrames + *ioNumberDataPackets) > qtexport->audioLastFrame)
294                 *ioNumberDataPackets = (qtexport->audioLastFrame - qtexport->audioTotalExportedFrames) / qtexport->audioInputFormat.mFramesPerPacket;
295         
296         qtexport->audioTotalExportedFrames += *ioNumberDataPackets;
297         
298         AUD_readDevice(qtexport->audioInputDevice, (UInt8*)qtexport->audioInputBuffer, 
299                                    qtexport->audioInputFormat.mFramesPerPacket * *ioNumberDataPackets);
300         
301         ioData->mBuffers[0].mDataByteSize = qtexport->audioInputFormat.mBytesPerPacket * *ioNumberDataPackets;
302         ioData->mBuffers[0].mData = qtexport->audioInputBuffer;
303         ioData->mBuffers[0].mNumberChannels = qtexport->audioInputFormat.mChannelsPerFrame;
304         
305         return noErr;
306 }       
307
308
309 #pragma mark export functions
310
311 int start_qt(struct Scene *scene, struct RenderData *rd, int rectx, int recty, ReportList *reports)
312 {
313         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
314         NSError *error;
315         char name[1024];
316         int success = 1;
317         OSStatus err = noErr;
318
319         if(qtexport == NULL) qtexport = MEM_callocN(sizeof(QuicktimeExport), "QuicktimeExport");
320         
321         [QTMovie enterQTKitOnThread];
322         
323         /* Check first if the QuickTime 7.2.1 initToWritableFile: method is available */
324         if ([[[[QTMovie alloc] init] autorelease] respondsToSelector:@selector(initToWritableFile:error:)] != YES) {
325                 BKE_report(reports, RPT_ERROR, "\nUnable to create quicktime movie, need Quicktime rev 7.2.1 or later");
326                 success = 0;
327         }
328         else {
329                 makeqtstring(rd, name);
330                 qtexport->filename = [[NSString alloc] initWithCString:name
331                                                                        encoding:[NSString defaultCStringEncoding]];
332                 qtexport->movie = nil;
333                 qtexport->audioFile = NULL;
334
335                 if (rd->qtcodecsettings.audiocodecType) {
336                         // generate a name for our video & audio files
337                         /* Init audio file */
338                         CFURLRef outputFileURL;
339                         char extension[32];
340                         AudioFileTypeID audioFileType;
341                         
342                         switch (rd->qtcodecsettings.audiocodecType) {
343                                 case kAudioFormatLinearPCM:
344                                         audioFileType = kAudioFileWAVEType;
345                                         strcpy(extension,".wav");
346                                         break;
347                                 case kAudioFormatMPEG4AAC:
348                                 case kAudioFormatAppleLossless:
349                                         audioFileType = kAudioFileM4AType;
350                                         strcpy(extension, ".m4a");
351                                         break;
352                                 default:
353                                         audioFileType = kAudioFileAIFFType;
354                                         strcpy(extension,".aiff");
355                                         break;
356                         }
357
358                         tmpnam(name);
359                         strcat(name, extension);
360                         outputFileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,(UInt8*) name, strlen(name), false);
361                         
362                         if (outputFileURL) {
363                                 
364                                 qtexport->audioFileName = [[NSString alloc] initWithCString:name
365                                                                                             encoding:[NSString defaultCStringEncoding]];
366                                 
367                                 qtexport->audioInputFormat.mSampleRate = U.audiorate;
368                                 qtexport->audioInputFormat.mFormatID = kAudioFormatLinearPCM;
369                                 qtexport->audioInputFormat.mChannelsPerFrame = U.audiochannels;
370                                 switch (U.audioformat) {
371                                         case AUD_FORMAT_U8:
372                                                 qtexport->audioInputFormat.mBitsPerChannel = 8;
373                                                 qtexport->audioInputFormat.mFormatFlags = 0;
374                                                 break;
375                                         case AUD_FORMAT_S24:
376                                                 qtexport->audioInputFormat.mBitsPerChannel = 24;
377                                                 qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
378                                                 break;
379                                         case AUD_FORMAT_S32:
380                                                 qtexport->audioInputFormat.mBitsPerChannel = 32;
381                                                 qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
382                                                 break;
383                                         case AUD_FORMAT_FLOAT32:
384                                                 qtexport->audioInputFormat.mBitsPerChannel = 32;
385                                                 qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
386                                                 break;
387                                         case AUD_FORMAT_FLOAT64:
388                                                 qtexport->audioInputFormat.mBitsPerChannel = 64;
389                                                 qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
390                                                 break;
391                                         case AUD_FORMAT_S16:
392                                         default:
393                                                 qtexport->audioInputFormat.mBitsPerChannel = 16;
394                                                 qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
395                                                 break;
396                                 }
397                                 qtexport->audioInputFormat.mBytesPerFrame = qtexport->audioInputFormat.mChannelsPerFrame * qtexport->audioInputFormat.mBitsPerChannel / 8;
398                                 qtexport->audioInputFormat.mFramesPerPacket = 1; /*If not ==1, then need to check input callback for "rounding" issues"*/
399                                 qtexport->audioInputFormat.mBytesPerPacket = qtexport->audioInputFormat.mBytesPerFrame;
400                                 qtexport->audioInputFormat.mFormatFlags |= kLinearPCMFormatFlagIsPacked;
401                                 
402                                 
403                                 /*Output format*/
404                                 qtexport->audioOutputFormat.mFormatID = rd->qtcodecsettings.audiocodecType;
405                                 //TODO: set audio channels
406                                 qtexport->audioOutputFormat.mChannelsPerFrame = 2;
407                                 qtexport->audioOutputFormat.mSampleRate = rd->qtcodecsettings.audioSampleRate;
408                                 
409                                 /* Default value for compressed formats, overridden after if not the case */
410                                 qtexport->audioOutputFormat.mFramesPerPacket = 0;
411                                 qtexport->audioOutputFormat.mBytesPerFrame = 0;
412                                 qtexport->audioOutputFormat.mBytesPerPacket = 0;
413                                 qtexport->audioOutputFormat.mBitsPerChannel = 0;
414
415                                 switch (rd->qtcodecsettings.audiocodecType) {
416                                         case kAudioFormatMPEG4AAC:
417                                                 qtexport->audioOutputFormat.mFormatFlags = kMPEG4Object_AAC_Main;
418                                                 /* AAC codec does not handle sample rates above 48kHz, force this limit instead of getting an error afterwards */
419                                                 if (qtexport->audioOutputFormat.mSampleRate > 48000) qtexport->audioOutputFormat.mSampleRate = 48000;
420                                                 break;
421                                         case kAudioFormatAppleLossless:
422                                                 switch (U.audioformat) {
423                                                         case AUD_FORMAT_S16:
424                                                                 qtexport->audioOutputFormat.mFormatFlags = kAppleLosslessFormatFlag_16BitSourceData;
425                                                                 break;
426                                                         case AUD_FORMAT_S24:
427                                                                 qtexport->audioOutputFormat.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData;
428                                                                 break;
429                                                         case AUD_FORMAT_S32:
430                                                                 qtexport->audioOutputFormat.mFormatFlags = kAppleLosslessFormatFlag_32BitSourceData;
431                                                                 break;
432                                                         case AUD_FORMAT_U8:
433                                                         case AUD_FORMAT_FLOAT32:
434                                                         case AUD_FORMAT_FLOAT64:
435                                                         default:
436                                                                 break;
437                                                 }
438                                                 break;
439                                         case kAudioFormatLinearPCM:
440                                         default:
441                                                 switch (rd->qtcodecsettings.audioBitDepth) {
442                                                         case AUD_FORMAT_U8:
443                                                                 qtexport->audioOutputFormat.mBitsPerChannel = 8;
444                                                                 qtexport->audioOutputFormat.mFormatFlags = 0;
445                                                                 break;
446                                                         case AUD_FORMAT_S24:
447                                                                 qtexport->audioOutputFormat.mBitsPerChannel = 24;
448                                                                 qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
449                                                                 break;
450                                                         case AUD_FORMAT_S32:
451                                                                 qtexport->audioOutputFormat.mBitsPerChannel = 32;
452                                                                 qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
453                                                                 break;
454                                                         case AUD_FORMAT_FLOAT32:
455                                                                 qtexport->audioOutputFormat.mBitsPerChannel = 32;
456                                                                 qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
457                                                                 break;
458                                                         case AUD_FORMAT_FLOAT64:
459                                                                 qtexport->audioOutputFormat.mBitsPerChannel = 64;
460                                                                 qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
461                                                                 break;
462                                                         case AUD_FORMAT_S16:
463                                                         default:
464                                                                 qtexport->audioOutputFormat.mBitsPerChannel = 16;
465                                                                 qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
466                                                                 break;
467                                                 }
468                                                 qtexport->audioOutputFormat.mFormatFlags |= kLinearPCMFormatFlagIsPacked;
469                                                 qtexport->audioOutputFormat.mBytesPerPacket = qtexport->audioOutputFormat.mChannelsPerFrame * (qtexport->audioOutputFormat.mBitsPerChannel / 8);
470                                                 qtexport->audioOutputFormat.mFramesPerPacket = 1;
471                                                 qtexport->audioOutputFormat.mBytesPerFrame = qtexport->audioOutputFormat.mBytesPerPacket;
472                                                 break;
473                                 }
474
475                                 err = AudioFileCreateWithURL(outputFileURL, audioFileType, &qtexport->audioOutputFormat, kAudioFileFlags_EraseFile, &qtexport->audioFile);
476                                 CFRelease(outputFileURL);
477                                 
478                                 if(err)
479                                         BKE_report(reports, RPT_ERROR, "\nQuicktime: unable to create temporary audio file. Format error ?");
480                                 else {
481                                         err = AudioConverterNew(&qtexport->audioInputFormat, &qtexport->audioOutputFormat, &qtexport->audioConverter);
482                                         if (err) {
483                                                 BKE_report(reports, RPT_ERROR, "\nQuicktime: unable to initialize audio codec converter. Format error ?");
484                                                 AudioFileClose(qtexport->audioFile);
485                                                 qtexport->audioFile = NULL;
486                                                 [qtexport->audioFileName release];
487                                                 qtexport->audioFileName = nil;
488                                         }
489                                         else {
490                                                 UInt32 prop,propSize;
491                                                 /* Set up codec properties */
492                                                 if (rd->qtcodecsettings.audiocodecType == kAudioFormatMPEG4AAC) {  /* Lossy compressed format */
493                                                         prop = rd->qtcodecsettings.audioBitRate;
494                                                         AudioConverterSetProperty(qtexport->audioConverter, kAudioConverterEncodeBitRate,
495                                                                                   sizeof(prop), &prop);
496                                                         
497                                                         if (rd->qtcodecsettings.audioCodecFlags & QTAUDIO_FLAG_CODEC_ISCBR)
498                                                                 prop = kAudioCodecBitRateControlMode_Constant;
499                                                         else
500                                                                 prop = kAudioCodecBitRateControlMode_LongTermAverage;
501                                                         AudioConverterSetProperty(qtexport->audioConverter, kAudioCodecPropertyBitRateControlMode,
502                                                                                   sizeof(prop), &prop);
503                                                 }
504                                                 /* Conversion quality : if performance impact then offer degraded option */
505                                                 if ((rd->qtcodecsettings.audioCodecFlags & QTAUDIO_FLAG_RESAMPLE_NOHQ) == 0) {
506                                                         prop = kAudioConverterSampleRateConverterComplexity_Mastering;
507                                                         AudioConverterSetProperty(qtexport->audioConverter, kAudioConverterSampleRateConverterComplexity,
508                                                                                   sizeof(prop), &prop);
509                                                         
510                                                         prop = kAudioConverterQuality_Max;
511                                                         AudioConverterSetProperty(qtexport->audioConverter, kAudioConverterSampleRateConverterQuality,
512                                                                                   sizeof(prop), &prop);
513                                                 }
514                                                 
515                                                 write_cookie(qtexport->audioConverter, qtexport->audioFile);
516                                                 
517                                                 /* Allocate output buffer */
518                                                 if (qtexport->audioOutputFormat.mBytesPerPacket ==0) /* VBR */
519                                                         AudioConverterGetProperty(qtexport->audioConverter, kAudioConverterPropertyMaximumOutputPacketSize,
520                                                                                   &propSize, &qtexport->audioCodecMaxOutputPacketSize);
521                                                 else
522                                                         qtexport->audioCodecMaxOutputPacketSize = qtexport->audioOutputFormat.mBytesPerPacket;
523                                                 
524                                                 qtexport->audioInputBuffer = MEM_mallocN(AUDIOOUTPUTBUFFERSIZE, "qt_audio_inputPacket");
525                                                 qtexport->audioOutputBuffer = MEM_mallocN(AUDIOOUTPUTBUFFERSIZE, "qt_audio_outputPacket");
526                                                 qtexport->audioOutputPktDesc = MEM_mallocN(sizeof(AudioStreamPacketDescription) * AUDIOOUTPUTBUFFERSIZE / qtexport->audioCodecMaxOutputPacketSize,
527                                                                                            "qt_audio_pktdesc");
528                                         }
529                                 }
530                         }
531
532                         if (err == noErr) {
533                                 qtexport->videoTempFileName = [[NSString alloc] initWithCString:tmpnam(nil)
534                                                                                 encoding:[NSString defaultCStringEncoding]];
535                                 if (qtexport->videoTempFileName) {
536                                         qtexport->movie = [[QTMovie alloc] initToWritableFile:qtexport->videoTempFileName error:&error];
537                                 }
538
539                         }
540                 }
541                 else
542                         qtexport->movie = [[QTMovie alloc] initToWritableFile:qtexport->filename error:&error];
543
544                 if(qtexport->movie == nil) {
545                         BKE_report(reports, RPT_ERROR, "Unable to create quicktime movie.");
546                         success = 0;
547                         if (qtexport->filename) [qtexport->filename release];
548                         qtexport->filename = nil;
549                         if (qtexport->audioFileName) [qtexport->audioFileName release];
550                         qtexport->audioFileName = nil;
551                         if (qtexport->videoTempFileName) [qtexport->videoTempFileName release];
552                         qtexport->videoTempFileName = nil;
553                         [QTMovie exitQTKitOnThread];
554                 }
555                 else {
556                         [qtexport->movie retain];
557                         [qtexport->movie setAttribute:[NSNumber numberWithBool:YES] forKey:QTMovieEditableAttribute];
558                         [qtexport->movie setAttribute:@"Made with Blender" forKey:QTMovieCopyrightAttribute];
559                         
560                         qtexport->frameDuration = QTMakeTime(rd->frs_sec_base * 1000, rd->frs_sec * 1000);
561                         
562                         /* specifying the codec attributes : try to retrieve them from render data first*/
563                         if (rd->qtcodecsettings.codecType) {
564                                 qtexport->frameAttributes = [
565                                         NSDictionary dictionaryWithObjectsAndKeys:
566                                         stringWithCodecType(rd->qtcodecsettings.codecType),
567                                         QTAddImageCodecType,
568                                         [NSNumber numberWithLong:((rd->qtcodecsettings.codecSpatialQuality)*codecLosslessQuality)/100],
569                                         QTAddImageCodecQuality,
570                                         nil];
571                         }
572                         else {
573                                 qtexport->frameAttributes = [
574                                         NSDictionary dictionaryWithObjectsAndKeys:@"jpeg",
575                                         QTAddImageCodecType,
576                                         [NSNumber numberWithLong:codecHighQuality],
577                                         QTAddImageCodecQuality,
578                                         nil];
579                         }
580                         [qtexport->frameAttributes retain];
581                         
582                         if (qtexport->audioFile) {
583                                 /* Init audio input stream */
584                                 AUD_DeviceSpecs specs;
585
586                                 specs.channels = U.audiochannels;
587                                 specs.format = U.audioformat;
588                                 specs.rate = U.audiorate;
589                                 qtexport->audioInputDevice = AUD_openReadDevice(specs);
590                                 AUD_playDevice(qtexport->audioInputDevice, scene->sound_scene, rd->sfra * rd->frs_sec_base / rd->frs_sec);
591
592                                 qtexport->audioOutputPktPos = 0;
593                                 qtexport->audioTotalExportedFrames = 0;
594                                 qtexport->audioTotalSavedFrames = 0;
595                                 
596                                 qtexport->audioLastFrame = (rd->efra - rd->sfra) * qtexport->audioInputFormat.mSampleRate * rd->frs_sec_base / rd->frs_sec;
597                         }
598                 }
599         }
600         
601         [pool drain];
602
603         return success;
604 }
605
606 int append_qt(struct RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
607 {
608         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
609         NSBitmapImageRep *blBitmapFormatImage;
610         NSImage *frameImage;
611         OSStatus err = noErr;
612         unsigned char *from_Ptr,*to_Ptr;
613         int y,from_i,to_i;
614         
615         /* Create bitmap image rep in blender format (32bit RGBA) */
616         blBitmapFormatImage = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
617                                                                                                                                   pixelsWide:rectx 
618                                                                                                                                   pixelsHigh:recty
619                                                                                                                            bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
620                                                                                                                           colorSpaceName:NSCalibratedRGBColorSpace 
621                                                                                                                                 bitmapFormat:NSAlphaNonpremultipliedBitmapFormat
622                                                                                                                                  bytesPerRow:rectx*4
623                                                                                                                                 bitsPerPixel:32];
624         if (!blBitmapFormatImage) {
625                 [pool drain];
626                 return 0;
627         }
628         
629         from_Ptr = (unsigned char *)pixels;
630         to_Ptr = (unsigned char *)[blBitmapFormatImage bitmapData];
631         for (y = 0; y < recty; y++) {
632                 to_i = (recty-y-1)*rectx;
633                 from_i = y*rectx;
634                 memcpy(to_Ptr+4*to_i, from_Ptr+4*from_i, 4*rectx);
635         }
636         
637         frameImage = [[NSImage alloc] initWithSize:NSMakeSize(rectx, recty)];
638         [frameImage addRepresentation:blBitmapFormatImage];
639         
640         /* Add the image to the movie clip */
641         [qtexport->movie addImage:frameImage
642                                   forDuration:qtexport->frameDuration
643                            withAttributes:qtexport->frameAttributes];
644
645         [blBitmapFormatImage release];
646         [frameImage release];
647         
648         
649         if (qtexport->audioFile) {
650                 UInt32 audioPacketsConverted;
651                 /* Append audio */
652                 while (qtexport->audioTotalExportedFrames < qtexport->audioLastFrame) {
653
654                         qtexport->audioBufferList.mNumberBuffers = 1;
655                         qtexport->audioBufferList.mBuffers[0].mNumberChannels = qtexport->audioOutputFormat.mChannelsPerFrame;
656                         qtexport->audioBufferList.mBuffers[0].mDataByteSize = AUDIOOUTPUTBUFFERSIZE;
657                         qtexport->audioBufferList.mBuffers[0].mData = qtexport->audioOutputBuffer;
658                         audioPacketsConverted = AUDIOOUTPUTBUFFERSIZE / qtexport->audioCodecMaxOutputPacketSize;
659                         
660                         err = AudioConverterFillComplexBuffer(qtexport->audioConverter, AudioConverterInputCallback,
661                                                               NULL, &audioPacketsConverted, &qtexport->audioBufferList, qtexport->audioOutputPktDesc);
662                         if (audioPacketsConverted) {
663                                 AudioFileWritePackets(qtexport->audioFile, false, qtexport->audioBufferList.mBuffers[0].mDataByteSize,
664                                         qtexport->audioOutputPktDesc, qtexport->audioOutputPktPos, &audioPacketsConverted, qtexport->audioOutputBuffer);
665                                 qtexport->audioOutputPktPos += audioPacketsConverted;
666                                 
667                                 if (qtexport->audioOutputFormat.mFramesPerPacket) {
668                                         // this is the common case: format has constant frames per packet
669                                         qtexport->audioTotalSavedFrames += (audioPacketsConverted * qtexport->audioOutputFormat.mFramesPerPacket);
670                                 }
671                                 else {
672                                         unsigned int i;
673                                         // if there are variable frames per packet, then we have to do this for each packeet
674                                         for (i = 0; i < audioPacketsConverted; ++i)
675                                                 qtexport->audioTotalSavedFrames += qtexport->audioOutputPktDesc[i].mVariableFramesInPacket;
676                                 }
677                                 
678                                 
679                         }
680                         else {
681                                 //Error getting audio packets
682                                 BKE_reportf(reports, RPT_ERROR, "Unable to get further audio packets from frame %i, error = 0x%x",(int)qtexport->audioTotalExportedFrames,err);
683                                 break;
684                         }
685
686                 }
687         }
688         [pool drain];
689
690         return 1;
691 }
692
693
694 void end_qt(void)
695 {
696         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
697         if (qtexport->movie) {
698                 
699                 if (qtexport->audioFile)
700                 {
701                         NSDictionary *dict = nil;
702                         QTMovie *audioTmpMovie = nil;
703                         NSError *error;
704                         NSFileManager *fileManager;
705                         
706                         /* Mux video and audio then save file */
707                         
708                         /* Write last frames for VBR files */
709                         if (qtexport->audioOutputFormat.mBitsPerChannel == 0) {
710                                 OSStatus err = noErr;
711                                 AudioConverterPrimeInfo primeInfo;
712                                 UInt32 primeSize = sizeof(primeInfo);
713                                 
714                                 err = AudioConverterGetProperty(qtexport->audioConverter, kAudioConverterPrimeInfo, &primeSize, &primeInfo);
715                                 if (err == noErr) {
716                                         // there's priming to write out to the file
717                                         AudioFilePacketTableInfo pti;
718                                         pti.mPrimingFrames = primeInfo.leadingFrames;
719                                         pti.mRemainderFrames = primeInfo.trailingFrames;
720                                         pti.mNumberValidFrames = qtexport->audioTotalSavedFrames - pti.mPrimingFrames - pti.mRemainderFrames;
721                                         AudioFileSetProperty(qtexport->audioFile, kAudioFilePropertyPacketTableInfo, sizeof(pti), &pti);
722                                 }
723                                 
724                         }
725                         
726                         write_cookie(qtexport->audioConverter, qtexport->audioFile);
727                         AudioConverterDispose(qtexport->audioConverter);
728                         AudioFileClose(qtexport->audioFile);
729                         AUD_closeReadDevice(qtexport->audioInputDevice);
730                         qtexport->audioFile = NULL;
731                         qtexport->audioInputDevice = NULL;
732                         MEM_freeN(qtexport->audioInputBuffer);
733                         MEM_freeN(qtexport->audioOutputBuffer);
734                         MEM_freeN(qtexport->audioOutputPktDesc);
735                         
736                         /* Reopen audio file and merge it */
737                         audioTmpMovie = [QTMovie movieWithFile:qtexport->audioFileName error:&error];
738                         if (audioTmpMovie) {
739                                 NSArray *audioTracks = [audioTmpMovie tracksOfMediaType:QTMediaTypeSound];
740                                 QTTrack *audioTrack = nil;
741                                 if( [audioTracks count] > 0 )
742                                 {
743                                         audioTrack = [audioTracks objectAtIndex:0];
744                                 }
745                         
746                                 if( audioTrack )
747                                 {
748                                         QTTimeRange totalRange;
749                                         totalRange.time = QTZeroTime;
750                                         totalRange.duration = [[audioTmpMovie attributeForKey:QTMovieDurationAttribute] QTTimeValue];
751                                         
752                                         [qtexport->movie insertSegmentOfTrack:audioTrack timeRange:totalRange atTime:QTZeroTime];
753                                 }
754                         }
755                         
756                         /* Save file */
757                         dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
758                                 forKey:QTMovieFlatten];
759
760                         if (dict) {
761                                 [qtexport->movie writeToFile:qtexport->filename withAttributes:dict];
762                         }
763                         
764                         /* Delete temp files */
765                         fileManager = [[NSFileManager alloc] init];
766                         [fileManager removeItemAtPath:qtexport->audioFileName error:&error];
767                         [fileManager removeItemAtPath:qtexport->videoTempFileName error:&error];
768                         [fileManager release];
769                 }
770                 else {
771                         /* Flush update of the movie file */
772                         [qtexport->movie updateMovieFile];
773                         
774                         [qtexport->movie invalidate];
775                 }
776                 
777                 /* Clean up movie structure */
778                 if (qtexport->filename) [qtexport->filename release];
779                 qtexport->filename = nil;
780                 if (qtexport->audioFileName) [qtexport->audioFileName release];
781                 qtexport->audioFileName = nil;
782                 if (qtexport->videoTempFileName) [qtexport->videoTempFileName release];
783                 qtexport->videoTempFileName = nil;
784                 [qtexport->frameAttributes release];
785                 [qtexport->movie release];
786         }
787         
788         [QTMovie exitQTKitOnThread];
789
790         if(qtexport) {
791                 MEM_freeN(qtexport);
792                 qtexport = NULL;
793         }
794         [pool drain];
795 }
796
797
798 void free_qtcomponentdata(void)
799 {
800 }
801
802 void quicktime_verify_image_type(RenderData *rd, ImageFormatData *imf)
803 {
804         if (imf->imtype == R_IMF_IMTYPE_QUICKTIME) {
805                 if ((rd->qtcodecsettings.codecType<= 0) ||
806                         (rd->qtcodecsettings.codecSpatialQuality <0) ||
807                         (rd->qtcodecsettings.codecSpatialQuality > 100)) {
808                         
809                         rd->qtcodecsettings.codecType = kJPEGCodecType;
810                         rd->qtcodecsettings.codecSpatialQuality = (codecHighQuality*100)/codecLosslessQuality;
811                 }
812                 if ((rd->qtcodecsettings.audioSampleRate < 21000) ||
813                         (rd->qtcodecsettings.audioSampleRate > 193000)) 
814                         rd->qtcodecsettings.audioSampleRate = 48000;
815                 
816                 if (rd->qtcodecsettings.audioBitDepth == 0)
817                         rd->qtcodecsettings.audioBitDepth = AUD_FORMAT_S16;
818                 
819                 if (rd->qtcodecsettings.audioBitRate == 0)
820                         rd->qtcodecsettings.audioBitRate = 256000;
821         }
822 }
823
824 #endif /* _WIN32 || __APPLE__ */
825 #endif /* WITH_QUICKTIME */
826