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