style cleanup, brackets in else/if, some indentation.
[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                 audio_input_samples = c->frame_size;
632                 if(c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
633                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
634         }
635
636         audio_output_buffer = (uint8_t*)av_malloc(
637                 audio_outbuf_size);
638
639         audio_input_buffer = (uint8_t*)av_malloc(
640                 audio_input_samples * c->channels * sizeof(int16_t));
641
642         audio_time = 0.0f;
643
644         return st;
645 }
646 /* essential functions -- start, append, end */
647
648 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
649 {
650         /* Handle to the output file */
651         AVFormatContext* of;
652         AVOutputFormat* fmt;
653         char name[256];
654         const char ** exts;
655
656         ffmpeg_type = rd->ffcodecdata.type;
657         ffmpeg_codec = rd->ffcodecdata.codec;
658         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
659         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
660         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
661         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
662         ffmpeg_autosplit = rd->ffcodecdata.flags
663                 & FFMPEG_AUTOSPLIT_OUTPUT;
664         
665         do_init_ffmpeg();
666
667         /* Determine the correct filename */
668         filepath_ffmpeg(name, rd);
669         fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
670                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
671                 "  video_bitrate=%d, audio_bitrate=%d,\n"
672                 "  gop_size=%d, autosplit=%d\n"
673                 "  render width=%d, render height=%d\n", 
674                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
675                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
676                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
677         
678         exts = get_file_extensions(ffmpeg_type);
679         if (!exts) {
680                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
681                 return 0;
682         }
683         fmt = av_guess_format(NULL, exts[0], NULL);
684         if (!fmt) {
685                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
686                 return 0;
687         }
688
689         of = avformat_alloc_context();
690         if (!of) {
691                 BKE_report(reports, RPT_ERROR, "Error opening output file");
692                 return 0;
693         }
694         
695         of->oformat = fmt;
696         of->packet_size= rd->ffcodecdata.mux_packet_size;
697         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
698                 of->mux_rate = rd->ffcodecdata.mux_rate;
699         } else {
700                 of->mux_rate = 0;
701         }
702
703         of->preload = (int)(0.5*AV_TIME_BASE);
704         of->max_delay = (int)(0.7*AV_TIME_BASE);
705
706         fmt->audio_codec = ffmpeg_audio_codec;
707
708         BLI_snprintf(of->filename, sizeof(of->filename), "%s", name);
709         /* set the codec to the user's selection */
710         switch(ffmpeg_type) {
711         case FFMPEG_AVI:
712         case FFMPEG_MOV:
713         case FFMPEG_MKV:
714                 fmt->video_codec = ffmpeg_codec;
715                 break;
716         case FFMPEG_OGG:
717                 fmt->video_codec = CODEC_ID_THEORA;
718                 break;
719         case FFMPEG_DV:
720                 fmt->video_codec = CODEC_ID_DVVIDEO;
721                 break;
722         case FFMPEG_MPEG1:
723                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
724                 break;
725         case FFMPEG_MPEG2:
726                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
727                 break;
728         case FFMPEG_H264:
729                 fmt->video_codec = CODEC_ID_H264;
730                 break;
731         case FFMPEG_XVID:
732                 fmt->video_codec = CODEC_ID_MPEG4;
733                 break;
734         case FFMPEG_FLV:
735                 fmt->video_codec = CODEC_ID_FLV1;
736                 break;
737         case FFMPEG_MP3:
738                 fmt->audio_codec = CODEC_ID_MP3;
739         case FFMPEG_WAV:
740                 fmt->video_codec = CODEC_ID_NONE;
741                 break;
742         case FFMPEG_MPEG4:
743         default:
744                 fmt->video_codec = CODEC_ID_MPEG4;
745                 break;
746         }
747         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
748                 if (rectx != 720) {
749                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
750                         return 0;
751                 }
752                 if (rd->frs_sec != 25 && recty != 480) {
753                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
754                         return 0;
755                 }
756                 if (rd->frs_sec == 25 && recty != 576) {
757                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
758                         return 0;
759                 }
760         }
761         
762         if (ffmpeg_type == FFMPEG_DV) {
763                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
764                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
765                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
766                         return 0;
767                 }
768         }
769         
770         if (fmt->video_codec != CODEC_ID_NONE) {
771                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty);
772                 printf("alloc video stream %p\n", video_stream);
773                 if (!video_stream) {
774                         BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
775                         return 0;
776                 }
777         }
778
779         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
780                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
781                 if (!audio_stream) {
782                         BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
783                         return 0;
784                 }
785         }
786         if (av_set_parameters(of, NULL) < 0) {
787                 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
788                 return 0;
789         }
790         if (!(fmt->flags & AVFMT_NOFILE)) {
791                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
792                         BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
793                         return 0;
794                 }
795         }
796
797         if (av_write_header(of) < 0) {
798                 BKE_report(reports, RPT_ERROR, "Could not initialize streams. Probably unsupported codec combination.");
799                 return 0;
800         }
801
802         outfile = of;
803         av_dump_format(of, 0, name, 1);
804
805         return 1;
806 }
807
808 /**
809  * Writes any delayed frames in the encoder. This function is called before 
810  * closing the encoder.
811  *
812  * <p>
813  * Since an encoder may use both past and future frames to predict 
814  * inter-frames (H.264 B-frames, for example), it can output the frames 
815  * in a different order from the one it was given.
816  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
817  * them in the order 1, 4, 2, 3 - first the two frames used for predition, 
818  * and then the bidirectionally-predicted frames. What this means in practice 
819  * is that the encoder may not immediately produce one output frame for each 
820  * input frame. These delayed frames must be flushed before we close the 
821  * stream. We do this by calling avcodec_encode_video with NULL for the last 
822  * parameter.
823  * </p>
824  */
825 void flush_ffmpeg(void)
826 {
827         int outsize = 0;
828         int ret = 0;
829         
830         AVCodecContext* c = video_stream->codec;
831         /* get the delayed frames */
832         while (1) {
833                 AVPacket packet;
834                 av_init_packet(&packet);
835                 
836                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
837                 if (outsize < 0) {
838                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
839                         break;
840                 }
841                 if (outsize == 0) {
842                         break;
843                 }
844                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
845                         packet.pts = av_rescale_q(c->coded_frame->pts,
846                                                   c->time_base,
847                                                   video_stream->time_base);
848                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
849                 } else {
850                         fprintf(stderr, "Video Frame PTS: not set\n");
851                 }
852                 if (c->coded_frame->key_frame) {
853                         packet.flags |= AV_PKT_FLAG_KEY;
854                 }
855                 packet.stream_index = video_stream->index;
856                 packet.data = video_buffer;
857                 packet.size = outsize;
858                 ret = av_interleaved_write_frame(outfile, &packet);
859                 if (ret != 0) {
860                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
861                         break;
862                 }
863         }
864         avcodec_flush_buffers(video_stream->codec);
865 }
866
867 /* **********************************************************************
868    * public interface
869    ********************************************************************** */
870
871 /* Get the output filename-- similar to the other output formats */
872 void filepath_ffmpeg(char* string, RenderData* rd)
873 {
874         char autosplit[20];
875
876         const char ** exts = get_file_extensions(rd->ffcodecdata.type);
877         const char ** fe = exts;
878
879         if (!string || !exts) return;
880
881         strcpy(string, rd->pic);
882         BLI_path_abs(string, G.main->name);
883
884         BLI_make_existing_file(string);
885
886         autosplit[0] = 0;
887
888         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
889                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
890         }
891
892         while (*fe) {
893                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
894                                    *fe) == 0) {
895                         break;
896                 }
897                 fe++;
898         }
899
900         if (!*fe) {
901                 strcat(string, autosplit);
902
903                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
904                 strcat(string, *exts);
905         } else {
906                 *(string + strlen(string) - strlen(*fe)) = 0;
907                 strcat(string, autosplit);
908                 strcat(string, *fe);
909         }
910 }
911
912 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
913 {
914         int success;
915
916         ffmpeg_autosplit_count = 0;
917
918         success = start_ffmpeg_impl(rd, rectx, recty, reports);
919 #ifdef WITH_AUDASPACE
920         if(audio_stream)
921         {
922                 AVCodecContext* c = audio_stream->codec;
923                 AUD_DeviceSpecs specs;
924                 specs.channels = c->channels;
925                 specs.format = AUD_FORMAT_S16;
926                 specs.rate = rd->ffcodecdata.audio_mixrate;
927                 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
928 #ifdef FFMPEG_CODEC_TIME_BASE
929                 c->time_base.den = specs.rate;
930                 c->time_base.num = 1;
931 #endif
932         }
933 #endif
934         return success;
935 }
936
937 void end_ffmpeg(void);
938
939 #ifdef WITH_AUDASPACE
940 static void write_audio_frames(double to_pts)
941 {
942         int finished = 0;
943
944         while (audio_stream && !finished) {
945                 if((audio_time >= to_pts) ||
946                    (write_audio_frame())) {
947                         finished = 1;
948                 }
949         }
950 }
951 #endif
952
953 int append_ffmpeg(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
954 {
955         AVFrame* avframe;
956         int success = 1;
957
958         fprintf(stderr, "Writing frame %i, "
959                 "render width=%d, render height=%d\n", frame,
960                 rectx, recty);
961
962 // why is this done before writing the video frame and again at end_ffmpeg?
963 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
964
965         if(video_stream)
966         {
967                 avframe= generate_video_frame((unsigned char*) pixels, reports);
968                 success= (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
969
970                 if (ffmpeg_autosplit) {
971                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
972                                 end_ffmpeg();
973                                 ffmpeg_autosplit_count++;
974                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
975                         }
976                 }
977         }
978
979 #ifdef WITH_AUDASPACE
980         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
981 #endif
982         return success;
983 }
984
985 void end_ffmpeg(void)
986 {
987         unsigned int i;
988         
989         fprintf(stderr, "Closing ffmpeg...\n");
990
991 /*      if (audio_stream) { SEE UPPER
992                 write_audio_frames();
993         }*/
994
995 #ifdef WITH_AUDASPACE
996         if (audio_mixdown_device) {
997                 AUD_closeReadDevice(audio_mixdown_device);
998                 audio_mixdown_device = 0;
999         }
1000 #endif
1001
1002         if (video_stream && video_stream->codec) {
1003                 fprintf(stderr, "Flushing delayed frames...\n");
1004                 flush_ffmpeg ();                
1005         }
1006         
1007         if (outfile) {
1008                 av_write_trailer(outfile);
1009         }
1010         
1011         /* Close the video codec */
1012
1013         if (video_stream && video_stream->codec) {
1014                 avcodec_close(video_stream->codec);
1015                 printf("zero video stream %p\n", video_stream);
1016                 video_stream = 0;
1017         }
1018
1019         
1020         /* Close the output file */
1021         if (outfile) {
1022                 for (i = 0; i < outfile->nb_streams; i++) {
1023                         if (&outfile->streams[i]) {
1024                                 av_freep(&outfile->streams[i]);
1025                         }
1026                 }
1027         }
1028         /* free the temp buffer */
1029         if (current_frame) {
1030                 delete_picture(current_frame);
1031                 current_frame = 0;
1032         }
1033         if (outfile && outfile->oformat) {
1034                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1035                         avio_close(outfile->pb);
1036                 }
1037         }
1038         if (outfile) {
1039                 av_free(outfile);
1040                 outfile = 0;
1041         }
1042         if (video_buffer) {
1043                 MEM_freeN(video_buffer);
1044                 video_buffer = 0;
1045         }
1046         if (audio_output_buffer) {
1047                 av_free(audio_output_buffer);
1048                 audio_output_buffer = 0;
1049         }
1050         if (audio_input_buffer) {
1051                 av_free(audio_input_buffer);
1052                 audio_input_buffer = 0;
1053         }
1054
1055         if (img_convert_ctx) {
1056                 sws_freeContext(img_convert_ctx);
1057                 img_convert_ctx = 0;
1058         }
1059 }
1060
1061 /* properties */
1062
1063 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1064 {
1065         struct IDProperty *prop = (struct IDProperty *) prop_;
1066         IDProperty * group;
1067         
1068         if (!rd->ffcodecdata.properties) {
1069                 return;
1070         }
1071
1072         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1073         if (group && prop) {
1074                 IDP_RemFromGroup(group, prop);
1075                 IDP_FreeProperty(prop);
1076                 MEM_freeN(prop);
1077         }
1078 }
1079
1080 IDProperty *ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1081 {
1082         AVCodecContext c;
1083         const AVOption * o;
1084         const AVOption * parent;
1085         IDProperty * group;
1086         IDProperty * prop;
1087         IDPropertyTemplate val;
1088         int idp_type;
1089         char name[256];
1090         
1091         val.i = 0;
1092
1093         avcodec_get_context_defaults(&c);
1094
1095         o = c.av_class->option + opt_index;
1096         parent = c.av_class->option + parent_index;
1097
1098         if (!rd->ffcodecdata.properties) {
1099                 rd->ffcodecdata.properties 
1100                         = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1101         }
1102
1103         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1104         
1105         if (!group) {
1106                 group = IDP_New(IDP_GROUP, &val, type);
1107                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1108         }
1109
1110         if (parent_index) {
1111                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1112         } else {
1113                 BLI_strncpy(name, o->name, sizeof(name));
1114         }
1115
1116         fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1117                 type, parent_index, opt_index, name);
1118
1119         prop = IDP_GetPropertyFromGroup(group, name);
1120         if (prop) {
1121                 return prop;
1122         }
1123
1124         switch (o->type) {
1125         case FF_OPT_TYPE_INT:
1126         case FF_OPT_TYPE_INT64:
1127                 val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1128                 idp_type = IDP_INT;
1129                 break;
1130         case FF_OPT_TYPE_DOUBLE:
1131         case FF_OPT_TYPE_FLOAT:
1132                 val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1133                 idp_type = IDP_FLOAT;
1134                 break;
1135         case FF_OPT_TYPE_STRING:
1136                 val.string.str = (char *)"                                                                               ";
1137                 val.string.len = 80;
1138 /*              val.str = (char *)"                                                                               ";*/
1139                 idp_type = IDP_STRING;
1140                 break;
1141         case FF_OPT_TYPE_CONST:
1142                 val.i = 1;
1143                 idp_type = IDP_INT;
1144                 break;
1145         default:
1146                 return NULL;
1147         }
1148         prop = IDP_New(idp_type, &val, name);
1149         IDP_AddToGroup(group, prop);
1150         return prop;
1151 }
1152
1153 /* not all versions of ffmpeg include that, so here we go ... */
1154
1155 static const AVOption *my_av_find_opt(void *v, const char *name,
1156                                       const char *unit, int mask, int flags)
1157 {
1158         AVClass *c= *(AVClass**)v; 
1159         const AVOption *o= c->option;
1160
1161         for(;o && o->name; o++) {
1162                 if(!strcmp(o->name, name) && 
1163                    (!unit || (o->unit && !strcmp(o->unit, unit))) && 
1164                    (o->flags & mask) == flags )
1165                         return o;
1166         }
1167         return NULL;
1168 }
1169
1170 int ffmpeg_property_add_string(RenderData *rd, const char * type, const char * str)
1171 {
1172         AVCodecContext c;
1173         const AVOption * o = 0;
1174         const AVOption * p = 0;
1175         char name_[128];
1176         char * name;
1177         char * param;
1178         IDProperty * prop;
1179         
1180         avcodec_get_context_defaults(&c);
1181
1182         strncpy(name_, str, sizeof(name_));
1183
1184         name = name_;
1185         while (*name == ' ') name++;
1186
1187         param = strchr(name, ':');
1188
1189         if (!param) {
1190                 param = strchr(name, ' ');
1191         }
1192         if (param) {
1193                 *param++ = 0;
1194                 while (*param == ' ') param++;
1195         }
1196         
1197         o = my_av_find_opt(&c, name, NULL, 0, 0);       
1198         if (!o) {
1199                 return 0;
1200         }
1201         if (param && o->type == FF_OPT_TYPE_CONST) {
1202                 return 0;
1203         }
1204         if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1205                 p = my_av_find_opt(&c, param, o->unit, 0, 0);   
1206                 prop = ffmpeg_property_add(rd,
1207                         (char*) type, p - c.av_class->option, 
1208                         o - c.av_class->option);
1209         } else {
1210                 prop = ffmpeg_property_add(rd,
1211                         (char*) type, o - c.av_class->option, 0);
1212         }
1213                 
1214
1215         if (!prop) {
1216                 return 0;
1217         }
1218
1219         if (param && !p) {
1220                 switch (prop->type) {
1221                 case IDP_INT:
1222                         IDP_Int(prop) = atoi(param);
1223                         break;
1224                 case IDP_FLOAT:
1225                         IDP_Float(prop) = atof(param);
1226                         break;
1227                 case IDP_STRING:
1228                         strncpy(IDP_String(prop), param, prop->len);
1229                         break;
1230                 }
1231         }
1232         return 1;
1233 }
1234
1235 static void ffmpeg_set_expert_options(RenderData *rd)
1236 {
1237         int codec_id = rd->ffcodecdata.codec;
1238
1239         if(rd->ffcodecdata.properties)
1240                 IDP_FreeProperty(rd->ffcodecdata.properties);
1241
1242         if(codec_id == CODEC_ID_H264) {
1243                 /*
1244                  * All options here are for x264, but must be set via ffmpeg.
1245                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1246                  * to get a list.
1247                  */
1248
1249                 /*
1250                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1251                  * crashes Blender for some reason. Either way - this is no big deal.
1252                  */
1253                 ffmpeg_property_add_string(rd, "video", "coder:vlc");
1254
1255                 /*
1256                  * The other options were taken from the libx264-default.preset
1257                  * included in the ffmpeg distribution.
1258                  */
1259 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1260                 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1261                 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1262                 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1263                 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1264                 ffmpeg_property_add_string(rd, "video", "me:hex");
1265                 ffmpeg_property_add_string(rd, "video", "subq:6");
1266                 ffmpeg_property_add_string(rd, "video", "me_range:16");
1267                 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1268                 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1269                 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1270                 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1271                 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1272                 ffmpeg_property_add_string(rd, "video", "bf:3");
1273                 ffmpeg_property_add_string(rd, "video", "refs:2");
1274                 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1275                 ffmpeg_property_add_string(rd, "video", "directpred:3");
1276                 ffmpeg_property_add_string(rd, "video", "trellis:0");
1277                 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1278                 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1279                 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1280                 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1281
1282                 if(rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1283                         ffmpeg_property_add_string(rd, "video", "cqp:0");
1284         }
1285 #if 0   /* disabled for after release */
1286         else if(codec_id == CODEC_ID_DNXHD) {
1287                 if(rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1288                         ffmpeg_property_add_string(rd, "video", "mbd:rd");
1289         }
1290 #endif
1291 }
1292
1293 void ffmpeg_set_preset(RenderData *rd, int preset)
1294 {
1295         int isntsc = (rd->frs_sec != 25);
1296
1297         if(rd->ffcodecdata.properties)
1298                 IDP_FreeProperty(rd->ffcodecdata.properties);
1299
1300         switch (preset) {
1301         case FFMPEG_PRESET_VCD:
1302                 rd->ffcodecdata.type = FFMPEG_MPEG1;
1303                 rd->ffcodecdata.video_bitrate = 1150;
1304                 rd->xsch = 352;
1305                 rd->ysch = isntsc ? 240 : 288;
1306                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1307                 rd->ffcodecdata.rc_max_rate = 1150;
1308                 rd->ffcodecdata.rc_min_rate = 1150;
1309                 rd->ffcodecdata.rc_buffer_size = 40*8;
1310                 rd->ffcodecdata.mux_packet_size = 2324;
1311                 rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1312                 break;
1313
1314         case FFMPEG_PRESET_SVCD:
1315                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1316                 rd->ffcodecdata.video_bitrate = 2040;
1317                 rd->xsch = 480;
1318                 rd->ysch = isntsc ? 480 : 576;
1319                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1320                 rd->ffcodecdata.rc_max_rate = 2516;
1321                 rd->ffcodecdata.rc_min_rate = 0;
1322                 rd->ffcodecdata.rc_buffer_size = 224*8;
1323                 rd->ffcodecdata.mux_packet_size = 2324;
1324                 rd->ffcodecdata.mux_rate = 0;
1325                 break;
1326
1327         case FFMPEG_PRESET_DVD:
1328                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1329                 rd->ffcodecdata.video_bitrate = 6000;
1330
1331                 /* Don't set resolution, see [#21351]
1332                  * rd->xsch = 720;
1333                  * rd->ysch = isntsc ? 480 : 576; */
1334
1335                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1336                 rd->ffcodecdata.rc_max_rate = 9000;
1337                 rd->ffcodecdata.rc_min_rate = 0;
1338                 rd->ffcodecdata.rc_buffer_size = 224*8;
1339                 rd->ffcodecdata.mux_packet_size = 2048;
1340                 rd->ffcodecdata.mux_rate = 10080000;
1341                 break;
1342
1343         case FFMPEG_PRESET_DV:
1344                 rd->ffcodecdata.type = FFMPEG_DV;
1345                 rd->xsch = 720;
1346                 rd->ysch = isntsc ? 480 : 576;
1347                 break;
1348
1349         case FFMPEG_PRESET_H264:
1350                 rd->ffcodecdata.type = FFMPEG_AVI;
1351                 rd->ffcodecdata.codec = CODEC_ID_H264;
1352                 rd->ffcodecdata.video_bitrate = 6000;
1353                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1354                 rd->ffcodecdata.rc_max_rate = 9000;
1355                 rd->ffcodecdata.rc_min_rate = 0;
1356                 rd->ffcodecdata.rc_buffer_size = 224*8;
1357                 rd->ffcodecdata.mux_packet_size = 2048;
1358                 rd->ffcodecdata.mux_rate = 10080000;
1359
1360                 break;
1361
1362         case FFMPEG_PRESET_THEORA:
1363         case FFMPEG_PRESET_XVID:
1364                 if(preset == FFMPEG_PRESET_XVID) {
1365                         rd->ffcodecdata.type = FFMPEG_AVI;
1366                         rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1367                 }
1368                 else if(preset == FFMPEG_PRESET_THEORA) {
1369                         rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1370                         rd->ffcodecdata.codec = CODEC_ID_THEORA;
1371                 }
1372
1373                 rd->ffcodecdata.video_bitrate = 6000;
1374                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1375                 rd->ffcodecdata.rc_max_rate = 9000;
1376                 rd->ffcodecdata.rc_min_rate = 0;
1377                 rd->ffcodecdata.rc_buffer_size = 224*8;
1378                 rd->ffcodecdata.mux_packet_size = 2048;
1379                 rd->ffcodecdata.mux_rate = 10080000;
1380                 break;
1381
1382         }
1383
1384         ffmpeg_set_expert_options(rd);
1385 }
1386
1387 void ffmpeg_verify_image_type(RenderData *rd, ImageFormatData *imf)
1388 {
1389         int audio= 0;
1390
1391         if(imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1392                 if(rd->ffcodecdata.type <= 0 ||
1393                    rd->ffcodecdata.codec <= 0 ||
1394                    rd->ffcodecdata.audio_codec <= 0 ||
1395                    rd->ffcodecdata.video_bitrate <= 1) {
1396
1397                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1398
1399                         ffmpeg_set_preset(rd, FFMPEG_PRESET_DVD);
1400                 }
1401                 if(rd->ffcodecdata.type == FFMPEG_OGG) {
1402                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1403                 }
1404
1405                 audio= 1;
1406         }
1407         else if(imf->imtype == R_IMF_IMTYPE_H264) {
1408                 if(rd->ffcodecdata.codec != CODEC_ID_H264) {
1409                         ffmpeg_set_preset(rd, FFMPEG_PRESET_H264);
1410                         audio= 1;
1411                 }
1412         }
1413         else if(imf->imtype == R_IMF_IMTYPE_XVID) {
1414                 if(rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1415                         ffmpeg_set_preset(rd, FFMPEG_PRESET_XVID);
1416                         audio= 1;
1417                 }
1418         }
1419         else if(imf->imtype == R_IMF_IMTYPE_THEORA) {
1420                 if(rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1421                         ffmpeg_set_preset(rd, FFMPEG_PRESET_THEORA);
1422                         audio= 1;
1423                 }
1424         }
1425
1426         if(audio && rd->ffcodecdata.audio_codec < 0) {
1427                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1428                 rd->ffcodecdata.audio_bitrate = 128;
1429         }
1430 }
1431
1432 void ffmpeg_verify_codec_settings(RenderData *rd)
1433 {
1434         ffmpeg_set_expert_options(rd);
1435 }
1436
1437 int ffmpeg_alpha_channel_supported(RenderData *rd)
1438 {
1439         int codec = rd->ffcodecdata.codec;
1440
1441         if (codec == CODEC_ID_QTRLE)
1442                 return TRUE;
1443
1444 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1445         if (codec == CODEC_ID_FFV1)
1446                 return TRUE;
1447 #endif
1448
1449         return FALSE;
1450 }
1451
1452 #endif