9d68e1d899c406b4af292d29126cff11905b65ca
[blender.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /*
2  *
3  * ffmpeg-write support
4  *
5  * Partial Copyright (c) 2006 Peter Schlaile
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  */
18
19 /** \file blender/blenkernel/intern/writeffmpeg.c
20  *  \ingroup bke
21  */
22
23 #ifdef WITH_FFMPEG
24 #include <string.h>
25 #include <stdio.h>
26
27 #if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
28 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
29 #if _MSC_VER < 1400
30 #include <stdint.h>
31 #endif
32 #endif
33
34 #include <stdlib.h>
35
36 #include <libavformat/avformat.h>
37 #include <libavcodec/avcodec.h>
38 #include <libavutil/rational.h>
39 #include <libswscale/swscale.h>
40 #include <libavcodec/opt.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_scene_types.h"
45
46 #include "BLI_blenlib.h"
47
48 #ifdef WITH_AUDASPACE
49 #  include "AUD_C-API.h"
50 #endif
51
52 #include "BLI_utildefines.h"
53
54 #include "BKE_global.h"
55 #include "BKE_idprop.h"
56 #include "BKE_main.h"
57 #include "BKE_report.h"
58 #include "BKE_sound.h"
59 #include "BKE_writeffmpeg.h"
60
61 #include "IMB_imbuf_types.h"
62 #include "IMB_imbuf.h"
63
64 #include "ffmpeg_compat.h"
65
66 extern void do_init_ffmpeg(void);
67
68 static int ffmpeg_type = 0;
69 static int ffmpeg_codec = CODEC_ID_MPEG4;
70 static int ffmpeg_audio_codec = CODEC_ID_NONE;
71 static int ffmpeg_video_bitrate = 1150;
72 static int ffmpeg_audio_bitrate = 128;
73 static int ffmpeg_gop_size = 12;
74 static int ffmpeg_autosplit = 0;
75 static int ffmpeg_autosplit_count = 0;
76
77 static AVFormatContext* outfile = 0;
78 static AVStream* video_stream = 0;
79 static AVStream* audio_stream = 0;
80 static AVFrame* current_frame = 0;
81 static struct SwsContext *img_convert_ctx = 0;
82
83 static uint8_t* video_buffer = 0;
84 static int video_buffersize = 0;
85
86 static uint8_t* audio_input_buffer = 0;
87 static int audio_input_samples = 0;
88 static uint8_t* audio_output_buffer = 0;
89 static int audio_outbuf_size = 0;
90 static double audio_time = 0.0f;
91
92 #ifdef WITH_AUDASPACE
93 static AUD_Device* audio_mixdown_device = 0;
94 #endif
95
96 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
97
98 /* Delete a picture buffer */
99
100 static void delete_picture(AVFrame* f)
101 {
102         if (f) {
103                 if (f->data[0]) MEM_freeN(f->data[0]);
104                 av_free(f);
105         }
106 }
107
108 #ifdef WITH_AUDASPACE
109 static int write_audio_frame(void) 
110 {
111         AVCodecContext* c = NULL;
112         AVPacket pkt;
113
114         c = audio_stream->codec;
115
116         av_init_packet(&pkt);
117         pkt.size = 0;
118
119         AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
120         audio_time += (double) audio_input_samples / (double) c->sample_rate;
121
122         pkt.size = avcodec_encode_audio(c, audio_output_buffer,
123                                         audio_outbuf_size,
124                                         (short*) audio_input_buffer);
125
126         if(pkt.size < 0)
127         {
128                 // XXX error("Error writing audio packet");
129                 return -1;
130         }
131
132         pkt.data = audio_output_buffer;
133
134         if(c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
135         {
136                 pkt.pts = av_rescale_q(c->coded_frame->pts,
137                                        c->time_base, audio_stream->time_base);
138                 fprintf(stderr, "Audio Frame PTS: %d\n", (int)pkt.pts);
139         }
140
141         pkt.stream_index = audio_stream->index;
142
143         pkt.flags |= AV_PKT_FLAG_KEY;
144
145         if (av_interleaved_write_frame(outfile, &pkt) != 0) {
146                 fprintf(stderr, "Error writing audio packet!\n");
147                 return -1;
148         }
149         return 0;
150 }
151 #endif // #ifdef WITH_AUDASPACE
152
153 /* Allocate a temporary frame */
154 static AVFrame* alloc_picture(int pix_fmt, int width, int height) 
155 {
156         AVFrame* f;
157         uint8_t* buf;
158         int size;
159         
160         /* allocate space for the struct */
161         f = avcodec_alloc_frame();
162         if (!f) return NULL;
163         size = avpicture_get_size(pix_fmt, width, height);
164         /* allocate the actual picture buffer */
165         buf = MEM_mallocN(size, "AVFrame buffer");
166         if (!buf) {
167                 free(f);
168                 return NULL;
169         }
170         avpicture_fill((AVPicture*)f, buf, pix_fmt, width, height);
171         return f;
172 }
173
174 /* Get the correct file extensions for the requested format,
175    first is always desired guess_format parameter */
176 static const char** get_file_extensions(int format) 
177 {
178         switch(format) {
179         case FFMPEG_DV: {
180                 static const char * rv[] = { ".dv", NULL };
181                 return rv;
182         }
183         case FFMPEG_MPEG1: {
184                 static const char * rv[] = { ".mpg", ".mpeg", NULL };
185                 return rv;
186         }
187         case FFMPEG_MPEG2: {
188                 static const char * rv[] = { ".dvd", ".vob", ".mpg", ".mpeg",
189                                                  NULL };
190                 return rv;
191         }
192         case FFMPEG_MPEG4: {
193                 static const char * rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
194                 return rv;
195         }
196         case FFMPEG_AVI: {
197                 static const char * rv[] = { ".avi", NULL };
198                 return rv;
199         }
200         case FFMPEG_MOV: {
201                 static const char * rv[] = { ".mov", NULL };
202                 return rv;
203         }
204         case FFMPEG_H264: {
205                 /* FIXME: avi for now... */
206                 static const char * rv[] = { ".avi", NULL };
207                 return rv;
208         }
209
210         case FFMPEG_XVID: {
211                 /* FIXME: avi for now... */
212                 static const char * rv[] = { ".avi", NULL };
213                 return rv;
214         }
215         case FFMPEG_FLV: {
216                 static const char * rv[] = { ".flv", NULL };
217                 return rv;
218         }
219         case FFMPEG_MKV: {
220                 static const char * rv[] = { ".mkv", NULL };
221                 return rv;
222         }
223         case FFMPEG_OGG: {
224                 static const char * rv[] = { ".ogg", ".ogv", NULL };
225                 return rv;
226         }
227         case FFMPEG_MP3: {
228                 static const char * rv[] = { ".mp3", NULL };
229                 return rv;
230         }
231         case FFMPEG_WAV: {
232                 static const char * rv[] = { ".wav", NULL };
233                 return rv;
234         }
235         default:
236                 return NULL;
237         }
238 }
239
240 /* Write a frame to the output file */
241 static int write_video_frame(RenderData *rd, int cfra, AVFrame* frame, ReportList *reports)
242 {
243         int outsize = 0;
244         int ret, success= 1;
245         AVCodecContext* c = video_stream->codec;
246
247         frame->pts = cfra;
248
249         if (rd->mode & R_FIELDS) {
250                 frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
251         }
252
253         outsize = avcodec_encode_video(c, video_buffer, video_buffersize, 
254                                            frame);
255
256         if (outsize > 0) {
257                 AVPacket packet;
258                 av_init_packet(&packet);
259
260                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
261                         packet.pts = av_rescale_q(c->coded_frame->pts,
262                                                   c->time_base,
263                                                   video_stream->time_base);
264                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
265                 } else {
266                         fprintf(stderr, "Video Frame PTS: not set\n");
267                 }
268                 if (c->coded_frame->key_frame)
269                         packet.flags |= AV_PKT_FLAG_KEY;
270                 packet.stream_index = video_stream->index;
271                 packet.data = video_buffer;
272                 packet.size = outsize;
273                 ret = av_interleaved_write_frame(outfile, &packet);
274                 success = (ret == 0);
275         } else if (outsize < 0) {
276                 success = 0;
277         }
278
279         if (!success)
280                 BKE_report(reports, RPT_ERROR, "Error writing frame.");
281
282         return success;
283 }
284
285 /* read and encode a frame of audio from the buffer */
286 static AVFrame* generate_video_frame(uint8_t* pixels, ReportList *reports) 
287 {
288         uint8_t* rendered_frame;
289
290         AVCodecContext* c = video_stream->codec;
291         int width = c->width;
292         int height = c->height;
293         AVFrame* rgb_frame;
294
295         if (c->pix_fmt != PIX_FMT_BGR32) {
296                 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
297                 if (!rgb_frame) {
298                         BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame.");
299                         return NULL;
300                 }
301         } else {
302                 rgb_frame = current_frame;
303         }
304
305         rendered_frame = pixels;
306
307         /* Do RGBA-conversion and flipping in one step depending
308            on CPU-Endianess */
309
310         if (ENDIAN_ORDER == L_ENDIAN) {
311                 int y;
312                 for (y = 0; y < height; y++) {
313                         uint8_t* target = rgb_frame->data[0]
314                                 + width * 4 * (height - y - 1);
315                         uint8_t* src = rendered_frame + width * 4 * y;
316                         uint8_t* end = src + width * 4;
317                         while (src != end) {
318                                 target[3] = src[3];
319                                 target[2] = src[2];
320                                 target[1] = src[1];
321                                 target[0] = src[0];
322
323                                 target += 4;
324                                 src += 4;
325                         }
326                 }
327         } else {
328                 int y;
329                 for (y = 0; y < height; y++) {
330                         uint8_t* target = rgb_frame->data[0]
331                                 + width * 4 * (height - y - 1);
332                         uint8_t* src = rendered_frame + width * 4 * y;
333                         uint8_t* end = src + width * 4;
334                         while (src != end) {
335                                 target[3] = src[0];
336                                 target[2] = src[1];
337                                 target[1] = src[2];
338                                 target[0] = src[3];
339
340                                 target += 4;
341                                 src += 4;
342                         }
343                 }
344         }
345
346         if (c->pix_fmt != PIX_FMT_BGR32) {
347                 sws_scale(img_convert_ctx, (const uint8_t * const*) rgb_frame->data,
348                           rgb_frame->linesize, 0, c->height,
349                           current_frame->data, current_frame->linesize);
350                 delete_picture(rgb_frame);
351         }
352         return current_frame;
353 }
354
355 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
356 {
357         char name[128];
358         char * param;
359         const AVOption * rv = NULL;
360
361         fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
362
363         BLI_strncpy(name, prop->name, sizeof(name));
364
365         param = strchr(name, ':');
366
367         if (param) {
368                 *param++ = 0;
369         }
370
371         switch(prop->type) {
372         case IDP_STRING:
373                 fprintf(stderr, "%s.\n", IDP_String(prop));
374                 av_set_string3(c, prop->name, IDP_String(prop), 1, &rv);
375                 break;
376         case IDP_FLOAT:
377                 fprintf(stderr, "%g.\n", IDP_Float(prop));
378                 rv = av_set_double(c, prop->name, IDP_Float(prop));
379                 break;
380         case IDP_INT:
381                 fprintf(stderr, "%d.\n", IDP_Int(prop));
382                 
383                 if (param) {
384                         if (IDP_Int(prop)) {
385                                 av_set_string3(c, name, param, 1, &rv);
386                         } else {
387                                 return;
388                         }
389                 } else {
390                         rv = av_set_int(c, prop->name, IDP_Int(prop));
391                 }
392                 break;
393         }
394
395         if (!rv) {
396                 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
397                         prop->name);
398         }
399 }
400
401 static int ffmpeg_proprty_valid(AVCodecContext *c, const char *prop_name, IDProperty *curr)
402 {
403         int valid= 1;
404
405         if(strcmp(prop_name, "video")==0) {
406                 if(strcmp(curr->name, "bf")==0) {
407                         /* flash codec doesn't support b frames */
408                         valid&= c->codec_id!=CODEC_ID_FLV1;
409                 }
410         }
411
412         return valid;
413 }
414
415 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char * prop_name)
416 {
417         IDProperty * prop;
418         void * iter;
419         IDProperty * curr;
420
421         if (!rd->ffcodecdata.properties) {
422                 return;
423         }
424         
425         prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name);
426         if (!prop) {
427                 return;
428         }
429
430         iter = IDP_GetGroupIterator(prop);
431
432         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
433                 if(ffmpeg_proprty_valid(c, prop_name, curr))
434                         set_ffmpeg_property_option(c, curr);
435         }
436 }
437
438 /* prepare a video stream for the output file */
439
440 static AVStream* alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext* of,
441                                         int rectx, int recty) 
442 {
443         AVStream* st;
444         AVCodecContext* c;
445         AVCodec* codec;
446         st = av_new_stream(of, 0);
447         if (!st) return NULL;
448
449         /* Set up the codec context */
450         
451         c = st->codec;
452         c->codec_id = codec_id;
453         c->codec_type = AVMEDIA_TYPE_VIDEO;
454
455
456         /* Get some values from the current render settings */
457         
458         c->width = rectx;
459         c->height = recty;
460
461         /* FIXME: Really bad hack (tm) for NTSC support */
462         if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
463                 c->time_base.den = 2997;
464                 c->time_base.num = 100;
465         } else if ((double) ((int) rd->frs_sec_base) == 
466                    rd->frs_sec_base) {
467                 c->time_base.den = rd->frs_sec;
468                 c->time_base.num = (int) rd->frs_sec_base;
469         } else {
470                 c->time_base.den = rd->frs_sec * 100000;
471                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
472         }
473         
474         c->gop_size = ffmpeg_gop_size;
475         c->bit_rate = ffmpeg_video_bitrate*1000;
476         c->rc_max_rate = rd->ffcodecdata.rc_max_rate*1000;
477         c->rc_min_rate = rd->ffcodecdata.rc_min_rate*1000;
478         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
479         c->rc_initial_buffer_occupancy 
480                 = rd->ffcodecdata.rc_buffer_size*3/4;
481         c->rc_buffer_aggressivity = 1.0;
482         c->me_method = ME_EPZS;
483         
484         codec = avcodec_find_encoder(c->codec_id);
485         if (!codec) return NULL;
486         
487         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
488
489         if (codec->pix_fmts) {
490                 c->pix_fmt = codec->pix_fmts[0];
491         } else {
492                 /* makes HuffYUV happy ... */
493                 c->pix_fmt = PIX_FMT_YUV422P;
494         }
495
496         if (ffmpeg_type == FFMPEG_XVID) {
497                 /* arghhhh ... */
498                 c->pix_fmt = PIX_FMT_YUV420P;
499                 c->codec_tag = (('D'<<24) + ('I'<<16) + ('V'<<8) + 'X');
500         }
501
502         if (codec_id == CODEC_ID_H264) {
503                 /* correct wrong default ffmpeg param which crash x264 */
504                 c->qmin=10;
505                 c->qmax=51;
506         }
507         
508         // Keep lossless encodes in the RGB domain.
509         if (codec_id == CODEC_ID_HUFFYUV) {
510                 /* HUFFYUV was PIX_FMT_YUV422P before */
511                 c->pix_fmt = PIX_FMT_RGB32;
512         }
513
514         if (codec_id == CODEC_ID_FFV1) {
515 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
516                 if (rd->im_format.planes ==  R_IMF_PLANES_RGBA) {
517                         c->pix_fmt = PIX_FMT_RGB32;
518                 }
519                 else {
520                         c->pix_fmt = PIX_FMT_BGR0;
521                 }
522 #else
523                 c->pix_fmt = PIX_FMT_RGB32;
524 #endif
525         }
526
527         if (codec_id == CODEC_ID_QTRLE ) {
528                 if (rd->im_format.planes ==  R_IMF_PLANES_RGBA) {
529                         c->pix_fmt = PIX_FMT_ARGB;
530                 }
531         }
532
533         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
534 //              || !strcmp(of->oformat->name, "mp4")
535 //          || !strcmp(of->oformat->name, "mov")
536 //          || !strcmp(of->oformat->name, "3gp")
537                 ) {
538                 fprintf(stderr, "Using global header\n");
539                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
540         }
541         
542         /* Determine whether we are encoding interlaced material or not */
543         if (rd->mode & R_FIELDS) {
544                 fprintf(stderr, "Encoding interlaced video\n");
545                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
546                 c->flags |= CODEC_FLAG_INTERLACED_ME;
547         }
548
549         /* xasp & yasp got float lately... */
550
551         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
552                 ((double) rd->xasp / (double) rd->yasp), 255);
553
554         set_ffmpeg_properties(rd, c, "video");
555         
556         if (avcodec_open(c, codec) < 0) {
557                 //
558                 //XXX error("Couldn't initialize codec");
559                 return NULL;
560         }
561
562         if ( codec_id == CODEC_ID_QTRLE ) {
563                 // normally it should be enough to have buffer with actual image size,
564                 // but some codecs like QTRLE might store extra information in this buffer,
565                 // so it should be a way larger
566
567                 // maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
568                 // (from FFmpeg sources)
569                 int size = c->width * c->height;
570                 video_buffersize = 7*size + 10000;
571         }
572         else
573                 video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
574
575         video_buffer = (uint8_t*)MEM_mallocN(video_buffersize*sizeof(uint8_t),
576                                                  "FFMPEG video buffer");
577         
578         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
579
580         img_convert_ctx = sws_getContext(c->width, c->height,
581                                          PIX_FMT_BGR32,
582                                          c->width, c->height,
583                                          c->pix_fmt,
584                                          SWS_BICUBIC,
585                                          NULL, NULL, NULL);
586         return st;
587 }
588
589 /* Prepare an audio stream for the output file */
590
591 static AVStream* alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext* of) 
592 {
593         AVStream* st;
594         AVCodecContext* c;
595         AVCodec* codec;
596
597         st = av_new_stream(of, 1);
598         if (!st) return NULL;
599
600         c = st->codec;
601         c->codec_id = codec_id;
602         c->codec_type = AVMEDIA_TYPE_AUDIO;
603
604         c->sample_rate = rd->ffcodecdata.audio_mixrate;
605         c->bit_rate = ffmpeg_audio_bitrate*1000;
606         c->sample_fmt = SAMPLE_FMT_S16;
607         c->channels = rd->ffcodecdata.audio_channels;
608         codec = avcodec_find_encoder(c->codec_id);
609         if (!codec) {
610                 //XXX error("Couldn't find a valid audio codec");
611                 return NULL;
612         }
613
614         set_ffmpeg_properties(rd, c, "audio");
615
616         if (avcodec_open(c, codec) < 0) {
617                 //XXX error("Couldn't initialize audio codec");
618                 return NULL;
619         }
620
621         /* need to prevent floating point exception when using vorbis audio codec,
622            initialize this value in the same way as it's done in FFmpeg iteslf (sergey) */
623         st->codec->time_base.num= 1;
624         st->codec->time_base.den= st->codec->sample_rate;
625
626         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
627
628         if((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
629                 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
630         else
631         {
632                 audio_input_samples = c->frame_size;
633                 if(c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
634                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
635         }
636
637         audio_output_buffer = (uint8_t*)av_malloc(
638                 audio_outbuf_size);
639
640         audio_input_buffer = (uint8_t*)av_malloc(
641                 audio_input_samples * c->channels * sizeof(int16_t));
642
643         audio_time = 0.0f;
644
645         return st;
646 }
647 /* essential functions -- start, append, end */
648
649 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
650 {
651         /* Handle to the output file */
652         AVFormatContext* of;
653         AVOutputFormat* fmt;
654         char name[256];
655         const char ** exts;
656
657         ffmpeg_type = rd->ffcodecdata.type;
658         ffmpeg_codec = rd->ffcodecdata.codec;
659         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
660         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
661         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
662         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
663         ffmpeg_autosplit = rd->ffcodecdata.flags
664                 & FFMPEG_AUTOSPLIT_OUTPUT;
665         
666         do_init_ffmpeg();
667
668         /* Determine the correct filename */
669         filepath_ffmpeg(name, rd);
670         fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
671                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
672                 "  video_bitrate=%d, audio_bitrate=%d,\n"
673                 "  gop_size=%d, autosplit=%d\n"
674                 "  render width=%d, render height=%d\n", 
675                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
676                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
677                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
678         
679         exts = get_file_extensions(ffmpeg_type);
680         if (!exts) {
681                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
682                 return 0;
683         }
684         fmt = av_guess_format(NULL, exts[0], NULL);
685         if (!fmt) {
686                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
687                 return 0;
688         }
689
690         of = avformat_alloc_context();
691         if (!of) {
692                 BKE_report(reports, RPT_ERROR, "Error opening output file");
693                 return 0;
694         }
695         
696         of->oformat = fmt;
697         of->packet_size= rd->ffcodecdata.mux_packet_size;
698         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
699                 of->mux_rate = rd->ffcodecdata.mux_rate;
700         } else {
701                 of->mux_rate = 0;
702         }
703
704         of->preload = (int)(0.5*AV_TIME_BASE);
705         of->max_delay = (int)(0.7*AV_TIME_BASE);
706
707         fmt->audio_codec = ffmpeg_audio_codec;
708
709         BLI_snprintf(of->filename, sizeof(of->filename), "%s", name);
710         /* set the codec to the user's selection */
711         switch(ffmpeg_type) {
712         case FFMPEG_AVI:
713         case FFMPEG_MOV:
714         case FFMPEG_MKV:
715                 fmt->video_codec = ffmpeg_codec;
716                 break;
717         case FFMPEG_OGG:
718                 fmt->video_codec = CODEC_ID_THEORA;
719                 break;
720         case FFMPEG_DV:
721                 fmt->video_codec = CODEC_ID_DVVIDEO;
722                 break;
723         case FFMPEG_MPEG1:
724                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
725                 break;
726         case FFMPEG_MPEG2:
727                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
728                 break;
729         case FFMPEG_H264:
730                 fmt->video_codec = CODEC_ID_H264;
731                 break;
732         case FFMPEG_XVID:
733                 fmt->video_codec = CODEC_ID_MPEG4;
734                 break;
735         case FFMPEG_FLV:
736                 fmt->video_codec = CODEC_ID_FLV1;
737                 break;
738         case FFMPEG_MP3:
739                 fmt->audio_codec = CODEC_ID_MP3;
740         case FFMPEG_WAV:
741                 fmt->video_codec = CODEC_ID_NONE;
742                 break;
743         case FFMPEG_MPEG4:
744         default:
745                 fmt->video_codec = CODEC_ID_MPEG4;
746                 break;
747         }
748         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
749                 if (rectx != 720) {
750                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
751                         return 0;
752                 }
753                 if (rd->frs_sec != 25 && recty != 480) {
754                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
755                         return 0;
756                 }
757                 if (rd->frs_sec == 25 && recty != 576) {
758                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
759                         return 0;
760                 }
761         }
762         
763         if (ffmpeg_type == FFMPEG_DV) {
764                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
765                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
766                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
767                         return 0;
768                 }
769         }
770         
771         if (fmt->video_codec != CODEC_ID_NONE) {
772                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty);
773                 printf("alloc video stream %p\n", video_stream);
774                 if (!video_stream) {
775                         BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
776                         return 0;
777                 }
778         }
779
780         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
781                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
782                 if (!audio_stream) {
783                         BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
784                         return 0;
785                 }
786         }
787         if (av_set_parameters(of, NULL) < 0) {
788                 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
789                 return 0;
790         }
791         if (!(fmt->flags & AVFMT_NOFILE)) {
792                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
793                         BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
794                         return 0;
795                 }
796         }
797
798         if (av_write_header(of) < 0) {
799                 BKE_report(reports, RPT_ERROR, "Could not initialize streams. Probably unsupported codec combination.");
800                 return 0;
801         }
802
803         outfile = of;
804         av_dump_format(of, 0, name, 1);
805
806         return 1;
807 }
808
809 /**
810  * Writes any delayed frames in the encoder. This function is called before 
811  * closing the encoder.
812  *
813  * <p>
814  * Since an encoder may use both past and future frames to predict 
815  * inter-frames (H.264 B-frames, for example), it can output the frames 
816  * in a different order from the one it was given.
817  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
818  * them in the order 1, 4, 2, 3 - first the two frames used for predition, 
819  * and then the bidirectionally-predicted frames. What this means in practice 
820  * is that the encoder may not immediately produce one output frame for each 
821  * input frame. These delayed frames must be flushed before we close the 
822  * stream. We do this by calling avcodec_encode_video with NULL for the last 
823  * parameter.
824  * </p>
825  */
826 void flush_ffmpeg(void)
827 {
828         int outsize = 0;
829         int ret = 0;
830         
831         AVCodecContext* c = video_stream->codec;
832         /* get the delayed frames */
833         while (1) {
834                 AVPacket packet;
835                 av_init_packet(&packet);
836                 
837                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
838                 if (outsize < 0) {
839                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
840                         break;
841                 }
842                 if (outsize == 0) {
843                         break;
844                 }
845                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
846                         packet.pts = av_rescale_q(c->coded_frame->pts,
847                                                   c->time_base,
848                                                   video_stream->time_base);
849                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
850                 } else {
851                         fprintf(stderr, "Video Frame PTS: not set\n");
852                 }
853                 if (c->coded_frame->key_frame) {
854                         packet.flags |= AV_PKT_FLAG_KEY;
855                 }
856                 packet.stream_index = video_stream->index;
857                 packet.data = video_buffer;
858                 packet.size = outsize;
859                 ret = av_interleaved_write_frame(outfile, &packet);
860                 if (ret != 0) {
861                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
862                         break;
863                 }
864         }
865         avcodec_flush_buffers(video_stream->codec);
866 }
867
868 /* **********************************************************************
869    * public interface
870    ********************************************************************** */
871
872 /* Get the output filename-- similar to the other output formats */
873 void filepath_ffmpeg(char* string, RenderData* rd)
874 {
875         char autosplit[20];
876
877         const char ** exts = get_file_extensions(rd->ffcodecdata.type);
878         const char ** fe = exts;
879
880         if (!string || !exts) return;
881
882         strcpy(string, rd->pic);
883         BLI_path_abs(string, G.main->name);
884
885         BLI_make_existing_file(string);
886
887         autosplit[0] = 0;
888
889         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
890                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
891         }
892
893         while (*fe) {
894                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
895                                    *fe) == 0) {
896                         break;
897                 }
898                 fe++;
899         }
900
901         if (!*fe) {
902                 strcat(string, autosplit);
903
904                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
905                 strcat(string, *exts);
906         } else {
907                 *(string + strlen(string) - strlen(*fe)) = 0;
908                 strcat(string, autosplit);
909                 strcat(string, *fe);
910         }
911 }
912
913 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
914 {
915         int success;
916
917         ffmpeg_autosplit_count = 0;
918
919         success = start_ffmpeg_impl(rd, rectx, recty, reports);
920 #ifdef WITH_AUDASPACE
921         if(audio_stream)
922         {
923                 AVCodecContext* c = audio_stream->codec;
924                 AUD_DeviceSpecs specs;
925                 specs.channels = c->channels;
926                 specs.format = AUD_FORMAT_S16;
927                 specs.rate = rd->ffcodecdata.audio_mixrate;
928                 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
929 #ifdef FFMPEG_CODEC_TIME_BASE
930                 c->time_base.den = specs.rate;
931                 c->time_base.num = 1;
932 #endif
933         }
934 #endif
935         return success;
936 }
937
938 void end_ffmpeg(void);
939
940 #ifdef WITH_AUDASPACE
941 static void write_audio_frames(double to_pts)
942 {
943         int finished = 0;
944
945         while (audio_stream && !finished) {
946                 if((audio_time >= to_pts) ||
947                    (write_audio_frame())) {
948                         finished = 1;
949                 }
950         }
951 }
952 #endif
953
954 int append_ffmpeg(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
955 {
956         AVFrame* avframe;
957         int success = 1;
958
959         fprintf(stderr, "Writing frame %i, "
960                 "render width=%d, render height=%d\n", frame,
961                 rectx, recty);
962
963 // why is this done before writing the video frame and again at end_ffmpeg?
964 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
965
966         if(video_stream)
967         {
968                 avframe= generate_video_frame((unsigned char*) pixels, reports);
969                 success= (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
970
971                 if (ffmpeg_autosplit) {
972                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
973                                 end_ffmpeg();
974                                 ffmpeg_autosplit_count++;
975                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
976                         }
977                 }
978         }
979
980 #ifdef WITH_AUDASPACE
981         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
982 #endif
983         return success;
984 }
985
986 void end_ffmpeg(void)
987 {
988         unsigned int i;
989         
990         fprintf(stderr, "Closing ffmpeg...\n");
991
992 /*      if (audio_stream) { SEE UPPER
993                 write_audio_frames();
994         }*/
995
996 #ifdef WITH_AUDASPACE
997         if(audio_mixdown_device)
998         {
999                 AUD_closeReadDevice(audio_mixdown_device);
1000                 audio_mixdown_device = 0;
1001         }
1002 #endif
1003
1004         if (video_stream && video_stream->codec) {
1005                 fprintf(stderr, "Flushing delayed frames...\n");
1006                 flush_ffmpeg ();                
1007         }
1008         
1009         if (outfile) {
1010                 av_write_trailer(outfile);
1011         }
1012         
1013         /* Close the video codec */
1014
1015         if (video_stream && video_stream->codec) {
1016                 avcodec_close(video_stream->codec);
1017                 printf("zero video stream %p\n", video_stream);
1018                 video_stream = 0;
1019         }
1020
1021         
1022         /* Close the output file */
1023         if (outfile) {
1024                 for (i = 0; i < outfile->nb_streams; i++) {
1025                         if (&outfile->streams[i]) {
1026                                 av_freep(&outfile->streams[i]);
1027                         }
1028                 }
1029         }
1030         /* free the temp buffer */
1031         if (current_frame) {
1032                 delete_picture(current_frame);
1033                 current_frame = 0;
1034         }
1035         if (outfile && outfile->oformat) {
1036                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1037                         avio_close(outfile->pb);
1038                 }
1039         }
1040         if (outfile) {
1041                 av_free(outfile);
1042                 outfile = 0;
1043         }
1044         if (video_buffer) {
1045                 MEM_freeN(video_buffer);
1046                 video_buffer = 0;
1047         }
1048         if (audio_output_buffer) {
1049                 av_free(audio_output_buffer);
1050                 audio_output_buffer = 0;
1051         }
1052         if (audio_input_buffer) {
1053                 av_free(audio_input_buffer);
1054                 audio_input_buffer = 0;
1055         }
1056
1057         if (img_convert_ctx) {
1058                 sws_freeContext(img_convert_ctx);
1059                 img_convert_ctx = 0;
1060         }
1061 }
1062
1063 /* properties */
1064
1065 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1066 {
1067         struct IDProperty *prop = (struct IDProperty *) prop_;
1068         IDProperty * group;
1069         
1070         if (!rd->ffcodecdata.properties) {
1071                 return;
1072         }
1073
1074         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1075         if (group && prop) {
1076                 IDP_RemFromGroup(group, prop);
1077                 IDP_FreeProperty(prop);
1078                 MEM_freeN(prop);
1079         }
1080 }
1081
1082 IDProperty *ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1083 {
1084         AVCodecContext c;
1085         const AVOption * o;
1086         const AVOption * parent;
1087         IDProperty * group;
1088         IDProperty * prop;
1089         IDPropertyTemplate val;
1090         int idp_type;
1091         char name[256];
1092         
1093         val.i = 0;
1094
1095         avcodec_get_context_defaults(&c);
1096
1097         o = c.av_class->option + opt_index;
1098         parent = c.av_class->option + parent_index;
1099
1100         if (!rd->ffcodecdata.properties) {
1101                 rd->ffcodecdata.properties 
1102                         = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1103         }
1104
1105         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1106         
1107         if (!group) {
1108                 group = IDP_New(IDP_GROUP, &val, type);
1109                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1110         }
1111
1112         if (parent_index) {
1113                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1114         } else {
1115                 BLI_strncpy(name, o->name, sizeof(name));
1116         }
1117
1118         fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1119                 type, parent_index, opt_index, name);
1120
1121         prop = IDP_GetPropertyFromGroup(group, name);
1122         if (prop) {
1123                 return prop;
1124         }
1125
1126         switch (o->type) {
1127         case FF_OPT_TYPE_INT:
1128         case FF_OPT_TYPE_INT64:
1129                 val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1130                 idp_type = IDP_INT;
1131                 break;
1132         case FF_OPT_TYPE_DOUBLE:
1133         case FF_OPT_TYPE_FLOAT:
1134                 val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1135                 idp_type = IDP_FLOAT;
1136                 break;
1137         case FF_OPT_TYPE_STRING:
1138                 val.string.str = (char *)"                                                                               ";
1139                 val.string.len = 80;
1140 /*              val.str = (char *)"                                                                               ";*/
1141                 idp_type = IDP_STRING;
1142                 break;
1143         case FF_OPT_TYPE_CONST:
1144                 val.i = 1;
1145                 idp_type = IDP_INT;
1146                 break;
1147         default:
1148                 return NULL;
1149         }
1150         prop = IDP_New(idp_type, &val, name);
1151         IDP_AddToGroup(group, prop);
1152         return prop;
1153 }
1154
1155 /* not all versions of ffmpeg include that, so here we go ... */
1156
1157 static const AVOption *my_av_find_opt(void *v, const char *name,
1158                                       const char *unit, int mask, int flags)
1159 {
1160         AVClass *c= *(AVClass**)v; 
1161         const AVOption *o= c->option;
1162
1163         for(;o && o->name; o++) {
1164                 if(!strcmp(o->name, name) && 
1165                    (!unit || (o->unit && !strcmp(o->unit, unit))) && 
1166                    (o->flags & mask) == flags )
1167                         return o;
1168         }
1169         return NULL;
1170 }
1171
1172 int ffmpeg_property_add_string(RenderData *rd, const char * type, const char * str)
1173 {
1174         AVCodecContext c;
1175         const AVOption * o = 0;
1176         const AVOption * p = 0;
1177         char name_[128];
1178         char * name;
1179         char * param;
1180         IDProperty * prop;
1181         
1182         avcodec_get_context_defaults(&c);
1183
1184         strncpy(name_, str, sizeof(name_));
1185
1186         name = name_;
1187         while (*name == ' ') name++;
1188
1189         param = strchr(name, ':');
1190
1191         if (!param) {
1192                 param = strchr(name, ' ');
1193         }
1194         if (param) {
1195                 *param++ = 0;
1196                 while (*param == ' ') param++;
1197         }
1198         
1199         o = my_av_find_opt(&c, name, NULL, 0, 0);       
1200         if (!o) {
1201                 return 0;
1202         }
1203         if (param && o->type == FF_OPT_TYPE_CONST) {
1204                 return 0;
1205         }
1206         if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1207                 p = my_av_find_opt(&c, param, o->unit, 0, 0);   
1208                 prop = ffmpeg_property_add(rd,
1209                         (char*) type, p - c.av_class->option, 
1210                         o - c.av_class->option);
1211         } else {
1212                 prop = ffmpeg_property_add(rd,
1213                         (char*) type, o - c.av_class->option, 0);
1214         }
1215                 
1216
1217         if (!prop) {
1218                 return 0;
1219         }
1220
1221         if (param && !p) {
1222                 switch (prop->type) {
1223                 case IDP_INT:
1224                         IDP_Int(prop) = atoi(param);
1225                         break;
1226                 case IDP_FLOAT:
1227                         IDP_Float(prop) = atof(param);
1228                         break;
1229                 case IDP_STRING:
1230                         strncpy(IDP_String(prop), param, prop->len);
1231                         break;
1232                 }
1233         }
1234         return 1;
1235 }
1236
1237 static void ffmpeg_set_expert_options(RenderData *rd)
1238 {
1239         int codec_id = rd->ffcodecdata.codec;
1240
1241         if(rd->ffcodecdata.properties)
1242                 IDP_FreeProperty(rd->ffcodecdata.properties);
1243
1244         if(codec_id == CODEC_ID_H264) {
1245                 /*
1246                  * All options here are for x264, but must be set via ffmpeg.
1247                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1248                  * to get a list.
1249                  */
1250
1251                 /*
1252                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1253                  * crashes Blender for some reason. Either way - this is no big deal.
1254                  */
1255                 ffmpeg_property_add_string(rd, "video", "coder:vlc");
1256
1257                 /*
1258                  * The other options were taken from the libx264-default.preset
1259                  * included in the ffmpeg distribution.
1260                  */
1261 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1262                 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1263                 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1264                 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1265                 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1266                 ffmpeg_property_add_string(rd, "video", "me:hex");
1267                 ffmpeg_property_add_string(rd, "video", "subq:6");
1268                 ffmpeg_property_add_string(rd, "video", "me_range:16");
1269                 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1270                 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1271                 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1272                 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1273                 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1274                 ffmpeg_property_add_string(rd, "video", "bf:3");
1275                 ffmpeg_property_add_string(rd, "video", "refs:2");
1276                 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1277                 ffmpeg_property_add_string(rd, "video", "directpred:3");
1278                 ffmpeg_property_add_string(rd, "video", "trellis:0");
1279                 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1280                 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1281                 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1282                 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1283
1284                 if(rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1285                         ffmpeg_property_add_string(rd, "video", "cqp:0");
1286         }
1287 #if 0   /* disabled for after release */
1288         else if(codec_id == CODEC_ID_DNXHD) {
1289                 if(rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1290                         ffmpeg_property_add_string(rd, "video", "mbd:rd");
1291         }
1292 #endif
1293 }
1294
1295 void ffmpeg_set_preset(RenderData *rd, int preset)
1296 {
1297         int isntsc = (rd->frs_sec != 25);
1298
1299         if(rd->ffcodecdata.properties)
1300                 IDP_FreeProperty(rd->ffcodecdata.properties);
1301
1302         switch (preset) {
1303         case FFMPEG_PRESET_VCD:
1304                 rd->ffcodecdata.type = FFMPEG_MPEG1;
1305                 rd->ffcodecdata.video_bitrate = 1150;
1306                 rd->xsch = 352;
1307                 rd->ysch = isntsc ? 240 : 288;
1308                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1309                 rd->ffcodecdata.rc_max_rate = 1150;
1310                 rd->ffcodecdata.rc_min_rate = 1150;
1311                 rd->ffcodecdata.rc_buffer_size = 40*8;
1312                 rd->ffcodecdata.mux_packet_size = 2324;
1313                 rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1314                 break;
1315
1316         case FFMPEG_PRESET_SVCD:
1317                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1318                 rd->ffcodecdata.video_bitrate = 2040;
1319                 rd->xsch = 480;
1320                 rd->ysch = isntsc ? 480 : 576;
1321                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1322                 rd->ffcodecdata.rc_max_rate = 2516;
1323                 rd->ffcodecdata.rc_min_rate = 0;
1324                 rd->ffcodecdata.rc_buffer_size = 224*8;
1325                 rd->ffcodecdata.mux_packet_size = 2324;
1326                 rd->ffcodecdata.mux_rate = 0;
1327                 break;
1328
1329         case FFMPEG_PRESET_DVD:
1330                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1331                 rd->ffcodecdata.video_bitrate = 6000;
1332
1333                 /* Don't set resolution, see [#21351]
1334                  * rd->xsch = 720;
1335                  * rd->ysch = isntsc ? 480 : 576; */
1336
1337                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1338                 rd->ffcodecdata.rc_max_rate = 9000;
1339                 rd->ffcodecdata.rc_min_rate = 0;
1340                 rd->ffcodecdata.rc_buffer_size = 224*8;
1341                 rd->ffcodecdata.mux_packet_size = 2048;
1342                 rd->ffcodecdata.mux_rate = 10080000;
1343                 break;
1344
1345         case FFMPEG_PRESET_DV:
1346                 rd->ffcodecdata.type = FFMPEG_DV;
1347                 rd->xsch = 720;
1348                 rd->ysch = isntsc ? 480 : 576;
1349                 break;
1350
1351         case FFMPEG_PRESET_H264:
1352                 rd->ffcodecdata.type = FFMPEG_AVI;
1353                 rd->ffcodecdata.codec = CODEC_ID_H264;
1354                 rd->ffcodecdata.video_bitrate = 6000;
1355                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1356                 rd->ffcodecdata.rc_max_rate = 9000;
1357                 rd->ffcodecdata.rc_min_rate = 0;
1358                 rd->ffcodecdata.rc_buffer_size = 224*8;
1359                 rd->ffcodecdata.mux_packet_size = 2048;
1360                 rd->ffcodecdata.mux_rate = 10080000;
1361
1362                 break;
1363
1364         case FFMPEG_PRESET_THEORA:
1365         case FFMPEG_PRESET_XVID:
1366                 if(preset == FFMPEG_PRESET_XVID) {
1367                         rd->ffcodecdata.type = FFMPEG_AVI;
1368                         rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1369                 }
1370                 else if(preset == FFMPEG_PRESET_THEORA) {
1371                         rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1372                         rd->ffcodecdata.codec = CODEC_ID_THEORA;
1373                 }
1374
1375                 rd->ffcodecdata.video_bitrate = 6000;
1376                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1377                 rd->ffcodecdata.rc_max_rate = 9000;
1378                 rd->ffcodecdata.rc_min_rate = 0;
1379                 rd->ffcodecdata.rc_buffer_size = 224*8;
1380                 rd->ffcodecdata.mux_packet_size = 2048;
1381                 rd->ffcodecdata.mux_rate = 10080000;
1382                 break;
1383
1384         }
1385
1386         ffmpeg_set_expert_options(rd);
1387 }
1388
1389 void ffmpeg_verify_image_type(RenderData *rd, ImageFormatData *imf)
1390 {
1391         int audio= 0;
1392
1393         if(imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1394                 if(rd->ffcodecdata.type <= 0 ||
1395                    rd->ffcodecdata.codec <= 0 ||
1396                    rd->ffcodecdata.audio_codec <= 0 ||
1397                    rd->ffcodecdata.video_bitrate <= 1) {
1398
1399                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1400
1401                         ffmpeg_set_preset(rd, FFMPEG_PRESET_DVD);
1402                 }
1403                 if(rd->ffcodecdata.type == FFMPEG_OGG) {
1404                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1405                 }
1406
1407                 audio= 1;
1408         }
1409         else if(imf->imtype == R_IMF_IMTYPE_H264) {
1410                 if(rd->ffcodecdata.codec != CODEC_ID_H264) {
1411                         ffmpeg_set_preset(rd, FFMPEG_PRESET_H264);
1412                         audio= 1;
1413                 }
1414         }
1415         else if(imf->imtype == R_IMF_IMTYPE_XVID) {
1416                 if(rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1417                         ffmpeg_set_preset(rd, FFMPEG_PRESET_XVID);
1418                         audio= 1;
1419                 }
1420         }
1421         else if(imf->imtype == R_IMF_IMTYPE_THEORA) {
1422                 if(rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1423                         ffmpeg_set_preset(rd, FFMPEG_PRESET_THEORA);
1424                         audio= 1;
1425                 }
1426         }
1427
1428         if(audio && rd->ffcodecdata.audio_codec < 0) {
1429                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1430                 rd->ffcodecdata.audio_bitrate = 128;
1431         }
1432 }
1433
1434 void ffmpeg_verify_codec_settings(RenderData *rd)
1435 {
1436         ffmpeg_set_expert_options(rd);
1437 }
1438
1439 int ffmpeg_alpha_channel_supported(RenderData *rd)
1440 {
1441         int codec = rd->ffcodecdata.codec;
1442
1443         if (codec == CODEC_ID_QTRLE)
1444                 return TRUE;
1445
1446 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1447         if (codec == CODEC_ID_FFV1)
1448                 return TRUE;
1449 #endif
1450
1451         return FALSE;
1452 }
1453
1454 #endif