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