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