Patch #34569: Enable PNG Codec for video output
[blender.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s):
19  *
20  * Partial Copyright (c) 2006 Peter Schlaile
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/blenkernel/intern/writeffmpeg.c
26  *  \ingroup bke
27  */
28
29 #ifdef WITH_FFMPEG
30 #include <string.h>
31 #include <stdio.h>
32
33 #if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
34 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
35 #if _MSC_VER < 1400
36 #include <stdint.h>
37 #endif
38 #endif
39
40 #include <stdlib.h>
41
42 #include <libavformat/avformat.h>
43 #include <libavcodec/avcodec.h>
44 #include <libavutil/rational.h>
45 #include <libavutil/samplefmt.h>
46 #include <libswscale/swscale.h>
47
48 #include "MEM_guardedalloc.h"
49
50 #include "DNA_scene_types.h"
51
52 #include "BLI_blenlib.h"
53
54 #ifdef WITH_AUDASPACE
55 #  include "AUD_C-API.h"
56 #endif
57
58 #include "BLI_utildefines.h"
59
60 #include "BKE_global.h"
61 #include "BKE_idprop.h"
62 #include "BKE_main.h"
63 #include "BKE_report.h"
64 #include "BKE_sound.h"
65 #include "BKE_writeffmpeg.h"
66
67 #include "IMB_imbuf_types.h"
68 #include "IMB_imbuf.h"
69
70 #include "ffmpeg_compat.h"
71
72 static int ffmpeg_type = 0;
73 static int ffmpeg_codec = CODEC_ID_MPEG4;
74 static int ffmpeg_audio_codec = CODEC_ID_NONE;
75 static int ffmpeg_video_bitrate = 1150;
76 static int ffmpeg_audio_bitrate = 128;
77 static int ffmpeg_gop_size = 12;
78 static int ffmpeg_autosplit = 0;
79 static int ffmpeg_autosplit_count = 0;
80
81 static AVFormatContext *outfile = 0;
82 static AVStream *video_stream = 0;
83 static AVStream *audio_stream = 0;
84 static AVFrame *current_frame = 0;
85 static struct SwsContext *img_convert_ctx = 0;
86
87 static uint8_t *video_buffer = 0;
88 static int video_buffersize = 0;
89
90 static uint8_t *audio_input_buffer = 0;
91 static int audio_input_samples = 0;
92 static uint8_t *audio_output_buffer = 0;
93 static int audio_outbuf_size = 0;
94 static double audio_time = 0.0f;
95
96 #ifdef WITH_AUDASPACE
97 static AUD_Device *audio_mixdown_device = 0;
98 #endif
99
100 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
101
102 #define PRINT if (G.debug & G_DEBUG_FFMPEG) printf
103
104 /* Delete a picture buffer */
105
106 static void delete_picture(AVFrame *f)
107 {
108         if (f) {
109                 if (f->data[0]) MEM_freeN(f->data[0]);
110                 av_free(f);
111         }
112 }
113
114 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         int fail = TRUE;
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                         fail = av_opt_set(c, prop->name, IDP_String(prop), 0);
392                         break;
393                 case IDP_FLOAT:
394                         PRINT("%g.\n", IDP_Float(prop));
395                         fail = av_opt_set_double(c, prop->name, IDP_Float(prop), 0);
396                         break;
397                 case IDP_INT:
398                         PRINT("%d.\n", IDP_Int(prop));
399
400                         if (param) {
401                                 if (IDP_Int(prop)) {
402                                         fail = av_opt_set(c, name, param, 0);
403                                 }
404                                 else {
405                                         return;
406                                 }
407                         }
408                         else {
409                                 fail = av_opt_set_int(c, prop->name, IDP_Int(prop), 0);
410                         }
411                         break;
412         }
413
414         if (fail) {
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 = avformat_new_stream(of, NULL);
468         if (!st) return NULL;
469         st->id = 0;
470
471         /* Set up the codec context */
472         
473         c = st->codec;
474         c->codec_id = codec_id;
475         c->codec_type = AVMEDIA_TYPE_VIDEO;
476
477         /* Get some values from the current render settings */
478         
479         c->width = rectx;
480         c->height = recty;
481
482         /* FIXME: Really bad hack (tm) for NTSC support */
483         if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
484                 c->time_base.den = 2997;
485                 c->time_base.num = 100;
486         }
487         else if ((float) ((int) rd->frs_sec_base) == rd->frs_sec_base) {
488                 c->time_base.den = rd->frs_sec;
489                 c->time_base.num = (int) rd->frs_sec_base;
490         }
491         else {
492                 c->time_base.den = rd->frs_sec * 100000;
493                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
494         }
495         
496         c->gop_size = ffmpeg_gop_size;
497         c->bit_rate = ffmpeg_video_bitrate * 1000;
498         c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
499         c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
500         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
501
502 #if 0
503         /* this options are not set in ffmpeg.c and leads to artifacts with MPEG-4
504          * see #33586: Encoding to mpeg4 makes first frame(s) blocky
505          */
506         c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
507         c->rc_buffer_aggressivity = 1.0;
508 #endif
509
510         c->me_method = ME_EPZS;
511         
512         codec = avcodec_find_encoder(c->codec_id);
513         if (!codec)
514                 return NULL;
515         
516         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
517
518         if (codec->pix_fmts) {
519                 c->pix_fmt = codec->pix_fmts[0];
520         }
521         else {
522                 /* makes HuffYUV happy ... */
523                 c->pix_fmt = PIX_FMT_YUV422P;
524         }
525
526         if (ffmpeg_type == FFMPEG_XVID) {
527                 /* arghhhh ... */
528                 c->pix_fmt = PIX_FMT_YUV420P;
529                 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
530         }
531
532         if (codec_id == CODEC_ID_H264) {
533                 /* correct wrong default ffmpeg param which crash x264 */
534                 c->qmin = 10;
535                 c->qmax = 51;
536         }
537         
538         /* Keep lossless encodes in the RGB domain. */
539         if (codec_id == CODEC_ID_HUFFYUV) {
540                 /* HUFFYUV was PIX_FMT_YUV422P before */
541                 c->pix_fmt = PIX_FMT_RGB32;
542         }
543
544         if (codec_id == CODEC_ID_FFV1) {
545                 c->pix_fmt = PIX_FMT_RGB32;
546         }
547
548         if (codec_id == CODEC_ID_QTRLE) {
549                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
550                         c->pix_fmt = PIX_FMT_ARGB;
551                 }
552         }
553
554         if (codec_id == CODEC_ID_PNG) {
555                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
556                         c->pix_fmt = PIX_FMT_ARGB;
557                 }
558         }
559
560         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
561 //              || !strcmp(of->oformat->name, "mp4")
562 //          || !strcmp(of->oformat->name, "mov")
563 //          || !strcmp(of->oformat->name, "3gp")
564             )
565         {
566                 PRINT("Using global header\n");
567                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
568         }
569         
570         /* Determine whether we are encoding interlaced material or not */
571         if (rd->mode & R_FIELDS) {
572                 PRINT("Encoding interlaced video\n");
573                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
574                 c->flags |= CODEC_FLAG_INTERLACED_ME;
575         }
576
577         /* xasp & yasp got float lately... */
578
579         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);
580
581         set_ffmpeg_properties(rd, c, "video");
582         
583         if (avcodec_open2(c, codec, NULL) < 0) {
584                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
585                 return NULL;
586         }
587
588         if (codec_id == CODEC_ID_QTRLE) {
589                 /* normally it should be enough to have buffer with actual image size,
590                  * but some codecs like QTRLE might store extra information in this buffer,
591                  * so it should be a way larger */
592
593                 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
594                  * (from FFmpeg sources) */
595                 int size = c->width * c->height;
596                 video_buffersize = 7 * size + 10000;
597         }
598         else
599                 video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
600
601         video_buffer = (uint8_t *)MEM_mallocN(video_buffersize * sizeof(uint8_t), "FFMPEG video buffer");
602         
603         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
604
605         img_convert_ctx = sws_getContext(c->width, c->height, PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
606                                          NULL, NULL, NULL);
607         return st;
608 }
609
610 /* Prepare an audio stream for the output file */
611
612 static AVStream *alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext *of, char *error, int error_size)
613 {
614         AVStream *st;
615         AVCodecContext *c;
616         AVCodec *codec;
617
618         error[0] = '\0';
619
620         st = avformat_new_stream(of, NULL);
621         if (!st) return NULL;
622         st->id = 1;
623
624         c = st->codec;
625         c->codec_id = codec_id;
626         c->codec_type = AVMEDIA_TYPE_AUDIO;
627
628         c->sample_rate = rd->ffcodecdata.audio_mixrate;
629         c->bit_rate = ffmpeg_audio_bitrate * 1000;
630         c->sample_fmt = AV_SAMPLE_FMT_S16;
631         c->channels = rd->ffcodecdata.audio_channels;
632         if (use_float_audio_buffer(codec_id)) {
633                 c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
634                 c->sample_fmt = AV_SAMPLE_FMT_FLT;
635         }
636         codec = avcodec_find_encoder(c->codec_id);
637         if (!codec) {
638                 //XXX error("Couldn't find a valid audio codec");
639                 return NULL;
640         }
641
642         set_ffmpeg_properties(rd, c, "audio");
643
644         if (avcodec_open2(c, codec, NULL) < 0) {
645                 //XXX error("Couldn't initialize audio codec");
646                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
647                 return NULL;
648         }
649
650         /* need to prevent floating point exception when using vorbis audio codec,
651          * initialize this value in the same way as it's done in FFmpeg iteslf (sergey) */
652         st->codec->time_base.num = 1;
653         st->codec->time_base.den = st->codec->sample_rate;
654
655         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
656
657         if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
658                 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
659         else {
660                 audio_input_samples = c->frame_size;
661                 if (c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
662                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
663         }
664
665         audio_output_buffer = (uint8_t *) av_malloc(audio_outbuf_size);
666
667         if (use_float_audio_buffer(codec_id)) {
668                 audio_input_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * sizeof(float));
669         }
670         else {
671                 audio_input_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * sizeof(int16_t));
672         }
673
674         audio_time = 0.0f;
675
676         return st;
677 }
678 /* essential functions -- start, append, end */
679
680 static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
681 {
682         char buffer[32];
683
684         BLI_snprintf(buffer, sizeof(buffer), "%d", value);
685
686         av_dict_set(dict, key, buffer, 0);
687 }
688
689 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
690 {
691         /* Handle to the output file */
692         AVFormatContext *of;
693         AVOutputFormat *fmt;
694         AVDictionary *opts = NULL;
695         char name[256], error[1024];
696         const char **exts;
697
698         ffmpeg_type = rd->ffcodecdata.type;
699         ffmpeg_codec = rd->ffcodecdata.codec;
700         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
701         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
702         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
703         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
704         ffmpeg_autosplit = rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT;
705         
706         /* Determine the correct filename */
707         BKE_ffmpeg_filepath_get(name, rd);
708         PRINT("Starting output to %s(ffmpeg)...\n"
709                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
710                 "  video_bitrate=%d, audio_bitrate=%d,\n"
711                 "  gop_size=%d, autosplit=%d\n"
712                 "  render width=%d, render height=%d\n",
713                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
714                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
715                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
716         
717         exts = get_file_extensions(ffmpeg_type);
718         if (!exts) {
719                 BKE_report(reports, RPT_ERROR, "No valid formats found");
720                 return 0;
721         }
722         fmt = av_guess_format(NULL, exts[0], NULL);
723         if (!fmt) {
724                 BKE_report(reports, RPT_ERROR, "No valid formats found");
725                 return 0;
726         }
727
728         of = avformat_alloc_context();
729         if (!of) {
730                 BKE_report(reports, RPT_ERROR, "Error opening output file");
731                 return 0;
732         }
733         
734         of->oformat = fmt;
735         of->packet_size = rd->ffcodecdata.mux_packet_size;
736         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
737                 ffmpeg_dict_set_int(&opts, "muxrate", rd->ffcodecdata.mux_rate);
738         }
739         else {
740                 av_dict_set(&opts, "muxrate", "0", 0);
741         }
742
743         ffmpeg_dict_set_int(&opts, "preload", (int)(0.5 * AV_TIME_BASE));
744
745         of->max_delay = (int)(0.7 * AV_TIME_BASE);
746
747         fmt->audio_codec = ffmpeg_audio_codec;
748
749         BLI_snprintf(of->filename, sizeof(of->filename), "%s", name);
750         /* set the codec to the user's selection */
751         switch (ffmpeg_type) {
752                 case FFMPEG_AVI:
753                 case FFMPEG_MOV:
754                 case FFMPEG_MKV:
755                         fmt->video_codec = ffmpeg_codec;
756                         break;
757                 case FFMPEG_OGG:
758                         fmt->video_codec = CODEC_ID_THEORA;
759                         break;
760                 case FFMPEG_DV:
761                         fmt->video_codec = CODEC_ID_DVVIDEO;
762                         break;
763                 case FFMPEG_MPEG1:
764                         fmt->video_codec = CODEC_ID_MPEG1VIDEO;
765                         break;
766                 case FFMPEG_MPEG2:
767                         fmt->video_codec = CODEC_ID_MPEG2VIDEO;
768                         break;
769                 case FFMPEG_H264:
770                         fmt->video_codec = CODEC_ID_H264;
771                         break;
772                 case FFMPEG_XVID:
773                         fmt->video_codec = CODEC_ID_MPEG4;
774                         break;
775                 case FFMPEG_FLV:
776                         fmt->video_codec = CODEC_ID_FLV1;
777                         break;
778                 case FFMPEG_MP3:
779                         fmt->audio_codec = CODEC_ID_MP3;
780                 case FFMPEG_WAV:
781                         fmt->video_codec = CODEC_ID_NONE;
782                         break;
783                 case FFMPEG_MPEG4:
784                 default:
785                         fmt->video_codec = CODEC_ID_MPEG4;
786                         break;
787         }
788         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
789                 if (rectx != 720) {
790                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
791                         return 0;
792                 }
793                 if (rd->frs_sec != 25 && recty != 480) {
794                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
795                         return 0;
796                 }
797                 if (rd->frs_sec == 25 && recty != 576) {
798                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
799                         return 0;
800                 }
801         }
802         
803         if (ffmpeg_type == FFMPEG_DV) {
804                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
805                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
806                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
807                         av_dict_free(&opts);
808                         return 0;
809                 }
810         }
811         
812         if (fmt->video_codec != CODEC_ID_NONE) {
813                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty, error, sizeof(error));
814                 PRINT("alloc video stream %p\n", video_stream);
815                 if (!video_stream) {
816                         if (error[0])
817                                 BKE_report(reports, RPT_ERROR, error);
818                         else
819                                 BKE_report(reports, RPT_ERROR, "Error initializing video stream");
820
821                         av_dict_free(&opts);
822                         return 0;
823                 }
824         }
825
826         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
827                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of, error, sizeof(error));
828                 if (!audio_stream) {
829                         if (error[0])
830                                 BKE_report(reports, RPT_ERROR, error);
831                         else
832                                 BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
833                         av_dict_free(&opts);
834                         return 0;
835                 }
836         }
837         if (!(fmt->flags & AVFMT_NOFILE)) {
838                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
839                         BKE_report(reports, RPT_ERROR, "Could not open file for writing");
840                         av_dict_free(&opts);
841                         return 0;
842                 }
843         }
844         if (avformat_write_header(of, NULL) < 0) {
845                 BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
846                 av_dict_free(&opts);
847                 avio_close(of->pb);
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 static void end_ffmpeg_impl(int is_autosplit);
991
992 #ifdef WITH_AUDASPACE
993 static void write_audio_frames(double to_pts)
994 {
995         int finished = 0;
996
997         while (audio_stream && !finished) {
998                 if ((audio_time >= to_pts) ||
999                     (write_audio_frame()))
1000                 {
1001                         finished = 1;
1002                 }
1003         }
1004 }
1005 #endif
1006
1007 int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
1008 {
1009         AVFrame *avframe;
1010         int success = 1;
1011
1012         PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);
1013
1014 /* why is this done before writing the video frame and again at end_ffmpeg? */
1015 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
1016
1017         if (video_stream) {
1018                 avframe = generate_video_frame((unsigned char *) pixels, reports);
1019                 success = (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
1020
1021                 if (ffmpeg_autosplit) {
1022                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
1023                                 end_ffmpeg_impl(TRUE);
1024                                 ffmpeg_autosplit_count++;
1025                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
1026                         }
1027                 }
1028         }
1029
1030 #ifdef WITH_AUDASPACE
1031         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / (double)rd->frs_sec_base));
1032 #endif
1033         return success;
1034 }
1035
1036 static void end_ffmpeg_impl(int is_autosplit)
1037 {
1038         unsigned int i;
1039         
1040         PRINT("Closing ffmpeg...\n");
1041
1042 #if 0
1043         if (audio_stream) { /* SEE UPPER */
1044                 write_audio_frames();
1045         }
1046 #endif
1047
1048 #ifdef WITH_AUDASPACE
1049         if (is_autosplit == FALSE) {
1050                 if (audio_mixdown_device) {
1051                         AUD_closeReadDevice(audio_mixdown_device);
1052                         audio_mixdown_device = 0;
1053                 }
1054         }
1055 #endif
1056
1057         if (video_stream && video_stream->codec) {
1058                 PRINT("Flushing delayed frames...\n");
1059                 flush_ffmpeg();
1060         }
1061         
1062         if (outfile) {
1063                 av_write_trailer(outfile);
1064         }
1065         
1066         /* Close the video codec */
1067
1068         if (video_stream && video_stream->codec) {
1069                 avcodec_close(video_stream->codec);
1070                 PRINT("zero video stream %p\n", video_stream);
1071                 video_stream = 0;
1072         }
1073
1074         
1075         /* Close the output file */
1076         if (outfile) {
1077                 for (i = 0; i < outfile->nb_streams; i++) {
1078                         if (&outfile->streams[i]) {
1079                                 av_freep(&outfile->streams[i]);
1080                         }
1081                 }
1082         }
1083         /* free the temp buffer */
1084         if (current_frame) {
1085                 delete_picture(current_frame);
1086                 current_frame = 0;
1087         }
1088         if (outfile && outfile->oformat) {
1089                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1090                         avio_close(outfile->pb);
1091                 }
1092         }
1093         if (outfile) {
1094                 av_free(outfile);
1095                 outfile = 0;
1096         }
1097         if (video_buffer) {
1098                 MEM_freeN(video_buffer);
1099                 video_buffer = 0;
1100         }
1101         if (audio_output_buffer) {
1102                 av_free(audio_output_buffer);
1103                 audio_output_buffer = 0;
1104         }
1105         if (audio_input_buffer) {
1106                 av_free(audio_input_buffer);
1107                 audio_input_buffer = 0;
1108         }
1109
1110         if (img_convert_ctx) {
1111                 sws_freeContext(img_convert_ctx);
1112                 img_convert_ctx = 0;
1113         }
1114 }
1115
1116 void BKE_ffmpeg_end(void)
1117 {
1118         end_ffmpeg_impl(FALSE);
1119 }
1120
1121 /* properties */
1122
1123 void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1124 {
1125         struct IDProperty *prop = (struct IDProperty *) prop_;
1126         IDProperty *group;
1127         
1128         if (!rd->ffcodecdata.properties) {
1129                 return;
1130         }
1131
1132         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1133         if (group && prop) {
1134                 IDP_RemFromGroup(group, prop);
1135                 IDP_FreeProperty(prop);
1136                 MEM_freeN(prop);
1137         }
1138 }
1139
1140 IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1141 {
1142         AVCodecContext c;
1143         const AVOption *o;
1144         const AVOption *parent;
1145         IDProperty *group;
1146         IDProperty *prop;
1147         IDPropertyTemplate val;
1148         int idp_type;
1149         char name[256];
1150         
1151         val.i = 0;
1152
1153         avcodec_get_context_defaults3(&c, NULL);
1154
1155         o = c.av_class->option + opt_index;
1156         parent = c.av_class->option + parent_index;
1157
1158         if (!rd->ffcodecdata.properties) {
1159                 rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1160         }
1161
1162         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1163         
1164         if (!group) {
1165                 group = IDP_New(IDP_GROUP, &val, type);
1166                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1167         }
1168
1169         if (parent_index) {
1170                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1171         }
1172         else {
1173                 BLI_strncpy(name, o->name, sizeof(name));
1174         }
1175
1176         PRINT("ffmpeg_property_add: %s %d %d %s\n", type, parent_index, opt_index, name);
1177
1178         prop = IDP_GetPropertyFromGroup(group, name);
1179         if (prop) {
1180                 return prop;
1181         }
1182
1183         switch (o->type) {
1184                 case AV_OPT_TYPE_INT:
1185                 case AV_OPT_TYPE_INT64:
1186                         val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1187                         idp_type = IDP_INT;
1188                         break;
1189                 case AV_OPT_TYPE_DOUBLE:
1190                 case AV_OPT_TYPE_FLOAT:
1191                         val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1192                         idp_type = IDP_FLOAT;
1193                         break;
1194                 case AV_OPT_TYPE_STRING:
1195                         val.string.str = (char *)"                                                                               ";
1196                         val.string.len = 80;
1197 /*              val.str = (char *)"                                                                               ";*/
1198                         idp_type = IDP_STRING;
1199                         break;
1200                 case AV_OPT_TYPE_CONST:
1201                         val.i = 1;
1202                         idp_type = IDP_INT;
1203                         break;
1204                 default:
1205                         return NULL;
1206         }
1207         prop = IDP_New(idp_type, &val, name);
1208         IDP_AddToGroup(group, prop);
1209         return prop;
1210 }
1211
1212 /* not all versions of ffmpeg include that, so here we go ... */
1213
1214 static const AVOption *my_av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
1215 {
1216         AVClass *c = *(AVClass **)v;
1217         const AVOption *o = c->option;
1218
1219         for (; o && o->name; o++) {
1220                 if (!strcmp(o->name, name) &&
1221                     (!unit || (o->unit && !strcmp(o->unit, unit))) &&
1222                     (o->flags & mask) == flags)
1223                 {
1224                         return o;
1225                 }
1226         }
1227         return NULL;
1228 }
1229
1230 int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *str)
1231 {
1232         AVCodecContext c;
1233         const AVOption *o = 0;
1234         const AVOption *p = 0;
1235         char name_[128];
1236         char *name;
1237         char *param;
1238         IDProperty *prop = NULL;
1239         
1240         avcodec_get_context_defaults3(&c, NULL);
1241
1242         strncpy(name_, str, sizeof(name_));
1243
1244         name = name_;
1245         while (*name == ' ') name++;
1246
1247         param = strchr(name, ':');
1248
1249         if (!param) {
1250                 param = strchr(name, ' ');
1251         }
1252         if (param) {
1253                 *param++ = 0;
1254                 while (*param == ' ') param++;
1255         }
1256         
1257         o = my_av_find_opt(&c, name, NULL, 0, 0);
1258         if (!o) {
1259                 return 0;
1260         }
1261         if (param && o->type == AV_OPT_TYPE_CONST) {
1262                 return 0;
1263         }
1264         if (param && o->type != AV_OPT_TYPE_CONST && o->unit) {
1265                 p = my_av_find_opt(&c, param, o->unit, 0, 0);
1266                 if (p) {
1267                         prop = BKE_ffmpeg_property_add(rd, (char *) type, p - c.av_class->option, o - c.av_class->option);
1268                 }
1269         }
1270         else {
1271                 prop = BKE_ffmpeg_property_add(rd, (char *) type, o - c.av_class->option, 0);
1272         }
1273                 
1274
1275         if (!prop) {
1276                 return 0;
1277         }
1278
1279         if (param && !p) {
1280                 switch (prop->type) {
1281                         case IDP_INT:
1282                                 IDP_Int(prop) = atoi(param);
1283                                 break;
1284                         case IDP_FLOAT:
1285                                 IDP_Float(prop) = atof(param);
1286                                 break;
1287                         case IDP_STRING:
1288                                 strncpy(IDP_String(prop), param, prop->len);
1289                                 break;
1290                 }
1291         }
1292         return 1;
1293 }
1294
1295 static void ffmpeg_set_expert_options(RenderData *rd)
1296 {
1297         int codec_id = rd->ffcodecdata.codec;
1298
1299         if (rd->ffcodecdata.properties)
1300                 IDP_FreeProperty(rd->ffcodecdata.properties);
1301
1302         if (codec_id == CODEC_ID_H264) {
1303                 /*
1304                  * All options here are for x264, but must be set via ffmpeg.
1305                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1306                  * to get a list.
1307                  */
1308
1309                 /*
1310                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1311                  * crashes Blender for some reason. Either way - this is no big deal.
1312                  */
1313                 BKE_ffmpeg_property_add_string(rd, "video", "coder:vlc");
1314
1315                 /*
1316                  * The other options were taken from the libx264-default.preset
1317                  * included in the ffmpeg distribution.
1318                  */
1319 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1320                 BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1321                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1322                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1323                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1324                 BKE_ffmpeg_property_add_string(rd, "video", "me:hex");
1325                 BKE_ffmpeg_property_add_string(rd, "video", "subq:6");
1326                 BKE_ffmpeg_property_add_string(rd, "video", "me_range:16");
1327                 BKE_ffmpeg_property_add_string(rd, "video", "qdiff:4");
1328                 BKE_ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1329                 BKE_ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1330                 BKE_ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1331                 BKE_ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1332                 BKE_ffmpeg_property_add_string(rd, "video", "bf:3");
1333                 BKE_ffmpeg_property_add_string(rd, "video", "refs:2");
1334                 BKE_ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1335                 BKE_ffmpeg_property_add_string(rd, "video", "directpred:3");
1336                 BKE_ffmpeg_property_add_string(rd, "video", "trellis:0");
1337                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1338                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1339                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1340                 BKE_ffmpeg_property_add_string(rd, "video", "wpredp:2");
1341
1342                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1343                         BKE_ffmpeg_property_add_string(rd, "video", "cqp:0");
1344         }
1345         else if (codec_id == CODEC_ID_DNXHD) {
1346                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1347                         BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd");
1348         }
1349 }
1350
1351 void BKE_ffmpeg_preset_set(RenderData *rd, int preset)
1352 {
1353         int isntsc = (rd->frs_sec != 25);
1354
1355         if (rd->ffcodecdata.properties)
1356                 IDP_FreeProperty(rd->ffcodecdata.properties);
1357
1358         switch (preset) {
1359                 case FFMPEG_PRESET_VCD:
1360                         rd->ffcodecdata.type = FFMPEG_MPEG1;
1361                         rd->ffcodecdata.video_bitrate = 1150;
1362                         rd->xsch = 352;
1363                         rd->ysch = isntsc ? 240 : 288;
1364                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1365                         rd->ffcodecdata.rc_max_rate = 1150;
1366                         rd->ffcodecdata.rc_min_rate = 1150;
1367                         rd->ffcodecdata.rc_buffer_size = 40 * 8;
1368                         rd->ffcodecdata.mux_packet_size = 2324;
1369                         rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1370                         break;
1371
1372                 case FFMPEG_PRESET_SVCD:
1373                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1374                         rd->ffcodecdata.video_bitrate = 2040;
1375                         rd->xsch = 480;
1376                         rd->ysch = isntsc ? 480 : 576;
1377                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1378                         rd->ffcodecdata.rc_max_rate = 2516;
1379                         rd->ffcodecdata.rc_min_rate = 0;
1380                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1381                         rd->ffcodecdata.mux_packet_size = 2324;
1382                         rd->ffcodecdata.mux_rate = 0;
1383                         break;
1384
1385                 case FFMPEG_PRESET_DVD:
1386                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1387                         rd->ffcodecdata.video_bitrate = 6000;
1388
1389                         /* Don't set resolution, see [#21351]
1390                          * rd->xsch = 720;
1391                          * rd->ysch = isntsc ? 480 : 576; */
1392
1393                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1394                         rd->ffcodecdata.rc_max_rate = 9000;
1395                         rd->ffcodecdata.rc_min_rate = 0;
1396                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1397                         rd->ffcodecdata.mux_packet_size = 2048;
1398                         rd->ffcodecdata.mux_rate = 10080000;
1399                         break;
1400
1401                 case FFMPEG_PRESET_DV:
1402                         rd->ffcodecdata.type = FFMPEG_DV;
1403                         rd->xsch = 720;
1404                         rd->ysch = isntsc ? 480 : 576;
1405                         break;
1406
1407                 case FFMPEG_PRESET_H264:
1408                         rd->ffcodecdata.type = FFMPEG_AVI;
1409                         rd->ffcodecdata.codec = CODEC_ID_H264;
1410                         rd->ffcodecdata.video_bitrate = 6000;
1411                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1412                         rd->ffcodecdata.rc_max_rate = 9000;
1413                         rd->ffcodecdata.rc_min_rate = 0;
1414                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1415                         rd->ffcodecdata.mux_packet_size = 2048;
1416                         rd->ffcodecdata.mux_rate = 10080000;
1417
1418                         break;
1419
1420                 case FFMPEG_PRESET_THEORA:
1421                 case FFMPEG_PRESET_XVID:
1422                         if (preset == FFMPEG_PRESET_XVID) {
1423                                 rd->ffcodecdata.type = FFMPEG_AVI;
1424                                 rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1425                         }
1426                         else if (preset == FFMPEG_PRESET_THEORA) {
1427                                 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1428                                 rd->ffcodecdata.codec = CODEC_ID_THEORA;
1429                         }
1430
1431                         rd->ffcodecdata.video_bitrate = 6000;
1432                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1433                         rd->ffcodecdata.rc_max_rate = 9000;
1434                         rd->ffcodecdata.rc_min_rate = 0;
1435                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1436                         rd->ffcodecdata.mux_packet_size = 2048;
1437                         rd->ffcodecdata.mux_rate = 10080000;
1438                         break;
1439
1440         }
1441
1442         ffmpeg_set_expert_options(rd);
1443 }
1444
1445 void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
1446 {
1447         int audio = 0;
1448
1449         if (imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1450                 if (rd->ffcodecdata.type <= 0 ||
1451                     rd->ffcodecdata.codec <= 0 ||
1452                     rd->ffcodecdata.audio_codec <= 0 ||
1453                     rd->ffcodecdata.video_bitrate <= 1)
1454                 {
1455                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1456
1457                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_DVD);
1458                 }
1459                 if (rd->ffcodecdata.type == FFMPEG_OGG) {
1460                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1461                 }
1462
1463                 audio = 1;
1464         }
1465         else if (imf->imtype == R_IMF_IMTYPE_H264) {
1466                 if (rd->ffcodecdata.codec != CODEC_ID_H264) {
1467                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
1468                         audio = 1;
1469                 }
1470         }
1471         else if (imf->imtype == R_IMF_IMTYPE_XVID) {
1472                 if (rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1473                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_XVID);
1474                         audio = 1;
1475                 }
1476         }
1477         else if (imf->imtype == R_IMF_IMTYPE_THEORA) {
1478                 if (rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1479                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_THEORA);
1480                         audio = 1;
1481                 }
1482         }
1483
1484         if (audio && rd->ffcodecdata.audio_codec < 0) {
1485                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1486                 rd->ffcodecdata.audio_bitrate = 128;
1487         }
1488 }
1489
1490 void BKE_ffmpeg_codec_settings_verify(RenderData *rd)
1491 {
1492         ffmpeg_set_expert_options(rd);
1493 }
1494
1495 int BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd)
1496 {
1497         int codec = rd->ffcodecdata.codec;
1498
1499         if (codec == CODEC_ID_QTRLE)
1500                 return TRUE;
1501
1502         if (codec == CODEC_ID_PNG)
1503                 return TRUE;
1504
1505 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1506         if (codec == CODEC_ID_FFV1)
1507                 return TRUE;
1508 #endif
1509
1510         return FALSE;
1511 }
1512
1513 #endif