Merging r50602 through r50617 form trunk into soc-2011-tomato
[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, "Couldn't 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 ((double) ((int) rd->frs_sec_base) ==
482                  rd->frs_sec_base)
483         {
484                 c->time_base.den = rd->frs_sec;
485                 c->time_base.num = (int) rd->frs_sec_base;
486         }
487         else {
488                 c->time_base.den = rd->frs_sec * 100000;
489                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
490         }
491         
492         c->gop_size = ffmpeg_gop_size;
493         c->bit_rate = ffmpeg_video_bitrate * 1000;
494         c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
495         c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
496         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
497         c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
498         c->rc_buffer_aggressivity = 1.0;
499         c->me_method = ME_EPZS;
500         
501         codec = avcodec_find_encoder(c->codec_id);
502         if (!codec)
503                 return NULL;
504         
505         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
506
507         if (codec->pix_fmts) {
508                 c->pix_fmt = codec->pix_fmts[0];
509         }
510         else {
511                 /* makes HuffYUV happy ... */
512                 c->pix_fmt = PIX_FMT_YUV422P;
513         }
514
515         if (ffmpeg_type == FFMPEG_XVID) {
516                 /* arghhhh ... */
517                 c->pix_fmt = PIX_FMT_YUV420P;
518                 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
519         }
520
521         if (codec_id == CODEC_ID_H264) {
522                 /* correct wrong default ffmpeg param which crash x264 */
523                 c->qmin = 10;
524                 c->qmax = 51;
525         }
526         
527         /* Keep lossless encodes in the RGB domain. */
528         if (codec_id == CODEC_ID_HUFFYUV) {
529                 /* HUFFYUV was PIX_FMT_YUV422P before */
530                 c->pix_fmt = PIX_FMT_RGB32;
531         }
532
533         if (codec_id == CODEC_ID_FFV1) {
534 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
535                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
536                         c->pix_fmt = PIX_FMT_RGB32;
537                 }
538                 else {
539                         c->pix_fmt = PIX_FMT_BGR0;
540                 }
541 #else
542                 c->pix_fmt = PIX_FMT_RGB32;
543 #endif
544         }
545
546         if (codec_id == CODEC_ID_QTRLE) {
547                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
548                         c->pix_fmt = PIX_FMT_ARGB;
549                 }
550         }
551
552         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
553 //              || !strcmp(of->oformat->name, "mp4")
554 //          || !strcmp(of->oformat->name, "mov")
555 //          || !strcmp(of->oformat->name, "3gp")
556             )
557         {
558                 PRINT("Using global header\n");
559                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
560         }
561         
562         /* Determine whether we are encoding interlaced material or not */
563         if (rd->mode & R_FIELDS) {
564                 PRINT("Encoding interlaced video\n");
565                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
566                 c->flags |= CODEC_FLAG_INTERLACED_ME;
567         }
568
569         /* xasp & yasp got float lately... */
570
571         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);
572
573         set_ffmpeg_properties(rd, c, "video");
574         
575         if (avcodec_open(c, codec) < 0) {
576                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
577                 return NULL;
578         }
579
580         if (codec_id == CODEC_ID_QTRLE) {
581                 /* normally it should be enough to have buffer with actual image size,
582                  * but some codecs like QTRLE might store extra information in this buffer,
583                  * so it should be a way larger */
584
585                 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
586                  * (from FFmpeg sources) */
587                 int size = c->width * c->height;
588                 video_buffersize = 7 * size + 10000;
589         }
590         else
591                 video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
592
593         video_buffer = (uint8_t *)MEM_mallocN(video_buffersize * sizeof(uint8_t), "FFMPEG video buffer");
594         
595         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
596
597         img_convert_ctx = sws_getContext(c->width, c->height, PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
598                                          NULL, NULL, NULL);
599         return st;
600 }
601
602 /* Prepare an audio stream for the output file */
603
604 static AVStream *alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext *of)
605 {
606         AVStream *st;
607         AVCodecContext *c;
608         AVCodec *codec;
609
610         st = av_new_stream(of, 1);
611         if (!st) return NULL;
612
613         c = st->codec;
614         c->codec_id = codec_id;
615         c->codec_type = AVMEDIA_TYPE_AUDIO;
616
617         c->sample_rate = rd->ffcodecdata.audio_mixrate;
618         c->bit_rate = ffmpeg_audio_bitrate * 1000;
619         c->sample_fmt = AV_SAMPLE_FMT_S16;
620         c->channels = rd->ffcodecdata.audio_channels;
621         codec = avcodec_find_encoder(c->codec_id);
622         if (!codec) {
623                 //XXX error("Couldn't find a valid audio codec");
624                 return NULL;
625         }
626
627         set_ffmpeg_properties(rd, c, "audio");
628
629         if (avcodec_open(c, codec) < 0) {
630                 //XXX error("Couldn't initialize audio codec");
631                 return NULL;
632         }
633
634         /* need to prevent floating point exception when using vorbis audio codec,
635          * initialize this value in the same way as it's done in FFmpeg iteslf (sergey) */
636         st->codec->time_base.num = 1;
637         st->codec->time_base.den = st->codec->sample_rate;
638
639         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
640
641         if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
642                 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
643         else {
644                 audio_input_samples = c->frame_size;
645                 if (c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
646                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
647         }
648
649         audio_output_buffer = (uint8_t *) av_malloc(audio_outbuf_size);
650
651         audio_input_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * sizeof(int16_t));
652
653         audio_time = 0.0f;
654
655         return st;
656 }
657 /* essential functions -- start, append, end */
658
659 static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
660 {
661         char buffer[32];
662
663         BLI_snprintf(buffer, sizeof(buffer), "%d", value);
664
665         av_dict_set(dict, key, buffer, 0);
666 }
667
668 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
669 {
670         /* Handle to the output file */
671         AVFormatContext *of;
672         AVOutputFormat *fmt;
673         AVDictionary *opts = NULL;
674         char name[256], error[1024];
675         const char **exts;
676
677         ffmpeg_type = rd->ffcodecdata.type;
678         ffmpeg_codec = rd->ffcodecdata.codec;
679         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
680         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
681         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
682         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
683         ffmpeg_autosplit = rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT;
684         
685         /* Determine the correct filename */
686         BKE_ffmpeg_filepath_get(name, rd);
687         PRINT("Starting output to %s(ffmpeg)...\n"
688                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
689                 "  video_bitrate=%d, audio_bitrate=%d,\n"
690                 "  gop_size=%d, autosplit=%d\n"
691                 "  render width=%d, render height=%d\n",
692                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
693                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
694                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
695         
696         exts = get_file_extensions(ffmpeg_type);
697         if (!exts) {
698                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
699                 return 0;
700         }
701         fmt = av_guess_format(NULL, exts[0], NULL);
702         if (!fmt) {
703                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
704                 return 0;
705         }
706
707         of = avformat_alloc_context();
708         if (!of) {
709                 BKE_report(reports, RPT_ERROR, "Error opening output file");
710                 return 0;
711         }
712         
713         of->oformat = fmt;
714         of->packet_size = rd->ffcodecdata.mux_packet_size;
715         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
716                 ffmpeg_dict_set_int(&opts, "muxrate", rd->ffcodecdata.mux_rate);
717         }
718         else {
719                 av_dict_set(&opts, "muxrate", "0", 0);
720         }
721
722         ffmpeg_dict_set_int(&opts, "preload", (int)(0.5 * AV_TIME_BASE));
723
724         of->max_delay = (int)(0.7 * AV_TIME_BASE);
725
726         fmt->audio_codec = ffmpeg_audio_codec;
727
728         BLI_snprintf(of->filename, sizeof(of->filename), "%s", name);
729         /* set the codec to the user's selection */
730         switch (ffmpeg_type) {
731                 case FFMPEG_AVI:
732                 case FFMPEG_MOV:
733                 case FFMPEG_MKV:
734                         fmt->video_codec = ffmpeg_codec;
735                         break;
736                 case FFMPEG_OGG:
737                         fmt->video_codec = CODEC_ID_THEORA;
738                         break;
739                 case FFMPEG_DV:
740                         fmt->video_codec = CODEC_ID_DVVIDEO;
741                         break;
742                 case FFMPEG_MPEG1:
743                         fmt->video_codec = CODEC_ID_MPEG1VIDEO;
744                         break;
745                 case FFMPEG_MPEG2:
746                         fmt->video_codec = CODEC_ID_MPEG2VIDEO;
747                         break;
748                 case FFMPEG_H264:
749                         fmt->video_codec = CODEC_ID_H264;
750                         break;
751                 case FFMPEG_XVID:
752                         fmt->video_codec = CODEC_ID_MPEG4;
753                         break;
754                 case FFMPEG_FLV:
755                         fmt->video_codec = CODEC_ID_FLV1;
756                         break;
757                 case FFMPEG_MP3:
758                         fmt->audio_codec = CODEC_ID_MP3;
759                 case FFMPEG_WAV:
760                         fmt->video_codec = CODEC_ID_NONE;
761                         break;
762                 case FFMPEG_MPEG4:
763                 default:
764                         fmt->video_codec = CODEC_ID_MPEG4;
765                         break;
766         }
767         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
768                 if (rectx != 720) {
769                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
770                         return 0;
771                 }
772                 if (rd->frs_sec != 25 && recty != 480) {
773                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
774                         return 0;
775                 }
776                 if (rd->frs_sec == 25 && recty != 576) {
777                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
778                         return 0;
779                 }
780         }
781         
782         if (ffmpeg_type == FFMPEG_DV) {
783                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
784                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
785                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
786                         av_dict_free(&opts);
787                         return 0;
788                 }
789         }
790         
791         if (fmt->video_codec != CODEC_ID_NONE) {
792                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty, error, sizeof(error));
793                 PRINT("alloc video stream %p\n", video_stream);
794                 if (!video_stream) {
795                         if (error[0])
796                                 BKE_report(reports, RPT_ERROR, error);
797                         else
798                                 BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
799
800                         av_dict_free(&opts);
801                         return 0;
802                 }
803         }
804
805         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
806                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
807                 if (!audio_stream) {
808                         BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
809                         av_dict_free(&opts);
810                         return 0;
811                 }
812         }
813         if (!(fmt->flags & AVFMT_NOFILE)) {
814                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
815                         BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
816                         av_dict_free(&opts);
817                         return 0;
818                 }
819         }
820         if (avformat_write_header(of, NULL) < 0) {
821                 BKE_report(reports, RPT_ERROR, "Could not initialize streams. Probably unsupported codec combination.");
822                         av_dict_free(&opts);
823                 return 0;
824         }
825
826         outfile = of;
827         av_dump_format(of, 0, name, 1);
828         av_dict_free(&opts);
829
830         return 1;
831 }
832
833 /**
834  * Writes any delayed frames in the encoder. This function is called before 
835  * closing the encoder.
836  *
837  * <p>
838  * Since an encoder may use both past and future frames to predict 
839  * inter-frames (H.264 B-frames, for example), it can output the frames 
840  * in a different order from the one it was given.
841  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
842  * them in the order 1, 4, 2, 3 - first the two frames used for predition, 
843  * and then the bidirectionally-predicted frames. What this means in practice 
844  * is that the encoder may not immediately produce one output frame for each 
845  * input frame. These delayed frames must be flushed before we close the 
846  * stream. We do this by calling avcodec_encode_video with NULL for the last 
847  * parameter.
848  * </p>
849  */
850 static void flush_ffmpeg(void)
851 {
852         int outsize = 0;
853         int ret = 0;
854         
855         AVCodecContext *c = video_stream->codec;
856         /* get the delayed frames */
857         while (1) {
858                 AVPacket packet;
859                 av_init_packet(&packet);
860                 
861                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
862                 if (outsize < 0) {
863                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
864                         break;
865                 }
866                 if (outsize == 0) {
867                         break;
868                 }
869                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
870                         packet.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_stream->time_base);
871                         PRINT("Video Frame PTS: %d\n", (int) packet.pts);
872                 }
873                 else {
874                         PRINT("Video Frame PTS: not set\n");
875                 }
876                 if (c->coded_frame->key_frame) {
877                         packet.flags |= AV_PKT_FLAG_KEY;
878                 }
879                 packet.stream_index = video_stream->index;
880                 packet.data = video_buffer;
881                 packet.size = outsize;
882                 ret = av_interleaved_write_frame(outfile, &packet);
883                 if (ret != 0) {
884                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
885                         break;
886                 }
887         }
888         avcodec_flush_buffers(video_stream->codec);
889 }
890
891 /* **********************************************************************
892  * * public interface
893  * ********************************************************************** */
894
895 /* Get the output filename-- similar to the other output formats */
896 void BKE_ffmpeg_filepath_get(char *string, RenderData *rd)
897 {
898         char autosplit[20];
899
900         const char **exts = get_file_extensions(rd->ffcodecdata.type);
901         const char **fe = exts;
902
903         if (!string || !exts) return;
904
905         strcpy(string, rd->pic);
906         BLI_path_abs(string, G.main->name);
907
908         BLI_make_existing_file(string);
909
910         autosplit[0] = 0;
911
912         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
913                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
914         }
915
916         while (*fe) {
917                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0)
918                 {
919                         break;
920                 }
921                 fe++;
922         }
923
924         if (*fe == NULL) {
925                 strcat(string, autosplit);
926
927                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
928                 strcat(string, *exts);
929         }
930         else {
931                 *(string + strlen(string) - strlen(*fe)) = 0;
932                 strcat(string, autosplit);
933                 strcat(string, *fe);
934         }
935 }
936
937 int BKE_ffmpeg_start(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
938 {
939         int success;
940
941         ffmpeg_autosplit_count = 0;
942
943         success = start_ffmpeg_impl(rd, rectx, recty, reports);
944 #ifdef WITH_AUDASPACE
945         if (audio_stream) {
946                 AVCodecContext *c = audio_stream->codec;
947                 AUD_DeviceSpecs specs;
948                 specs.channels = c->channels;
949                 specs.format = AUD_FORMAT_S16;
950                 specs.rate = rd->ffcodecdata.audio_mixrate;
951                 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
952 #ifdef FFMPEG_CODEC_TIME_BASE
953                 c->time_base.den = specs.rate;
954                 c->time_base.num = 1;
955 #endif
956         }
957 #endif
958         return success;
959 }
960
961 void BKE_ffmpeg_end(void);
962 static void end_ffmpeg_impl(int is_autosplit);
963
964 #ifdef WITH_AUDASPACE
965 static void write_audio_frames(double to_pts)
966 {
967         int finished = 0;
968
969         while (audio_stream && !finished) {
970                 if ((audio_time >= to_pts) ||
971                     (write_audio_frame()))
972                 {
973                         finished = 1;
974                 }
975         }
976 }
977 #endif
978
979 int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
980 {
981         AVFrame *avframe;
982         int success = 1;
983
984         PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);
985
986 // why is this done before writing the video frame and again at end_ffmpeg?
987 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
988
989         if (video_stream) {
990                 avframe = generate_video_frame((unsigned char *) pixels, reports);
991                 success = (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
992
993                 if (ffmpeg_autosplit) {
994                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
995                                 end_ffmpeg_impl(TRUE);
996                                 ffmpeg_autosplit_count++;
997                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
998                         }
999                 }
1000         }
1001
1002 #ifdef WITH_AUDASPACE
1003         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
1004 #endif
1005         return success;
1006 }
1007
1008 static void end_ffmpeg_impl(int is_autosplit)
1009 {
1010         unsigned int i;
1011         
1012         PRINT("Closing ffmpeg...\n");
1013
1014 #if 0
1015         if (audio_stream) { /* SEE UPPER */
1016                 write_audio_frames();
1017         }
1018 #endif
1019
1020 #ifdef WITH_AUDASPACE
1021         if (is_autosplit == FALSE) {
1022                 if (audio_mixdown_device) {
1023                         AUD_closeReadDevice(audio_mixdown_device);
1024                         audio_mixdown_device = 0;
1025                 }
1026         }
1027 #endif
1028
1029         if (video_stream && video_stream->codec) {
1030                 PRINT("Flushing delayed frames...\n");
1031                 flush_ffmpeg();
1032         }
1033         
1034         if (outfile) {
1035                 av_write_trailer(outfile);
1036         }
1037         
1038         /* Close the video codec */
1039
1040         if (video_stream && video_stream->codec) {
1041                 avcodec_close(video_stream->codec);
1042                 PRINT("zero video stream %p\n", video_stream);
1043                 video_stream = 0;
1044         }
1045
1046         
1047         /* Close the output file */
1048         if (outfile) {
1049                 for (i = 0; i < outfile->nb_streams; i++) {
1050                         if (&outfile->streams[i]) {
1051                                 av_freep(&outfile->streams[i]);
1052                         }
1053                 }
1054         }
1055         /* free the temp buffer */
1056         if (current_frame) {
1057                 delete_picture(current_frame);
1058                 current_frame = 0;
1059         }
1060         if (outfile && outfile->oformat) {
1061                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1062                         avio_close(outfile->pb);
1063                 }
1064         }
1065         if (outfile) {
1066                 av_free(outfile);
1067                 outfile = 0;
1068         }
1069         if (video_buffer) {
1070                 MEM_freeN(video_buffer);
1071                 video_buffer = 0;
1072         }
1073         if (audio_output_buffer) {
1074                 av_free(audio_output_buffer);
1075                 audio_output_buffer = 0;
1076         }
1077         if (audio_input_buffer) {
1078                 av_free(audio_input_buffer);
1079                 audio_input_buffer = 0;
1080         }
1081
1082         if (img_convert_ctx) {
1083                 sws_freeContext(img_convert_ctx);
1084                 img_convert_ctx = 0;
1085         }
1086 }
1087
1088 void BKE_ffmpeg_end(void)
1089 {
1090         end_ffmpeg_impl(FALSE);
1091 }
1092
1093 /* properties */
1094
1095 void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1096 {
1097         struct IDProperty *prop = (struct IDProperty *) prop_;
1098         IDProperty *group;
1099         
1100         if (!rd->ffcodecdata.properties) {
1101                 return;
1102         }
1103
1104         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1105         if (group && prop) {
1106                 IDP_RemFromGroup(group, prop);
1107                 IDP_FreeProperty(prop);
1108                 MEM_freeN(prop);
1109         }
1110 }
1111
1112 IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1113 {
1114         AVCodecContext c;
1115         const AVOption *o;
1116         const AVOption *parent;
1117         IDProperty *group;
1118         IDProperty *prop;
1119         IDPropertyTemplate val;
1120         int idp_type;
1121         char name[256];
1122         
1123         val.i = 0;
1124
1125         avcodec_get_context_defaults(&c);
1126
1127         o = c.av_class->option + opt_index;
1128         parent = c.av_class->option + parent_index;
1129
1130         if (!rd->ffcodecdata.properties) {
1131                 rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1132         }
1133
1134         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1135         
1136         if (!group) {
1137                 group = IDP_New(IDP_GROUP, &val, type);
1138                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1139         }
1140
1141         if (parent_index) {
1142                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1143         }
1144         else {
1145                 BLI_strncpy(name, o->name, sizeof(name));
1146         }
1147
1148         PRINT("ffmpeg_property_add: %s %d %d %s\n", type, parent_index, opt_index, name);
1149
1150         prop = IDP_GetPropertyFromGroup(group, name);
1151         if (prop) {
1152                 return prop;
1153         }
1154
1155         switch (o->type) {
1156                 case FF_OPT_TYPE_INT:
1157                 case FF_OPT_TYPE_INT64:
1158                         val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1159                         idp_type = IDP_INT;
1160                         break;
1161                 case FF_OPT_TYPE_DOUBLE:
1162                 case FF_OPT_TYPE_FLOAT:
1163                         val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1164                         idp_type = IDP_FLOAT;
1165                         break;
1166                 case FF_OPT_TYPE_STRING:
1167                         val.string.str = (char *)"                                                                               ";
1168                         val.string.len = 80;
1169 /*              val.str = (char *)"                                                                               ";*/
1170                         idp_type = IDP_STRING;
1171                         break;
1172                 case FF_OPT_TYPE_CONST:
1173                         val.i = 1;
1174                         idp_type = IDP_INT;
1175                         break;
1176                 default:
1177                         return NULL;
1178         }
1179         prop = IDP_New(idp_type, &val, name);
1180         IDP_AddToGroup(group, prop);
1181         return prop;
1182 }
1183
1184 /* not all versions of ffmpeg include that, so here we go ... */
1185
1186 static const AVOption *my_av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
1187 {
1188         AVClass *c = *(AVClass **)v;
1189         const AVOption *o = c->option;
1190
1191         for (; o && o->name; o++) {
1192                 if (!strcmp(o->name, name) &&
1193                     (!unit || (o->unit && !strcmp(o->unit, unit))) &&
1194                     (o->flags & mask) == flags)
1195                 {
1196                         return o;
1197                 }
1198         }
1199         return NULL;
1200 }
1201
1202 int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *str)
1203 {
1204         AVCodecContext c;
1205         const AVOption *o = 0;
1206         const AVOption *p = 0;
1207         char name_[128];
1208         char *name;
1209         char *param;
1210         IDProperty *prop = NULL;
1211         
1212         avcodec_get_context_defaults(&c);
1213
1214         strncpy(name_, str, sizeof(name_));
1215
1216         name = name_;
1217         while (*name == ' ') name++;
1218
1219         param = strchr(name, ':');
1220
1221         if (!param) {
1222                 param = strchr(name, ' ');
1223         }
1224         if (param) {
1225                 *param++ = 0;
1226                 while (*param == ' ') param++;
1227         }
1228         
1229         o = my_av_find_opt(&c, name, NULL, 0, 0);       
1230         if (!o) {
1231                 return 0;
1232         }
1233         if (param && o->type == FF_OPT_TYPE_CONST) {
1234                 return 0;
1235         }
1236         if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1237                 p = my_av_find_opt(&c, param, o->unit, 0, 0);   
1238                 if (p) {
1239                         prop = BKE_ffmpeg_property_add(rd, (char *) type, p - c.av_class->option, o - c.av_class->option);
1240                 }
1241         }
1242         else {
1243                 prop = BKE_ffmpeg_property_add(rd, (char *) type, o - c.av_class->option, 0);
1244         }
1245                 
1246
1247         if (!prop) {
1248                 return 0;
1249         }
1250
1251         if (param && !p) {
1252                 switch (prop->type) {
1253                         case IDP_INT:
1254                                 IDP_Int(prop) = atoi(param);
1255                                 break;
1256                         case IDP_FLOAT:
1257                                 IDP_Float(prop) = atof(param);
1258                                 break;
1259                         case IDP_STRING:
1260                                 strncpy(IDP_String(prop), param, prop->len);
1261                                 break;
1262                 }
1263         }
1264         return 1;
1265 }
1266
1267 static void ffmpeg_set_expert_options(RenderData *rd)
1268 {
1269         int codec_id = rd->ffcodecdata.codec;
1270
1271         if (rd->ffcodecdata.properties)
1272                 IDP_FreeProperty(rd->ffcodecdata.properties);
1273
1274         if (codec_id == CODEC_ID_H264) {
1275                 /*
1276                  * All options here are for x264, but must be set via ffmpeg.
1277                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1278                  * to get a list.
1279                  */
1280
1281                 /*
1282                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1283                  * crashes Blender for some reason. Either way - this is no big deal.
1284                  */
1285                 BKE_ffmpeg_property_add_string(rd, "video", "coder:vlc");
1286
1287                 /*
1288                  * The other options were taken from the libx264-default.preset
1289                  * included in the ffmpeg distribution.
1290                  */
1291 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1292                 BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1293                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1294                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1295                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1296                 BKE_ffmpeg_property_add_string(rd, "video", "me:hex");
1297                 BKE_ffmpeg_property_add_string(rd, "video", "subq:6");
1298                 BKE_ffmpeg_property_add_string(rd, "video", "me_range:16");
1299                 BKE_ffmpeg_property_add_string(rd, "video", "qdiff:4");
1300                 BKE_ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1301                 BKE_ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1302                 BKE_ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1303                 BKE_ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1304                 BKE_ffmpeg_property_add_string(rd, "video", "bf:3");
1305                 BKE_ffmpeg_property_add_string(rd, "video", "refs:2");
1306                 BKE_ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1307                 BKE_ffmpeg_property_add_string(rd, "video", "directpred:3");
1308                 BKE_ffmpeg_property_add_string(rd, "video", "trellis:0");
1309                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1310                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1311                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1312                 BKE_ffmpeg_property_add_string(rd, "video", "wpredp:2");
1313
1314                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1315                         BKE_ffmpeg_property_add_string(rd, "video", "cqp:0");
1316         }
1317         else if (codec_id == CODEC_ID_DNXHD) {
1318                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1319                         BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd");
1320         }
1321 }
1322
1323 void BKE_ffmpeg_preset_set(RenderData *rd, int preset)
1324 {
1325         int isntsc = (rd->frs_sec != 25);
1326
1327         if (rd->ffcodecdata.properties)
1328                 IDP_FreeProperty(rd->ffcodecdata.properties);
1329
1330         switch (preset) {
1331                 case FFMPEG_PRESET_VCD:
1332                         rd->ffcodecdata.type = FFMPEG_MPEG1;
1333                         rd->ffcodecdata.video_bitrate = 1150;
1334                         rd->xsch = 352;
1335                         rd->ysch = isntsc ? 240 : 288;
1336                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1337                         rd->ffcodecdata.rc_max_rate = 1150;
1338                         rd->ffcodecdata.rc_min_rate = 1150;
1339                         rd->ffcodecdata.rc_buffer_size = 40 * 8;
1340                         rd->ffcodecdata.mux_packet_size = 2324;
1341                         rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1342                         break;
1343
1344                 case FFMPEG_PRESET_SVCD:
1345                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1346                         rd->ffcodecdata.video_bitrate = 2040;
1347                         rd->xsch = 480;
1348                         rd->ysch = isntsc ? 480 : 576;
1349                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1350                         rd->ffcodecdata.rc_max_rate = 2516;
1351                         rd->ffcodecdata.rc_min_rate = 0;
1352                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1353                         rd->ffcodecdata.mux_packet_size = 2324;
1354                         rd->ffcodecdata.mux_rate = 0;
1355                         break;
1356
1357                 case FFMPEG_PRESET_DVD:
1358                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1359                         rd->ffcodecdata.video_bitrate = 6000;
1360
1361                         /* Don't set resolution, see [#21351]
1362                          * rd->xsch = 720;
1363                          * rd->ysch = isntsc ? 480 : 576; */
1364
1365                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1366                         rd->ffcodecdata.rc_max_rate = 9000;
1367                         rd->ffcodecdata.rc_min_rate = 0;
1368                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1369                         rd->ffcodecdata.mux_packet_size = 2048;
1370                         rd->ffcodecdata.mux_rate = 10080000;
1371                         break;
1372
1373                 case FFMPEG_PRESET_DV:
1374                         rd->ffcodecdata.type = FFMPEG_DV;
1375                         rd->xsch = 720;
1376                         rd->ysch = isntsc ? 480 : 576;
1377                         break;
1378
1379                 case FFMPEG_PRESET_H264:
1380                         rd->ffcodecdata.type = FFMPEG_AVI;
1381                         rd->ffcodecdata.codec = CODEC_ID_H264;
1382                         rd->ffcodecdata.video_bitrate = 6000;
1383                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1384                         rd->ffcodecdata.rc_max_rate = 9000;
1385                         rd->ffcodecdata.rc_min_rate = 0;
1386                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1387                         rd->ffcodecdata.mux_packet_size = 2048;
1388                         rd->ffcodecdata.mux_rate = 10080000;
1389
1390                         break;
1391
1392                 case FFMPEG_PRESET_THEORA:
1393                 case FFMPEG_PRESET_XVID:
1394                         if (preset == FFMPEG_PRESET_XVID) {
1395                                 rd->ffcodecdata.type = FFMPEG_AVI;
1396                                 rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1397                         }
1398                         else if (preset == FFMPEG_PRESET_THEORA) {
1399                                 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1400                                 rd->ffcodecdata.codec = CODEC_ID_THEORA;
1401                         }
1402
1403                         rd->ffcodecdata.video_bitrate = 6000;
1404                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1405                         rd->ffcodecdata.rc_max_rate = 9000;
1406                         rd->ffcodecdata.rc_min_rate = 0;
1407                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1408                         rd->ffcodecdata.mux_packet_size = 2048;
1409                         rd->ffcodecdata.mux_rate = 10080000;
1410                         break;
1411
1412         }
1413
1414         ffmpeg_set_expert_options(rd);
1415 }
1416
1417 void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
1418 {
1419         int audio = 0;
1420
1421         if (imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1422                 if (rd->ffcodecdata.type <= 0 ||
1423                     rd->ffcodecdata.codec <= 0 ||
1424                     rd->ffcodecdata.audio_codec <= 0 ||
1425                     rd->ffcodecdata.video_bitrate <= 1)
1426                 {
1427                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1428
1429                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_DVD);
1430                 }
1431                 if (rd->ffcodecdata.type == FFMPEG_OGG) {
1432                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1433                 }
1434
1435                 audio = 1;
1436         }
1437         else if (imf->imtype == R_IMF_IMTYPE_H264) {
1438                 if (rd->ffcodecdata.codec != CODEC_ID_H264) {
1439                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
1440                         audio = 1;
1441                 }
1442         }
1443         else if (imf->imtype == R_IMF_IMTYPE_XVID) {
1444                 if (rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1445                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_XVID);
1446                         audio = 1;
1447                 }
1448         }
1449         else if (imf->imtype == R_IMF_IMTYPE_THEORA) {
1450                 if (rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1451                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_THEORA);
1452                         audio = 1;
1453                 }
1454         }
1455
1456         if (audio && rd->ffcodecdata.audio_codec < 0) {
1457                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1458                 rd->ffcodecdata.audio_bitrate = 128;
1459         }
1460 }
1461
1462 void BKE_ffmpeg_codec_settings_verify(RenderData *rd)
1463 {
1464         ffmpeg_set_expert_options(rd);
1465 }
1466
1467 int BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd)
1468 {
1469         int codec = rd->ffcodecdata.codec;
1470
1471         if (codec == CODEC_ID_QTRLE)
1472                 return TRUE;
1473
1474 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1475         if (codec == CODEC_ID_FFV1)
1476                 return TRUE;
1477 #endif
1478
1479         return FALSE;
1480 }
1481
1482 #endif