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