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