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