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