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