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