Some FFmpeg changes
[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,
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                 PRINT("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                         PRINT("Video Frame PTS: %d\n", (int)packet.pts);
269                 }
270                 else {
271                         PRINT("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         PRINT("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                         PRINT("%s.\n", IDP_String(prop));
380                         av_set_string3(c, prop->name, IDP_String(prop), 1, &rv);
381                         break;
382                 case IDP_FLOAT:
383                         PRINT("%g.\n", IDP_Float(prop));
384                         rv = av_set_double(c, prop->name, IDP_Float(prop));
385                         break;
386                 case IDP_INT:
387                         PRINT("%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                 PRINT("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, char *error, int error_size)
450 {
451         AVStream *st;
452         AVCodecContext *c;
453         AVCodec *codec;
454
455         error[0] = '\0';
456
457         st = av_new_stream(of, 0);
458         if (!st) return NULL;
459
460         /* Set up the codec context */
461         
462         c = st->codec;
463         c->codec_id = codec_id;
464         c->codec_type = AVMEDIA_TYPE_VIDEO;
465
466
467         /* Get some values from the current render settings */
468         
469         c->width = rectx;
470         c->height = recty;
471
472         /* FIXME: Really bad hack (tm) for NTSC support */
473         if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
474                 c->time_base.den = 2997;
475                 c->time_base.num = 100;
476         }
477         else if ((double) ((int) rd->frs_sec_base) ==
478                  rd->frs_sec_base)
479         {
480                 c->time_base.den = rd->frs_sec;
481                 c->time_base.num = (int) rd->frs_sec_base;
482         }
483         else {
484                 c->time_base.den = rd->frs_sec * 100000;
485                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
486         }
487         
488         c->gop_size = ffmpeg_gop_size;
489         c->bit_rate = ffmpeg_video_bitrate * 1000;
490         c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
491         c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
492         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
493         c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
494         c->rc_buffer_aggressivity = 1.0;
495         c->me_method = ME_EPZS;
496         
497         codec = avcodec_find_encoder(c->codec_id);
498         if (!codec) return NULL;
499         
500         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
501
502         if (codec->pix_fmts) {
503                 c->pix_fmt = codec->pix_fmts[0];
504         }
505         else {
506                 /* makes HuffYUV happy ... */
507                 c->pix_fmt = PIX_FMT_YUV422P;
508         }
509
510         if (ffmpeg_type == FFMPEG_XVID) {
511                 /* arghhhh ... */
512                 c->pix_fmt = PIX_FMT_YUV420P;
513                 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
514         }
515
516         if (codec_id == CODEC_ID_H264) {
517                 /* correct wrong default ffmpeg param which crash x264 */
518                 c->qmin = 10;
519                 c->qmax = 51;
520         }
521         
522         /* Keep lossless encodes in the RGB domain. */
523         if (codec_id == CODEC_ID_HUFFYUV) {
524                 /* HUFFYUV was PIX_FMT_YUV422P before */
525                 c->pix_fmt = PIX_FMT_RGB32;
526         }
527
528         if (codec_id == CODEC_ID_FFV1) {
529 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
530                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
531                         c->pix_fmt = PIX_FMT_RGB32;
532                 }
533                 else {
534                         c->pix_fmt = PIX_FMT_BGR0;
535                 }
536 #else
537                 c->pix_fmt = PIX_FMT_RGB32;
538 #endif
539         }
540
541         if (codec_id == CODEC_ID_QTRLE) {
542                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
543                         c->pix_fmt = PIX_FMT_ARGB;
544                 }
545         }
546
547         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
548 //              || !strcmp(of->oformat->name, "mp4")
549 //          || !strcmp(of->oformat->name, "mov")
550 //          || !strcmp(of->oformat->name, "3gp")
551             )
552         {
553                 PRINT("Using global header\n");
554                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
555         }
556         
557         /* Determine whether we are encoding interlaced material or not */
558         if (rd->mode & R_FIELDS) {
559                 PRINT("Encoding interlaced video\n");
560                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
561                 c->flags |= CODEC_FLAG_INTERLACED_ME;
562         }
563
564         /* xasp & yasp got float lately... */
565
566         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
567                                       ((double) rd->xasp / (double) rd->yasp), 255);
568
569         set_ffmpeg_properties(rd, c, "video");
570         
571         if (avcodec_open(c, codec) < 0) {
572                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
573                 return NULL;
574         }
575
576         if (codec_id == CODEC_ID_QTRLE) {
577                 /* normally it should be enough to have buffer with actual image size,
578                  * but some codecs like QTRLE might store extra information in this buffer,
579                  * so it should be a way larger */
580
581                 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
582                  * (from FFmpeg sources) */
583                 int size = c->width * c->height;
584                 video_buffersize = 7 * size + 10000;
585         }
586         else
587                 video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
588
589         video_buffer = (uint8_t *)MEM_mallocN(video_buffersize * sizeof(uint8_t),
590                                               "FFMPEG video buffer");
591         
592         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
593
594         img_convert_ctx = sws_getContext(c->width, c->height,
595                                          PIX_FMT_BGR32,
596                                          c->width, c->height,
597                                          c->pix_fmt,
598                                          SWS_BICUBIC,
599                                          NULL, NULL, NULL);
600         return st;
601 }
602
603 /* Prepare an audio stream for the output file */
604
605 static AVStream *alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext *of)
606 {
607         AVStream *st;
608         AVCodecContext *c;
609         AVCodec *codec;
610
611         st = av_new_stream(of, 1);
612         if (!st) return NULL;
613
614         c = st->codec;
615         c->codec_id = codec_id;
616         c->codec_type = AVMEDIA_TYPE_AUDIO;
617
618         c->sample_rate = rd->ffcodecdata.audio_mixrate;
619         c->bit_rate = ffmpeg_audio_bitrate * 1000;
620         c->sample_fmt = AV_SAMPLE_FMT_S16;
621         c->channels = rd->ffcodecdata.audio_channels;
622         codec = avcodec_find_encoder(c->codec_id);
623         if (!codec) {
624                 //XXX error("Couldn't find a valid audio codec");
625                 return NULL;
626         }
627
628         set_ffmpeg_properties(rd, c, "audio");
629
630         if (avcodec_open(c, codec) < 0) {
631                 //XXX error("Couldn't initialize audio codec");
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(
651             audio_outbuf_size);
652
653         audio_input_buffer = (uint8_t *)av_malloc(
654             audio_input_samples * c->channels * sizeof(int16_t));
655
656         audio_time = 0.0f;
657
658         return st;
659 }
660 /* essential functions -- start, append, end */
661
662 static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
663 {
664         char buffer[32];
665
666         BLI_snprintf(buffer, sizeof(buffer), "%d", value);
667
668         av_dict_set(dict, key, buffer, 0);
669 }
670
671 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
672 {
673         /* Handle to the output file */
674         AVFormatContext *of;
675         AVOutputFormat *fmt;
676         AVDictionary *opts = NULL;
677         char name[256], error[1024];
678         const char **exts;
679
680         ffmpeg_type = rd->ffcodecdata.type;
681         ffmpeg_codec = rd->ffcodecdata.codec;
682         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
683         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
684         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
685         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
686         ffmpeg_autosplit = rd->ffcodecdata.flags
687                            & FFMPEG_AUTOSPLIT_OUTPUT;
688         
689         /* Determine the correct filename */
690         BKE_ffmpeg_filepath_get(name, rd);
691         PRINT("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, error, sizeof(error));
797                 PRINT("alloc video stream %p\n", video_stream);
798                 if (!video_stream) {
799                         if (error[0])
800                                 BKE_report(reports, RPT_ERROR, error);
801                         else
802                                 BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
803
804                         av_dict_free(&opts);
805                         return 0;
806                 }
807         }
808
809         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
810                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
811                 if (!audio_stream) {
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 predition, 
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 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,
875                                                   c->time_base,
876                                                   video_stream->time_base);
877                         PRINT("Video Frame PTS: %d\n", (int)packet.pts);
878                 }
879                 else {
880                         PRINT("Video Frame PTS: not set\n");
881                 }
882                 if (c->coded_frame->key_frame) {
883                         packet.flags |= AV_PKT_FLAG_KEY;
884                 }
885                 packet.stream_index = video_stream->index;
886                 packet.data = video_buffer;
887                 packet.size = outsize;
888                 ret = av_interleaved_write_frame(outfile, &packet);
889                 if (ret != 0) {
890                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
891                         break;
892                 }
893         }
894         avcodec_flush_buffers(video_stream->codec);
895 }
896
897 /* **********************************************************************
898  * * public interface
899  * ********************************************************************** */
900
901 /* Get the output filename-- similar to the other output formats */
902 void BKE_ffmpeg_filepath_get(char *string, RenderData *rd)
903 {
904         char autosplit[20];
905
906         const char **exts = get_file_extensions(rd->ffcodecdata.type);
907         const char **fe = exts;
908
909         if (!string || !exts) return;
910
911         strcpy(string, rd->pic);
912         BLI_path_abs(string, G.main->name);
913
914         BLI_make_existing_file(string);
915
916         autosplit[0] = 0;
917
918         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
919                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
920         }
921
922         while (*fe) {
923                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
924                                    *fe) == 0)
925                 {
926                         break;
927                 }
928                 fe++;
929         }
930
931         if (*fe == NULL) {
932                 strcat(string, autosplit);
933
934                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
935                 strcat(string, *exts);
936         }
937         else {
938                 *(string + strlen(string) - strlen(*fe)) = 0;
939                 strcat(string, autosplit);
940                 strcat(string, *fe);
941         }
942 }
943
944 int BKE_ffmpeg_start(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
945 {
946         int success;
947
948         ffmpeg_autosplit_count = 0;
949
950         success = start_ffmpeg_impl(rd, rectx, recty, reports);
951 #ifdef WITH_AUDASPACE
952         if (audio_stream) {
953                 AVCodecContext *c = audio_stream->codec;
954                 AUD_DeviceSpecs specs;
955                 specs.channels = c->channels;
956                 specs.format = AUD_FORMAT_S16;
957                 specs.rate = rd->ffcodecdata.audio_mixrate;
958                 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
959 #ifdef FFMPEG_CODEC_TIME_BASE
960                 c->time_base.den = specs.rate;
961                 c->time_base.num = 1;
962 #endif
963         }
964 #endif
965         return success;
966 }
967
968 void BKE_ffmpeg_end(void);
969
970 #ifdef WITH_AUDASPACE
971 static void write_audio_frames(double to_pts)
972 {
973         int finished = 0;
974
975         while (audio_stream && !finished) {
976                 if ((audio_time >= to_pts) ||
977                     (write_audio_frame()))
978                 {
979                         finished = 1;
980                 }
981         }
982 }
983 #endif
984
985 int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
986 {
987         AVFrame *avframe;
988         int success = 1;
989
990         PRINT("Writing frame %i, "
991               "render width=%d, render height=%d\n", frame,
992               rectx, recty);
993
994 // why is this done before writing the video frame and again at end_ffmpeg?
995 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
996
997         if (video_stream) {
998                 avframe = generate_video_frame((unsigned char *) pixels, reports);
999                 success = (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
1000
1001                 if (ffmpeg_autosplit) {
1002                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
1003                                 BKE_ffmpeg_end();
1004                                 ffmpeg_autosplit_count++;
1005                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
1006                         }
1007                 }
1008         }
1009
1010 #ifdef WITH_AUDASPACE
1011         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
1012 #endif
1013         return success;
1014 }
1015
1016 void BKE_ffmpeg_end(void)
1017 {
1018         unsigned int i;
1019         
1020         PRINT("Closing ffmpeg...\n");
1021
1022 #if 0
1023         if (audio_stream) { /* SEE UPPER */
1024                 write_audio_frames();
1025         }
1026 #endif
1027
1028 #ifdef WITH_AUDASPACE
1029         if (audio_mixdown_device) {
1030                 AUD_closeReadDevice(audio_mixdown_device);
1031                 audio_mixdown_device = 0;
1032         }
1033 #endif
1034
1035         if (video_stream && video_stream->codec) {
1036                 PRINT("Flushing delayed frames...\n");
1037                 flush_ffmpeg();
1038         }
1039         
1040         if (outfile) {
1041                 av_write_trailer(outfile);
1042         }
1043         
1044         /* Close the video codec */
1045
1046         if (video_stream && video_stream->codec) {
1047                 avcodec_close(video_stream->codec);
1048                 PRINT("zero video stream %p\n", video_stream);
1049                 video_stream = 0;
1050         }
1051
1052         
1053         /* Close the output file */
1054         if (outfile) {
1055                 for (i = 0; i < outfile->nb_streams; i++) {
1056                         if (&outfile->streams[i]) {
1057                                 av_freep(&outfile->streams[i]);
1058                         }
1059                 }
1060         }
1061         /* free the temp buffer */
1062         if (current_frame) {
1063                 delete_picture(current_frame);
1064                 current_frame = 0;
1065         }
1066         if (outfile && outfile->oformat) {
1067                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1068                         avio_close(outfile->pb);
1069                 }
1070         }
1071         if (outfile) {
1072                 av_free(outfile);
1073                 outfile = 0;
1074         }
1075         if (video_buffer) {
1076                 MEM_freeN(video_buffer);
1077                 video_buffer = 0;
1078         }
1079         if (audio_output_buffer) {
1080                 av_free(audio_output_buffer);
1081                 audio_output_buffer = 0;
1082         }
1083         if (audio_input_buffer) {
1084                 av_free(audio_input_buffer);
1085                 audio_input_buffer = 0;
1086         }
1087
1088         if (img_convert_ctx) {
1089                 sws_freeContext(img_convert_ctx);
1090                 img_convert_ctx = 0;
1091         }
1092 }
1093
1094 /* properties */
1095
1096 void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1097 {
1098         struct IDProperty *prop = (struct IDProperty *) prop_;
1099         IDProperty *group;
1100         
1101         if (!rd->ffcodecdata.properties) {
1102                 return;
1103         }
1104
1105         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1106         if (group && prop) {
1107                 IDP_RemFromGroup(group, prop);
1108                 IDP_FreeProperty(prop);
1109                 MEM_freeN(prop);
1110         }
1111 }
1112
1113 IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1114 {
1115         AVCodecContext c;
1116         const AVOption *o;
1117         const AVOption *parent;
1118         IDProperty *group;
1119         IDProperty *prop;
1120         IDPropertyTemplate val;
1121         int idp_type;
1122         char name[256];
1123         
1124         val.i = 0;
1125
1126         avcodec_get_context_defaults(&c);
1127
1128         o = c.av_class->option + opt_index;
1129         parent = c.av_class->option + parent_index;
1130
1131         if (!rd->ffcodecdata.properties) {
1132                 rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1133         }
1134
1135         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1136         
1137         if (!group) {
1138                 group = IDP_New(IDP_GROUP, &val, type);
1139                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1140         }
1141
1142         if (parent_index) {
1143                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1144         }
1145         else {
1146                 BLI_strncpy(name, o->name, sizeof(name));
1147         }
1148
1149         PRINT("ffmpeg_property_add: %s %d %d %s\n",
1150               type, parent_index, opt_index, name);
1151
1152         prop = IDP_GetPropertyFromGroup(group, name);
1153         if (prop) {
1154                 return prop;
1155         }
1156
1157         switch (o->type) {
1158                 case FF_OPT_TYPE_INT:
1159                 case FF_OPT_TYPE_INT64:
1160                         val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1161                         idp_type = IDP_INT;
1162                         break;
1163                 case FF_OPT_TYPE_DOUBLE:
1164                 case FF_OPT_TYPE_FLOAT:
1165                         val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1166                         idp_type = IDP_FLOAT;
1167                         break;
1168                 case FF_OPT_TYPE_STRING:
1169                         val.string.str = (char *)"                                                                               ";
1170                         val.string.len = 80;
1171 /*              val.str = (char *)"                                                                               ";*/
1172                         idp_type = IDP_STRING;
1173                         break;
1174                 case FF_OPT_TYPE_CONST:
1175                         val.i = 1;
1176                         idp_type = IDP_INT;
1177                         break;
1178                 default:
1179                         return NULL;
1180         }
1181         prop = IDP_New(idp_type, &val, name);
1182         IDP_AddToGroup(group, prop);
1183         return prop;
1184 }
1185
1186 /* not all versions of ffmpeg include that, so here we go ... */
1187
1188 static const AVOption *my_av_find_opt(void *v, const char *name,
1189                                       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,
1243                                                        (char *) type, p - c.av_class->option,
1244                                                        o - c.av_class->option);
1245                 }
1246         }
1247         else {
1248                 prop = BKE_ffmpeg_property_add(rd,
1249                                                (char *) type, o - c.av_class->option, 0);
1250         }
1251                 
1252
1253         if (!prop) {
1254                 return 0;
1255         }
1256
1257         if (param && !p) {
1258                 switch (prop->type) {
1259                         case IDP_INT:
1260                                 IDP_Int(prop) = atoi(param);
1261                                 break;
1262                         case IDP_FLOAT:
1263                                 IDP_Float(prop) = atof(param);
1264                                 break;
1265                         case IDP_STRING:
1266                                 strncpy(IDP_String(prop), param, prop->len);
1267                                 break;
1268                 }
1269         }
1270         return 1;
1271 }
1272
1273 static void ffmpeg_set_expert_options(RenderData *rd)
1274 {
1275         int codec_id = rd->ffcodecdata.codec;
1276
1277         if (rd->ffcodecdata.properties)
1278                 IDP_FreeProperty(rd->ffcodecdata.properties);
1279
1280         if (codec_id == CODEC_ID_H264) {
1281                 /*
1282                  * All options here are for x264, but must be set via ffmpeg.
1283                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1284                  * to get a list.
1285                  */
1286
1287                 /*
1288                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1289                  * crashes Blender for some reason. Either way - this is no big deal.
1290                  */
1291                 BKE_ffmpeg_property_add_string(rd, "video", "coder:vlc");
1292
1293                 /*
1294                  * The other options were taken from the libx264-default.preset
1295                  * included in the ffmpeg distribution.
1296                  */
1297 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1298                 BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1299                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1300                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1301                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1302                 BKE_ffmpeg_property_add_string(rd, "video", "me:hex");
1303                 BKE_ffmpeg_property_add_string(rd, "video", "subq:6");
1304                 BKE_ffmpeg_property_add_string(rd, "video", "me_range:16");
1305                 BKE_ffmpeg_property_add_string(rd, "video", "qdiff:4");
1306                 BKE_ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1307                 BKE_ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1308                 BKE_ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1309                 BKE_ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1310                 BKE_ffmpeg_property_add_string(rd, "video", "bf:3");
1311                 BKE_ffmpeg_property_add_string(rd, "video", "refs:2");
1312                 BKE_ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1313                 BKE_ffmpeg_property_add_string(rd, "video", "directpred:3");
1314                 BKE_ffmpeg_property_add_string(rd, "video", "trellis:0");
1315                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1316                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1317                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1318                 BKE_ffmpeg_property_add_string(rd, "video", "wpredp:2");
1319
1320                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1321                         BKE_ffmpeg_property_add_string(rd, "video", "cqp:0");
1322         }
1323         else if (codec_id == CODEC_ID_DNXHD) {
1324                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1325                         BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd");
1326         }
1327 }
1328
1329 void BKE_ffmpeg_preset_set(RenderData *rd, int preset)
1330 {
1331         int isntsc = (rd->frs_sec != 25);
1332
1333         if (rd->ffcodecdata.properties)
1334                 IDP_FreeProperty(rd->ffcodecdata.properties);
1335
1336         switch (preset) {
1337                 case FFMPEG_PRESET_VCD:
1338                         rd->ffcodecdata.type = FFMPEG_MPEG1;
1339                         rd->ffcodecdata.video_bitrate = 1150;
1340                         rd->xsch = 352;
1341                         rd->ysch = isntsc ? 240 : 288;
1342                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1343                         rd->ffcodecdata.rc_max_rate = 1150;
1344                         rd->ffcodecdata.rc_min_rate = 1150;
1345                         rd->ffcodecdata.rc_buffer_size = 40 * 8;
1346                         rd->ffcodecdata.mux_packet_size = 2324;
1347                         rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1348                         break;
1349
1350                 case FFMPEG_PRESET_SVCD:
1351                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1352                         rd->ffcodecdata.video_bitrate = 2040;
1353                         rd->xsch = 480;
1354                         rd->ysch = isntsc ? 480 : 576;
1355                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1356                         rd->ffcodecdata.rc_max_rate = 2516;
1357                         rd->ffcodecdata.rc_min_rate = 0;
1358                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1359                         rd->ffcodecdata.mux_packet_size = 2324;
1360                         rd->ffcodecdata.mux_rate = 0;
1361                         break;
1362
1363                 case FFMPEG_PRESET_DVD:
1364                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1365                         rd->ffcodecdata.video_bitrate = 6000;
1366
1367                         /* Don't set resolution, see [#21351]
1368                          * rd->xsch = 720;
1369                          * rd->ysch = isntsc ? 480 : 576; */
1370
1371                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1372                         rd->ffcodecdata.rc_max_rate = 9000;
1373                         rd->ffcodecdata.rc_min_rate = 0;
1374                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1375                         rd->ffcodecdata.mux_packet_size = 2048;
1376                         rd->ffcodecdata.mux_rate = 10080000;
1377                         break;
1378
1379                 case FFMPEG_PRESET_DV:
1380                         rd->ffcodecdata.type = FFMPEG_DV;
1381                         rd->xsch = 720;
1382                         rd->ysch = isntsc ? 480 : 576;
1383                         break;
1384
1385                 case FFMPEG_PRESET_H264:
1386                         rd->ffcodecdata.type = FFMPEG_AVI;
1387                         rd->ffcodecdata.codec = CODEC_ID_H264;
1388                         rd->ffcodecdata.video_bitrate = 6000;
1389                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1390                         rd->ffcodecdata.rc_max_rate = 9000;
1391                         rd->ffcodecdata.rc_min_rate = 0;
1392                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1393                         rd->ffcodecdata.mux_packet_size = 2048;
1394                         rd->ffcodecdata.mux_rate = 10080000;
1395
1396                         break;
1397
1398                 case FFMPEG_PRESET_THEORA:
1399                 case FFMPEG_PRESET_XVID:
1400                         if (preset == FFMPEG_PRESET_XVID) {
1401                                 rd->ffcodecdata.type = FFMPEG_AVI;
1402                                 rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1403                         }
1404                         else if (preset == FFMPEG_PRESET_THEORA) {
1405                                 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1406                                 rd->ffcodecdata.codec = CODEC_ID_THEORA;
1407                         }
1408
1409                         rd->ffcodecdata.video_bitrate = 6000;
1410                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1411                         rd->ffcodecdata.rc_max_rate = 9000;
1412                         rd->ffcodecdata.rc_min_rate = 0;
1413                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1414                         rd->ffcodecdata.mux_packet_size = 2048;
1415                         rd->ffcodecdata.mux_rate = 10080000;
1416                         break;
1417
1418         }
1419
1420         ffmpeg_set_expert_options(rd);
1421 }
1422
1423 void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
1424 {
1425         int audio = 0;
1426
1427         if (imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1428                 if (rd->ffcodecdata.type <= 0 ||
1429                     rd->ffcodecdata.codec <= 0 ||
1430                     rd->ffcodecdata.audio_codec <= 0 ||
1431                     rd->ffcodecdata.video_bitrate <= 1)
1432                 {
1433                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1434
1435                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_DVD);
1436                 }
1437                 if (rd->ffcodecdata.type == FFMPEG_OGG) {
1438                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1439                 }
1440
1441                 audio = 1;
1442         }
1443         else if (imf->imtype == R_IMF_IMTYPE_H264) {
1444                 if (rd->ffcodecdata.codec != CODEC_ID_H264) {
1445                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
1446                         audio = 1;
1447                 }
1448         }
1449         else if (imf->imtype == R_IMF_IMTYPE_XVID) {
1450                 if (rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1451                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_XVID);
1452                         audio = 1;
1453                 }
1454         }
1455         else if (imf->imtype == R_IMF_IMTYPE_THEORA) {
1456                 if (rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1457                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_THEORA);
1458                         audio = 1;
1459                 }
1460         }
1461
1462         if (audio && rd->ffcodecdata.audio_codec < 0) {
1463                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1464                 rd->ffcodecdata.audio_bitrate = 128;
1465         }
1466 }
1467
1468 void BKE_ffmpeg_codec_settings_verify(RenderData *rd)
1469 {
1470         ffmpeg_set_expert_options(rd);
1471 }
1472
1473 int BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd)
1474 {
1475         int codec = rd->ffcodecdata.codec;
1476
1477         if (codec == CODEC_ID_QTRLE)
1478                 return TRUE;
1479
1480 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1481         if (codec == CODEC_ID_FFV1)
1482                 return TRUE;
1483 #endif
1484
1485         return FALSE;
1486 }
1487
1488 #endif