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