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