svn merge ^/trunk/blender -r44562:HEAD
[blender.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /*
2  *
3  * ffmpeg-write support
4  *
5  * Partial Copyright (c) 2006 Peter Schlaile
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  */
18
19 /** \file blender/blenkernel/intern/writeffmpeg.c
20  *  \ingroup bke
21  */
22
23 #ifdef WITH_FFMPEG
24 #include <string.h>
25 #include <stdio.h>
26
27 #if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
28 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
29 #if _MSC_VER < 1400
30 #include <stdint.h>
31 #endif
32 #endif
33
34 #include <stdlib.h>
35
36 #include <libavformat/avformat.h>
37 #include <libavcodec/avcodec.h>
38 #include <libavutil/rational.h>
39 #include <libswscale/swscale.h>
40 #include <libavcodec/opt.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_scene_types.h"
45
46 #include "BLI_blenlib.h"
47
48 #ifdef WITH_AUDASPACE
49 #  include "AUD_C-API.h"
50 #endif
51
52 #include "BLI_utildefines.h"
53
54 #include "BKE_global.h"
55 #include "BKE_idprop.h"
56 #include "BKE_main.h"
57 #include "BKE_report.h"
58 #include "BKE_sound.h"
59 #include "BKE_writeffmpeg.h"
60
61 #include "IMB_imbuf_types.h"
62 #include "IMB_imbuf.h"
63
64 #include "ffmpeg_compat.h"
65
66 extern void do_init_ffmpeg(void);
67
68 static int ffmpeg_type = 0;
69 static int ffmpeg_codec = CODEC_ID_MPEG4;
70 static int ffmpeg_audio_codec = CODEC_ID_NONE;
71 static int ffmpeg_video_bitrate = 1150;
72 static int ffmpeg_audio_bitrate = 128;
73 static int ffmpeg_gop_size = 12;
74 static int ffmpeg_autosplit = 0;
75 static int ffmpeg_autosplit_count = 0;
76
77 static AVFormatContext* outfile = 0;
78 static AVStream* video_stream = 0;
79 static AVStream* audio_stream = 0;
80 static AVFrame* current_frame = 0;
81 static struct SwsContext *img_convert_ctx = 0;
82
83 static uint8_t* video_buffer = 0;
84 static int video_buffersize = 0;
85
86 static uint8_t* audio_input_buffer = 0;
87 static int audio_input_samples = 0;
88 static uint8_t* audio_output_buffer = 0;
89 static int audio_outbuf_size = 0;
90 static double audio_time = 0.0f;
91
92 #ifdef WITH_AUDASPACE
93 static AUD_Device* audio_mixdown_device = 0;
94 #endif
95
96 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
97
98 /* Delete a picture buffer */
99
100 static void delete_picture(AVFrame* f)
101 {
102         if (f) {
103                 if (f->data[0]) MEM_freeN(f->data[0]);
104                 av_free(f);
105         }
106 }
107
108 #ifdef WITH_AUDASPACE
109 static int write_audio_frame(void) 
110 {
111         AVCodecContext* c = NULL;
112         AVPacket pkt;
113
114         c = audio_stream->codec;
115
116         av_init_packet(&pkt);
117         pkt.size = 0;
118
119         AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
120         audio_time += (double) audio_input_samples / (double) c->sample_rate;
121
122         pkt.size = avcodec_encode_audio(c, audio_output_buffer,
123                                         audio_outbuf_size,
124                                         (short*) audio_input_buffer);
125
126         if (pkt.size < 0)
127         {
128                 // XXX error("Error writing audio packet");
129                 return -1;
130         }
131
132         pkt.data = audio_output_buffer;
133
134         if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
135         {
136                 pkt.pts = av_rescale_q(c->coded_frame->pts,
137                                        c->time_base, audio_stream->time_base);
138                 fprintf(stderr, "Audio Frame PTS: %d\n", (int)pkt.pts);
139         }
140
141         pkt.stream_index = audio_stream->index;
142
143         pkt.flags |= AV_PKT_FLAG_KEY;
144
145         if (av_interleaved_write_frame(outfile, &pkt) != 0) {
146                 fprintf(stderr, "Error writing audio packet!\n");
147                 return -1;
148         }
149         return 0;
150 }
151 #endif // #ifdef WITH_AUDASPACE
152
153 /* Allocate a temporary frame */
154 static AVFrame* alloc_picture(int pix_fmt, int width, int height) 
155 {
156         AVFrame* f;
157         uint8_t* buf;
158         int size;
159         
160         /* allocate space for the struct */
161         f = avcodec_alloc_frame();
162         if (!f) return NULL;
163         size = avpicture_get_size(pix_fmt, width, height);
164         /* allocate the actual picture buffer */
165         buf = MEM_mallocN(size, "AVFrame buffer");
166         if (!buf) {
167                 free(f);
168                 return NULL;
169         }
170         avpicture_fill((AVPicture*)f, buf, pix_fmt, width, height);
171         return f;
172 }
173
174 /* Get the correct file extensions for the requested format,
175  * first is always desired guess_format parameter */
176 static const char** get_file_extensions(int format) 
177 {
178         switch(format) {
179         case FFMPEG_DV: {
180                 static const char * rv[] = { ".dv", NULL };
181                 return rv;
182         }
183         case FFMPEG_MPEG1: {
184                 static const char * rv[] = { ".mpg", ".mpeg", NULL };
185                 return rv;
186         }
187         case FFMPEG_MPEG2: {
188                 static const char * rv[] = { ".dvd", ".vob", ".mpg", ".mpeg",
189                                                  NULL };
190                 return rv;
191         }
192         case FFMPEG_MPEG4: {
193                 static const char * rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
194                 return rv;
195         }
196         case FFMPEG_AVI: {
197                 static const char * rv[] = { ".avi", NULL };
198                 return rv;
199         }
200         case FFMPEG_MOV: {
201                 static const char * rv[] = { ".mov", NULL };
202                 return rv;
203         }
204         case FFMPEG_H264: {
205                 /* FIXME: avi for now... */
206                 static const char * rv[] = { ".avi", NULL };
207                 return rv;
208         }
209
210         case FFMPEG_XVID: {
211                 /* FIXME: avi for now... */
212                 static const char * rv[] = { ".avi", NULL };
213                 return rv;
214         }
215         case FFMPEG_FLV: {
216                 static const char * rv[] = { ".flv", NULL };
217                 return rv;
218         }
219         case FFMPEG_MKV: {
220                 static const char * rv[] = { ".mkv", NULL };
221                 return rv;
222         }
223         case FFMPEG_OGG: {
224                 static const char * rv[] = { ".ogg", ".ogv", NULL };
225                 return rv;
226         }
227         case FFMPEG_MP3: {
228                 static const char * rv[] = { ".mp3", NULL };
229                 return rv;
230         }
231         case FFMPEG_WAV: {
232                 static const char * rv[] = { ".wav", NULL };
233                 return rv;
234         }
235         default:
236                 return NULL;
237         }
238 }
239
240 /* Write a frame to the output file */
241 static int write_video_frame(RenderData *rd, int cfra, AVFrame* frame, ReportList *reports)
242 {
243         int outsize = 0;
244         int ret, success= 1;
245         AVCodecContext* c = video_stream->codec;
246
247         frame->pts = cfra;
248
249         if (rd->mode & R_FIELDS) {
250                 frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
251         }
252
253         outsize = avcodec_encode_video(c, video_buffer, video_buffersize, 
254                                            frame);
255
256         if (outsize > 0) {
257                 AVPacket packet;
258                 av_init_packet(&packet);
259
260                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
261                         packet.pts = av_rescale_q(c->coded_frame->pts,
262                                                   c->time_base,
263                                                   video_stream->time_base);
264                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
265                 }
266                 else {
267                         fprintf(stderr, "Video Frame PTS: not set\n");
268                 }
269                 if (c->coded_frame->key_frame)
270                         packet.flags |= AV_PKT_FLAG_KEY;
271                 packet.stream_index = video_stream->index;
272                 packet.data = video_buffer;
273                 packet.size = outsize;
274                 ret = av_interleaved_write_frame(outfile, &packet);
275                 success = (ret == 0);
276         }
277         else if (outsize < 0) {
278                 success = 0;
279         }
280
281         if (!success)
282                 BKE_report(reports, RPT_ERROR, "Error writing frame.");
283
284         return success;
285 }
286
287 /* read and encode a frame of audio from the buffer */
288 static AVFrame* generate_video_frame(uint8_t* pixels, ReportList *reports) 
289 {
290         uint8_t* rendered_frame;
291
292         AVCodecContext* c = video_stream->codec;
293         int width = c->width;
294         int height = c->height;
295         AVFrame* rgb_frame;
296
297         if (c->pix_fmt != PIX_FMT_BGR32) {
298                 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
299                 if (!rgb_frame) {
300                         BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame.");
301                         return NULL;
302                 }
303         }
304         else {
305                 rgb_frame = current_frame;
306         }
307
308         rendered_frame = pixels;
309
310         /* Do RGBA-conversion and flipping in one step depending
311          * on CPU-Endianess */
312
313         if (ENDIAN_ORDER == L_ENDIAN) {
314                 int y;
315                 for (y = 0; y < height; y++) {
316                         uint8_t* target = rgb_frame->data[0]
317                                 + width * 4 * (height - y - 1);
318                         uint8_t* src = rendered_frame + width * 4 * y;
319                         uint8_t* end = src + width * 4;
320                         while (src != end) {
321                                 target[3] = src[3];
322                                 target[2] = src[2];
323                                 target[1] = src[1];
324                                 target[0] = src[0];
325
326                                 target += 4;
327                                 src += 4;
328                         }
329                 }
330         }
331         else {
332                 int y;
333                 for (y = 0; y < height; y++) {
334                         uint8_t* target = rgb_frame->data[0]
335                                 + width * 4 * (height - y - 1);
336                         uint8_t* src = rendered_frame + width * 4 * y;
337                         uint8_t* end = src + width * 4;
338                         while (src != end) {
339                                 target[3] = src[0];
340                                 target[2] = src[1];
341                                 target[1] = src[2];
342                                 target[0] = src[3];
343
344                                 target += 4;
345                                 src += 4;
346                         }
347                 }
348         }
349
350         if (c->pix_fmt != PIX_FMT_BGR32) {
351                 sws_scale(img_convert_ctx, (const uint8_t * const*) rgb_frame->data,
352                           rgb_frame->linesize, 0, c->height,
353                           current_frame->data, current_frame->linesize);
354                 delete_picture(rgb_frame);
355         }
356         return current_frame;
357 }
358
359 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
360 {
361         char name[128];
362         char * param;
363         const AVOption * rv = NULL;
364
365         fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
366
367         BLI_strncpy(name, prop->name, sizeof(name));
368
369         param = strchr(name, ':');
370
371         if (param) {
372                 *param++ = 0;
373         }
374
375         switch(prop->type) {
376         case IDP_STRING:
377                 fprintf(stderr, "%s.\n", IDP_String(prop));
378                 av_set_string3(c, prop->name, IDP_String(prop), 1, &rv);
379                 break;
380         case IDP_FLOAT:
381                 fprintf(stderr, "%g.\n", IDP_Float(prop));
382                 rv = av_set_double(c, prop->name, IDP_Float(prop));
383                 break;
384         case IDP_INT:
385                 fprintf(stderr, "%d.\n", IDP_Int(prop));
386                 
387                 if (param) {
388                         if (IDP_Int(prop)) {
389                                 av_set_string3(c, name, param, 1, &rv);
390                         }
391                         else {
392                                 return;
393                         }
394                 }
395                 else {
396                         rv = av_set_int(c, prop->name, IDP_Int(prop));
397                 }
398                 break;
399         }
400
401         if (!rv) {
402                 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
403                         prop->name);
404         }
405 }
406
407 static int ffmpeg_proprty_valid(AVCodecContext *c, const char *prop_name, IDProperty *curr)
408 {
409         int valid= 1;
410
411         if (strcmp(prop_name, "video")==0) {
412                 if (strcmp(curr->name, "bf")==0) {
413                         /* flash codec doesn't support b frames */
414                         valid&= c->codec_id!=CODEC_ID_FLV1;
415                 }
416         }
417
418         return valid;
419 }
420
421 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char * prop_name)
422 {
423         IDProperty * prop;
424         void * iter;
425         IDProperty * curr;
426
427         if (!rd->ffcodecdata.properties) {
428                 return;
429         }
430         
431         prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name);
432         if (!prop) {
433                 return;
434         }
435
436         iter = IDP_GetGroupIterator(prop);
437
438         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
439                 if (ffmpeg_proprty_valid(c, prop_name, curr))
440                         set_ffmpeg_property_option(c, curr);
441         }
442 }
443
444 /* prepare a video stream for the output file */
445
446 static AVStream* alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext* of,
447                                         int rectx, int recty) 
448 {
449         AVStream* st;
450         AVCodecContext* c;
451         AVCodec* codec;
452         st = av_new_stream(of, 0);
453         if (!st) return NULL;
454
455         /* Set up the codec context */
456         
457         c = st->codec;
458         c->codec_id = codec_id;
459         c->codec_type = AVMEDIA_TYPE_VIDEO;
460
461
462         /* Get some values from the current render settings */
463         
464         c->width = rectx;
465         c->height = recty;
466
467         /* FIXME: Really bad hack (tm) for NTSC support */
468         if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
469                 c->time_base.den = 2997;
470                 c->time_base.num = 100;
471         }
472         else if ((double) ((int) rd->frs_sec_base) ==
473                    rd->frs_sec_base) {
474                 c->time_base.den = rd->frs_sec;
475                 c->time_base.num = (int) rd->frs_sec_base;
476         }
477         else {
478                 c->time_base.den = rd->frs_sec * 100000;
479                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
480         }
481         
482         c->gop_size = ffmpeg_gop_size;
483         c->bit_rate = ffmpeg_video_bitrate*1000;
484         c->rc_max_rate = rd->ffcodecdata.rc_max_rate*1000;
485         c->rc_min_rate = rd->ffcodecdata.rc_min_rate*1000;
486         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
487         c->rc_initial_buffer_occupancy 
488                 = rd->ffcodecdata.rc_buffer_size*3/4;
489         c->rc_buffer_aggressivity = 1.0;
490         c->me_method = ME_EPZS;
491         
492         codec = avcodec_find_encoder(c->codec_id);
493         if (!codec) return NULL;
494         
495         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
496
497         if (codec->pix_fmts) {
498                 c->pix_fmt = codec->pix_fmts[0];
499         }
500         else {
501                 /* makes HuffYUV happy ... */
502                 c->pix_fmt = PIX_FMT_YUV422P;
503         }
504
505         if (ffmpeg_type == FFMPEG_XVID) {
506                 /* arghhhh ... */
507                 c->pix_fmt = PIX_FMT_YUV420P;
508                 c->codec_tag = (('D'<<24) + ('I'<<16) + ('V'<<8) + 'X');
509         }
510
511         if (codec_id == CODEC_ID_H264) {
512                 /* correct wrong default ffmpeg param which crash x264 */
513                 c->qmin=10;
514                 c->qmax=51;
515         }
516         
517         // Keep lossless encodes in the RGB domain.
518         if (codec_id == CODEC_ID_HUFFYUV) {
519                 /* HUFFYUV was PIX_FMT_YUV422P before */
520                 c->pix_fmt = PIX_FMT_RGB32;
521         }
522
523         if (codec_id == CODEC_ID_FFV1) {
524 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
525                 if (rd->im_format.planes ==  R_IMF_PLANES_RGBA) {
526                         c->pix_fmt = PIX_FMT_RGB32;
527                 }
528                 else {
529                         c->pix_fmt = PIX_FMT_BGR0;
530                 }
531 #else
532                 c->pix_fmt = PIX_FMT_RGB32;
533 #endif
534         }
535
536         if (codec_id == CODEC_ID_QTRLE ) {
537                 if (rd->im_format.planes ==  R_IMF_PLANES_RGBA) {
538                         c->pix_fmt = PIX_FMT_ARGB;
539                 }
540         }
541
542         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
543 //              || !strcmp(of->oformat->name, "mp4")
544 //          || !strcmp(of->oformat->name, "mov")
545 //          || !strcmp(of->oformat->name, "3gp")
546                 ) {
547                 fprintf(stderr, "Using global header\n");
548                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
549         }
550         
551         /* Determine whether we are encoding interlaced material or not */
552         if (rd->mode & R_FIELDS) {
553                 fprintf(stderr, "Encoding interlaced video\n");
554                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
555                 c->flags |= CODEC_FLAG_INTERLACED_ME;
556         }
557
558         /* xasp & yasp got float lately... */
559
560         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
561                 ((double) rd->xasp / (double) rd->yasp), 255);
562
563         set_ffmpeg_properties(rd, c, "video");
564         
565         if (avcodec_open(c, codec) < 0) {
566                 //
567                 //XXX error("Couldn't initialize codec");
568                 return NULL;
569         }
570
571         if ( codec_id == CODEC_ID_QTRLE ) {
572                 // normally it should be enough to have buffer with actual image size,
573                 // but some codecs like QTRLE might store extra information in this buffer,
574                 // so it should be a way larger
575
576                 // maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
577                 // (from FFmpeg sources)
578                 int size = c->width * c->height;
579                 video_buffersize = 7*size + 10000;
580         }
581         else
582                 video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
583
584         video_buffer = (uint8_t*)MEM_mallocN(video_buffersize*sizeof(uint8_t),
585                                                  "FFMPEG video buffer");
586         
587         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
588
589         img_convert_ctx = sws_getContext(c->width, c->height,
590                                          PIX_FMT_BGR32,
591                                          c->width, c->height,
592                                          c->pix_fmt,
593                                          SWS_BICUBIC,
594                                          NULL, NULL, NULL);
595         return st;
596 }
597
598 /* Prepare an audio stream for the output file */
599
600 static AVStream* alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext* of) 
601 {
602         AVStream* st;
603         AVCodecContext* c;
604         AVCodec* codec;
605
606         st = av_new_stream(of, 1);
607         if (!st) return NULL;
608
609         c = st->codec;
610         c->codec_id = codec_id;
611         c->codec_type = AVMEDIA_TYPE_AUDIO;
612
613         c->sample_rate = rd->ffcodecdata.audio_mixrate;
614         c->bit_rate = ffmpeg_audio_bitrate*1000;
615         c->sample_fmt = SAMPLE_FMT_S16;
616         c->channels = rd->ffcodecdata.audio_channels;
617         codec = avcodec_find_encoder(c->codec_id);
618         if (!codec) {
619                 //XXX error("Couldn't find a valid audio codec");
620                 return NULL;
621         }
622
623         set_ffmpeg_properties(rd, c, "audio");
624
625         if (avcodec_open(c, codec) < 0) {
626                 //XXX error("Couldn't initialize audio codec");
627                 return NULL;
628         }
629
630         /* need to prevent floating point exception when using vorbis audio codec,
631          * initialize this value in the same way as it's done in FFmpeg iteslf (sergey) */
632         st->codec->time_base.num= 1;
633         st->codec->time_base.den= st->codec->sample_rate;
634
635         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
636
637         if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
638                 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
639         else {
640                 audio_input_samples = c->frame_size;
641                 if (c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
642                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
643         }
644
645         audio_output_buffer = (uint8_t*)av_malloc(
646                 audio_outbuf_size);
647
648         audio_input_buffer = (uint8_t*)av_malloc(
649                 audio_input_samples * c->channels * sizeof(int16_t));
650
651         audio_time = 0.0f;
652
653         return st;
654 }
655 /* essential functions -- start, append, end */
656
657 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
658 {
659         /* Handle to the output file */
660         AVFormatContext* of;
661         AVOutputFormat* fmt;
662         char name[256];
663         const char ** exts;
664
665         ffmpeg_type = rd->ffcodecdata.type;
666         ffmpeg_codec = rd->ffcodecdata.codec;
667         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
668         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
669         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
670         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
671         ffmpeg_autosplit = rd->ffcodecdata.flags
672                 & FFMPEG_AUTOSPLIT_OUTPUT;
673         
674         do_init_ffmpeg();
675
676         /* Determine the correct filename */
677         filepath_ffmpeg(name, rd);
678         fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
679                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
680                 "  video_bitrate=%d, audio_bitrate=%d,\n"
681                 "  gop_size=%d, autosplit=%d\n"
682                 "  render width=%d, render height=%d\n", 
683                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
684                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
685                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
686         
687         exts = get_file_extensions(ffmpeg_type);
688         if (!exts) {
689                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
690                 return 0;
691         }
692         fmt = av_guess_format(NULL, exts[0], NULL);
693         if (!fmt) {
694                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
695                 return 0;
696         }
697
698         of = avformat_alloc_context();
699         if (!of) {
700                 BKE_report(reports, RPT_ERROR, "Error opening output file");
701                 return 0;
702         }
703         
704         of->oformat = fmt;
705         of->packet_size= rd->ffcodecdata.mux_packet_size;
706         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
707                 of->mux_rate = rd->ffcodecdata.mux_rate;
708         }
709         else {
710                 of->mux_rate = 0;
711         }
712
713         of->preload = (int)(0.5*AV_TIME_BASE);
714         of->max_delay = (int)(0.7*AV_TIME_BASE);
715
716         fmt->audio_codec = ffmpeg_audio_codec;
717
718         BLI_snprintf(of->filename, sizeof(of->filename), "%s", name);
719         /* set the codec to the user's selection */
720         switch(ffmpeg_type) {
721         case FFMPEG_AVI:
722         case FFMPEG_MOV:
723         case FFMPEG_MKV:
724                 fmt->video_codec = ffmpeg_codec;
725                 break;
726         case FFMPEG_OGG:
727                 fmt->video_codec = CODEC_ID_THEORA;
728                 break;
729         case FFMPEG_DV:
730                 fmt->video_codec = CODEC_ID_DVVIDEO;
731                 break;
732         case FFMPEG_MPEG1:
733                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
734                 break;
735         case FFMPEG_MPEG2:
736                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
737                 break;
738         case FFMPEG_H264:
739                 fmt->video_codec = CODEC_ID_H264;
740                 break;
741         case FFMPEG_XVID:
742                 fmt->video_codec = CODEC_ID_MPEG4;
743                 break;
744         case FFMPEG_FLV:
745                 fmt->video_codec = CODEC_ID_FLV1;
746                 break;
747         case FFMPEG_MP3:
748                 fmt->audio_codec = CODEC_ID_MP3;
749         case FFMPEG_WAV:
750                 fmt->video_codec = CODEC_ID_NONE;
751                 break;
752         case FFMPEG_MPEG4:
753         default:
754                 fmt->video_codec = CODEC_ID_MPEG4;
755                 break;
756         }
757         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
758                 if (rectx != 720) {
759                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
760                         return 0;
761                 }
762                 if (rd->frs_sec != 25 && recty != 480) {
763                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
764                         return 0;
765                 }
766                 if (rd->frs_sec == 25 && recty != 576) {
767                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
768                         return 0;
769                 }
770         }
771         
772         if (ffmpeg_type == FFMPEG_DV) {
773                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
774                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
775                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
776                         return 0;
777                 }
778         }
779         
780         if (fmt->video_codec != CODEC_ID_NONE) {
781                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty);
782                 printf("alloc video stream %p\n", video_stream);
783                 if (!video_stream) {
784                         BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
785                         return 0;
786                 }
787         }
788
789         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
790                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
791                 if (!audio_stream) {
792                         BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
793                         return 0;
794                 }
795         }
796         if (av_set_parameters(of, NULL) < 0) {
797                 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
798                 return 0;
799         }
800         if (!(fmt->flags & AVFMT_NOFILE)) {
801                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
802                         BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
803                         return 0;
804                 }
805         }
806
807         if (av_write_header(of) < 0) {
808                 BKE_report(reports, RPT_ERROR, "Could not initialize streams. Probably unsupported codec combination.");
809                 return 0;
810         }
811
812         outfile = of;
813         av_dump_format(of, 0, name, 1);
814
815         return 1;
816 }
817
818 /**
819  * Writes any delayed frames in the encoder. This function is called before 
820  * closing the encoder.
821  *
822  * <p>
823  * Since an encoder may use both past and future frames to predict 
824  * inter-frames (H.264 B-frames, for example), it can output the frames 
825  * in a different order from the one it was given.
826  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
827  * them in the order 1, 4, 2, 3 - first the two frames used for predition, 
828  * and then the bidirectionally-predicted frames. What this means in practice 
829  * is that the encoder may not immediately produce one output frame for each 
830  * input frame. These delayed frames must be flushed before we close the 
831  * stream. We do this by calling avcodec_encode_video with NULL for the last 
832  * parameter.
833  * </p>
834  */
835 void flush_ffmpeg(void)
836 {
837         int outsize = 0;
838         int ret = 0;
839         
840         AVCodecContext* c = video_stream->codec;
841         /* get the delayed frames */
842         while (1) {
843                 AVPacket packet;
844                 av_init_packet(&packet);
845                 
846                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
847                 if (outsize < 0) {
848                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
849                         break;
850                 }
851                 if (outsize == 0) {
852                         break;
853                 }
854                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
855                         packet.pts = av_rescale_q(c->coded_frame->pts,
856                                                   c->time_base,
857                                                   video_stream->time_base);
858                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
859                 }
860                 else {
861                         fprintf(stderr, "Video Frame PTS: not set\n");
862                 }
863                 if (c->coded_frame->key_frame) {
864                         packet.flags |= AV_PKT_FLAG_KEY;
865                 }
866                 packet.stream_index = video_stream->index;
867                 packet.data = video_buffer;
868                 packet.size = outsize;
869                 ret = av_interleaved_write_frame(outfile, &packet);
870                 if (ret != 0) {
871                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
872                         break;
873                 }
874         }
875         avcodec_flush_buffers(video_stream->codec);
876 }
877
878 /* **********************************************************************
879  * * public interface
880  * ********************************************************************** */
881
882 /* Get the output filename-- similar to the other output formats */
883 void filepath_ffmpeg(char* string, RenderData* rd)
884 {
885         char autosplit[20];
886
887         const char ** exts = get_file_extensions(rd->ffcodecdata.type);
888         const char ** fe = exts;
889
890         if (!string || !exts) return;
891
892         strcpy(string, rd->pic);
893         BLI_path_abs(string, G.main->name);
894
895         BLI_make_existing_file(string);
896
897         autosplit[0] = 0;
898
899         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
900                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
901         }
902
903         while (*fe) {
904                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
905                                    *fe) == 0) {
906                         break;
907                 }
908                 fe++;
909         }
910
911         if (!*fe) {
912                 strcat(string, autosplit);
913
914                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
915                 strcat(string, *exts);
916         }
917         else {
918                 *(string + strlen(string) - strlen(*fe)) = 0;
919                 strcat(string, autosplit);
920                 strcat(string, *fe);
921         }
922 }
923
924 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
925 {
926         int success;
927
928         ffmpeg_autosplit_count = 0;
929
930         success = start_ffmpeg_impl(rd, rectx, recty, reports);
931 #ifdef WITH_AUDASPACE
932         if (audio_stream)
933         {
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 end_ffmpeg(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 append_ffmpeg(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         {
979                 avframe= generate_video_frame((unsigned char*) pixels, reports);
980                 success= (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
981
982                 if (ffmpeg_autosplit) {
983                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
984                                 end_ffmpeg();
985                                 ffmpeg_autosplit_count++;
986                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
987                         }
988                 }
989         }
990
991 #ifdef WITH_AUDASPACE
992         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
993 #endif
994         return success;
995 }
996
997 void end_ffmpeg(void)
998 {
999         unsigned int i;
1000         
1001         fprintf(stderr, "Closing ffmpeg...\n");
1002
1003 /*      if (audio_stream) { SEE UPPER
1004                 write_audio_frames();
1005         }*/
1006
1007 #ifdef WITH_AUDASPACE
1008         if (audio_mixdown_device) {
1009                 AUD_closeReadDevice(audio_mixdown_device);
1010                 audio_mixdown_device = 0;
1011         }
1012 #endif
1013
1014         if (video_stream && video_stream->codec) {
1015                 fprintf(stderr, "Flushing delayed frames...\n");
1016                 flush_ffmpeg ();                
1017         }
1018         
1019         if (outfile) {
1020                 av_write_trailer(outfile);
1021         }
1022         
1023         /* Close the video codec */
1024
1025         if (video_stream && video_stream->codec) {
1026                 avcodec_close(video_stream->codec);
1027                 printf("zero video stream %p\n", video_stream);
1028                 video_stream = 0;
1029         }
1030
1031         
1032         /* Close the output file */
1033         if (outfile) {
1034                 for (i = 0; i < outfile->nb_streams; i++) {
1035                         if (&outfile->streams[i]) {
1036                                 av_freep(&outfile->streams[i]);
1037                         }
1038                 }
1039         }
1040         /* free the temp buffer */
1041         if (current_frame) {
1042                 delete_picture(current_frame);
1043                 current_frame = 0;
1044         }
1045         if (outfile && outfile->oformat) {
1046                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1047                         avio_close(outfile->pb);
1048                 }
1049         }
1050         if (outfile) {
1051                 av_free(outfile);
1052                 outfile = 0;
1053         }
1054         if (video_buffer) {
1055                 MEM_freeN(video_buffer);
1056                 video_buffer = 0;
1057         }
1058         if (audio_output_buffer) {
1059                 av_free(audio_output_buffer);
1060                 audio_output_buffer = 0;
1061         }
1062         if (audio_input_buffer) {
1063                 av_free(audio_input_buffer);
1064                 audio_input_buffer = 0;
1065         }
1066
1067         if (img_convert_ctx) {
1068                 sws_freeContext(img_convert_ctx);
1069                 img_convert_ctx = 0;
1070         }
1071 }
1072
1073 /* properties */
1074
1075 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1076 {
1077         struct IDProperty *prop = (struct IDProperty *) prop_;
1078         IDProperty * group;
1079         
1080         if (!rd->ffcodecdata.properties) {
1081                 return;
1082         }
1083
1084         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1085         if (group && prop) {
1086                 IDP_RemFromGroup(group, prop);
1087                 IDP_FreeProperty(prop);
1088                 MEM_freeN(prop);
1089         }
1090 }
1091
1092 IDProperty *ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1093 {
1094         AVCodecContext c;
1095         const AVOption * o;
1096         const AVOption * parent;
1097         IDProperty * group;
1098         IDProperty * prop;
1099         IDPropertyTemplate val;
1100         int idp_type;
1101         char name[256];
1102         
1103         val.i = 0;
1104
1105         avcodec_get_context_defaults(&c);
1106
1107         o = c.av_class->option + opt_index;
1108         parent = c.av_class->option + parent_index;
1109
1110         if (!rd->ffcodecdata.properties) {
1111                 rd->ffcodecdata.properties 
1112                         = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1113         }
1114
1115         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1116         
1117         if (!group) {
1118                 group = IDP_New(IDP_GROUP, &val, type);
1119                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1120         }
1121
1122         if (parent_index) {
1123                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1124         }
1125         else {
1126                 BLI_strncpy(name, o->name, sizeof(name));
1127         }
1128
1129         fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1130                 type, parent_index, opt_index, name);
1131
1132         prop = IDP_GetPropertyFromGroup(group, name);
1133         if (prop) {
1134                 return prop;
1135         }
1136
1137         switch (o->type) {
1138         case FF_OPT_TYPE_INT:
1139         case FF_OPT_TYPE_INT64:
1140                 val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1141                 idp_type = IDP_INT;
1142                 break;
1143         case FF_OPT_TYPE_DOUBLE:
1144         case FF_OPT_TYPE_FLOAT:
1145                 val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1146                 idp_type = IDP_FLOAT;
1147                 break;
1148         case FF_OPT_TYPE_STRING:
1149                 val.string.str = (char *)"                                                                               ";
1150                 val.string.len = 80;
1151 /*              val.str = (char *)"                                                                               ";*/
1152                 idp_type = IDP_STRING;
1153                 break;
1154         case FF_OPT_TYPE_CONST:
1155                 val.i = 1;
1156                 idp_type = IDP_INT;
1157                 break;
1158         default:
1159                 return NULL;
1160         }
1161         prop = IDP_New(idp_type, &val, name);
1162         IDP_AddToGroup(group, prop);
1163         return prop;
1164 }
1165
1166 /* not all versions of ffmpeg include that, so here we go ... */
1167
1168 static const AVOption *my_av_find_opt(void *v, const char *name,
1169                                       const char *unit, int mask, int flags)
1170 {
1171         AVClass *c= *(AVClass**)v; 
1172         const AVOption *o= c->option;
1173
1174         for (;o && o->name; o++) {
1175                 if (!strcmp(o->name, name) && 
1176                    (!unit || (o->unit && !strcmp(o->unit, unit))) && 
1177                    (o->flags & mask) == flags )
1178                         return o;
1179         }
1180         return NULL;
1181 }
1182
1183 int 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 = ffmpeg_property_add(rd,
1220                         (char*) type, p - c.av_class->option, 
1221                         o - c.av_class->option);
1222         }
1223         else {
1224                 prop = 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                 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                 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1275                 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1276                 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1277                 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1278                 ffmpeg_property_add_string(rd, "video", "me:hex");
1279                 ffmpeg_property_add_string(rd, "video", "subq:6");
1280                 ffmpeg_property_add_string(rd, "video", "me_range:16");
1281                 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1282                 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1283                 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1284                 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1285                 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1286                 ffmpeg_property_add_string(rd, "video", "bf:3");
1287                 ffmpeg_property_add_string(rd, "video", "refs:2");
1288                 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1289                 ffmpeg_property_add_string(rd, "video", "directpred:3");
1290                 ffmpeg_property_add_string(rd, "video", "trellis:0");
1291                 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1292                 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1293                 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1294                 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1295
1296                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1297                         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 ffmpeg_set_preset(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 ffmpeg_verify_image_type(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                         ffmpeg_set_preset(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                         ffmpeg_set_preset(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                         ffmpeg_set_preset(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                         ffmpeg_set_preset(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 ffmpeg_verify_codec_settings(RenderData *rd)
1447 {
1448         ffmpeg_set_expert_options(rd);
1449 }
1450
1451 int ffmpeg_alpha_channel_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