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