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