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