d975e60146fa68cf73c3abfba3bc872dc539661a
[blender.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s):
19  *
20  * Partial Copyright (c) 2006 Peter Schlaile
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/blenkernel/intern/writeffmpeg.c
26  *  \ingroup bke
27  */
28
29 #ifdef WITH_FFMPEG
30 #include <string.h>
31 #include <stdio.h>
32
33 #if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
34 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
35 #if _MSC_VER < 1400
36 #include <stdint.h>
37 #endif
38 #endif
39
40 #include <stdlib.h>
41
42 #include <libavformat/avformat.h>
43 #include <libavcodec/avcodec.h>
44 #include <libavutil/rational.h>
45 #include <libavutil/samplefmt.h>
46 #include <libswscale/swscale.h>
47
48 #include "MEM_guardedalloc.h"
49
50 #include "DNA_scene_types.h"
51
52 #include "BLI_blenlib.h"
53
54 #ifdef WITH_AUDASPACE
55 #  include "AUD_C-API.h"
56 #endif
57
58 #include "BLI_utildefines.h"
59
60 #include "BKE_global.h"
61 #include "BKE_idprop.h"
62 #include "BKE_main.h"
63 #include "BKE_report.h"
64 #include "BKE_sound.h"
65 #include "BKE_writeffmpeg.h"
66
67 #include "IMB_imbuf_types.h"
68 #include "IMB_imbuf.h"
69
70 #include "ffmpeg_compat.h"
71
72 static int ffmpeg_type = 0;
73 static int ffmpeg_codec = CODEC_ID_MPEG4;
74 static int ffmpeg_audio_codec = CODEC_ID_NONE;
75 static int ffmpeg_video_bitrate = 1150;
76 static int ffmpeg_audio_bitrate = 128;
77 static int ffmpeg_gop_size = 12;
78 static int ffmpeg_autosplit = 0;
79 static int ffmpeg_autosplit_count = 0;
80
81 static AVFormatContext *outfile = 0;
82 static AVStream *video_stream = 0;
83 static AVStream *audio_stream = 0;
84 static AVFrame *current_frame = 0;
85 static struct SwsContext *img_convert_ctx = 0;
86
87 static uint8_t *video_buffer = 0;
88 static int video_buffersize = 0;
89
90 static uint8_t *audio_input_buffer = 0;
91 static uint8_t *audio_deinterleave_buffer = 0;
92 static int audio_input_samples = 0;
93 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
94 static uint8_t *audio_output_buffer = 0;
95 static int audio_outbuf_size = 0;
96 #endif
97 static double audio_time = 0.0f;
98 static bool audio_deinterleave = false;
99 static int audio_sample_size = 0;
100
101 #ifdef WITH_AUDASPACE
102 static AUD_Device *audio_mixdown_device = 0;
103 #endif
104
105 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
106
107 #define PRINT if (G.debug & G_DEBUG_FFMPEG) printf
108
109 /* Delete a picture buffer */
110
111 static void delete_picture(AVFrame *f)
112 {
113         if (f) {
114                 if (f->data[0]) MEM_freeN(f->data[0]);
115                 av_free(f);
116         }
117 }
118
119 static int request_float_audio_buffer(int codec_id)
120 {
121         /* If any of these codecs, we prefer the float sample format (if supported) */
122         return codec_id == CODEC_ID_AAC || codec_id == CODEC_ID_AC3 || codec_id == CODEC_ID_VORBIS;
123 }
124
125 #ifdef WITH_AUDASPACE
126 static int write_audio_frame(void) 
127 {
128         AVCodecContext *c = NULL;
129         AVPacket pkt;
130         AVFrame *frame = NULL;
131         int got_output = 0;
132
133         c = audio_stream->codec;
134
135         av_init_packet(&pkt);
136         pkt.size = 0;
137         pkt.data = NULL;
138
139         AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
140         audio_time += (double) audio_input_samples / (double) c->sample_rate;
141
142 #ifdef FFMPEG_HAVE_ENCODE_AUDIO2
143         frame = avcodec_alloc_frame();
144         frame->pts = audio_time / av_q2d(c->time_base);
145         frame->nb_samples = audio_input_samples;
146         frame->format = c->sample_fmt;
147 #ifdef FFMPEG_HAVE_FRAME_CHANNEL_LAYOUT
148         frame->channel_layout = c->channel_layout;
149 #endif
150
151         if (audio_deinterleave) {
152                 int channel, i;
153                 uint8_t *temp;
154
155                 for (channel = 0; channel < c->channels; channel++) {
156                         for (i = 0; i < frame->nb_samples; i++) {
157                                 memcpy(audio_deinterleave_buffer + (i + channel * frame->nb_samples) * audio_sample_size,
158                                            audio_input_buffer + (c->channels * i + channel) * audio_sample_size, audio_sample_size);
159                         }
160                 }
161
162                 temp = audio_deinterleave_buffer;
163                 audio_deinterleave_buffer = audio_input_buffer;
164                 audio_input_buffer = temp;
165         }
166
167         avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt, audio_input_buffer,
168                                  audio_input_samples * c->channels * audio_sample_size, 1);
169
170         if (avcodec_encode_audio2(c, &pkt, frame, &got_output) < 0) {
171                 // XXX error("Error writing audio packet");
172                 return -1;
173         }
174
175         if (!got_output) {
176                 avcodec_free_frame(&frame);
177                 return 0;
178         }
179 #else
180         pkt.size = avcodec_encode_audio(c, audio_output_buffer, audio_outbuf_size, (short *) audio_input_buffer);
181
182         if (pkt.size < 0) {
183                 // XXX error("Error writing audio packet");
184                 return -1;
185         }
186
187         pkt.data = audio_output_buffer;
188         got_output = 1;
189 #endif
190
191         if (got_output) {
192                 if (pkt.pts != AV_NOPTS_VALUE)
193                         pkt.pts = av_rescale_q(pkt.pts, c->time_base, audio_stream->time_base);
194                 if (pkt.dts != AV_NOPTS_VALUE)
195                         pkt.dts = av_rescale_q(pkt.dts, c->time_base, audio_stream->time_base);
196                 if (pkt.duration > 0)
197                         pkt.duration = av_rescale_q(pkt.duration, c->time_base, audio_stream->time_base);
198
199                 pkt.stream_index = audio_stream->index;
200
201                 pkt.flags |= AV_PKT_FLAG_KEY;
202
203                 if (av_interleaved_write_frame(outfile, &pkt) != 0) {
204                         fprintf(stderr, "Error writing audio packet!\n");
205                         if (frame)
206                                 avcodec_free_frame(&frame);
207                         return -1;
208                 }
209
210                 av_free_packet(&pkt);
211         }
212
213         if (frame)
214                 avcodec_free_frame(&frame);
215
216         return 0;
217 }
218 #endif // #ifdef WITH_AUDASPACE
219
220 /* Allocate a temporary frame */
221 static AVFrame *alloc_picture(int pix_fmt, int width, int height)
222 {
223         AVFrame *f;
224         uint8_t *buf;
225         int size;
226         
227         /* allocate space for the struct */
228         f = avcodec_alloc_frame();
229         if (!f) return NULL;
230         size = avpicture_get_size(pix_fmt, width, height);
231         /* allocate the actual picture buffer */
232         buf = MEM_mallocN(size, "AVFrame buffer");
233         if (!buf) {
234                 free(f);
235                 return NULL;
236         }
237         avpicture_fill((AVPicture *)f, buf, pix_fmt, width, height);
238         return f;
239 }
240
241 /* Get the correct file extensions for the requested format,
242  * first is always desired guess_format parameter */
243 static const char **get_file_extensions(int format)
244 {
245         switch (format) {
246                 case FFMPEG_DV:
247                 {
248                         static const char *rv[] = { ".dv", NULL };
249                         return rv;
250                 }
251                 case FFMPEG_MPEG1:
252                 {
253                         static const char *rv[] = { ".mpg", ".mpeg", NULL };
254                         return rv;
255                 }
256                 case FFMPEG_MPEG2:
257                 {
258                         static const char *rv[] = { ".dvd", ".vob", ".mpg", ".mpeg", NULL };
259                         return rv;
260                 }
261                 case FFMPEG_MPEG4:
262                 {
263                         static const char *rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
264                         return rv;
265                 }
266                 case FFMPEG_AVI:
267                 {
268                         static const char *rv[] = { ".avi", NULL };
269                         return rv;
270                 }
271                 case FFMPEG_MOV:
272                 {
273                         static const char *rv[] = { ".mov", NULL };
274                         return rv;
275                 }
276                 case FFMPEG_H264:
277                 {
278                         /* FIXME: avi for now... */
279                         static const char *rv[] = { ".avi", NULL };
280                         return rv;
281                 }
282
283                 case FFMPEG_XVID:
284                 {
285                         /* FIXME: avi for now... */
286                         static const char *rv[] = { ".avi", NULL };
287                         return rv;
288                 }
289                 case FFMPEG_FLV:
290                 {
291                         static const char *rv[] = { ".flv", NULL };
292                         return rv;
293                 }
294                 case FFMPEG_MKV:
295                 {
296                         static const char *rv[] = { ".mkv", NULL };
297                         return rv;
298                 }
299                 case FFMPEG_OGG:
300                 {
301                         static const char *rv[] = { ".ogv", ".ogg", NULL };
302                         return rv;
303                 }
304                 default:
305                         return NULL;
306         }
307 }
308
309 /* Write a frame to the output file */
310 static int write_video_frame(RenderData *rd, int cfra, AVFrame *frame, ReportList *reports)
311 {
312         int outsize = 0;
313         int ret, success = 1;
314         AVCodecContext *c = video_stream->codec;
315
316         frame->pts = cfra;
317
318         if (rd->mode & R_FIELDS) {
319                 frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
320         }
321
322         outsize = avcodec_encode_video(c, video_buffer, video_buffersize,  frame);
323
324         if (outsize > 0) {
325                 AVPacket packet;
326                 av_init_packet(&packet);
327
328                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
329                         packet.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_stream->time_base);
330                         PRINT("Video Frame PTS: %d\n", (int)packet.pts);
331                 }
332                 else {
333                         PRINT("Video Frame PTS: not set\n");
334                 }
335                 if (c->coded_frame->key_frame)
336                         packet.flags |= AV_PKT_FLAG_KEY;
337                 packet.stream_index = video_stream->index;
338                 packet.data = video_buffer;
339                 packet.size = outsize;
340                 ret = av_interleaved_write_frame(outfile, &packet);
341                 success = (ret == 0);
342         }
343         else if (outsize < 0) {
344                 success = 0;
345         }
346
347         if (!success)
348                 BKE_report(reports, RPT_ERROR, "Error writing frame");
349
350         return success;
351 }
352
353 /* read and encode a frame of audio from the buffer */
354 static AVFrame *generate_video_frame(uint8_t *pixels, ReportList *reports)
355 {
356         uint8_t *rendered_frame;
357
358         AVCodecContext *c = video_stream->codec;
359         int width = c->width;
360         int height = c->height;
361         AVFrame *rgb_frame;
362
363         if (c->pix_fmt != PIX_FMT_BGR32) {
364                 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
365                 if (!rgb_frame) {
366                         BKE_report(reports, RPT_ERROR, "Could not allocate temporary frame");
367                         return NULL;
368                 }
369         }
370         else {
371                 rgb_frame = current_frame;
372         }
373
374         rendered_frame = pixels;
375
376         /* Do RGBA-conversion and flipping in one step depending
377          * on CPU-Endianess */
378
379         if (ENDIAN_ORDER == L_ENDIAN) {
380                 int y;
381                 for (y = 0; y < height; y++) {
382                         uint8_t *target = rgb_frame->data[0] + width * 4 * (height - y - 1);
383                         uint8_t *src = rendered_frame + width * 4 * y;
384                         uint8_t *end = src + width * 4;
385                         while (src != end) {
386                                 target[3] = src[3];
387                                 target[2] = src[2];
388                                 target[1] = src[1];
389                                 target[0] = src[0];
390
391                                 target += 4;
392                                 src += 4;
393                         }
394                 }
395         }
396         else {
397                 int y;
398                 for (y = 0; y < height; y++) {
399                         uint8_t *target = rgb_frame->data[0] + width * 4 * (height - y - 1);
400                         uint8_t *src = rendered_frame + width * 4 * y;
401                         uint8_t *end = src + width * 4;
402                         while (src != end) {
403                                 target[3] = src[0];
404                                 target[2] = src[1];
405                                 target[1] = src[2];
406                                 target[0] = src[3];
407
408                                 target += 4;
409                                 src += 4;
410                         }
411                 }
412         }
413
414         if (c->pix_fmt != PIX_FMT_BGR32) {
415                 sws_scale(img_convert_ctx, (const uint8_t *const *) rgb_frame->data,
416                           rgb_frame->linesize, 0, c->height,
417                           current_frame->data, current_frame->linesize);
418                 delete_picture(rgb_frame);
419         }
420         return current_frame;
421 }
422
423 static void set_ffmpeg_property_option(AVCodecContext *c, IDProperty *prop)
424 {
425         char name[128];
426         char *param;
427         int fail = TRUE;
428
429         PRINT("FFMPEG expert option: %s: ", prop->name);
430
431         BLI_strncpy(name, prop->name, sizeof(name));
432
433         param = strchr(name, ':');
434
435         if (param) {
436                 *param++ = 0;
437         }
438
439         switch (prop->type) {
440                 case IDP_STRING:
441                         PRINT("%s.\n", IDP_String(prop));
442                         fail = av_opt_set(c, prop->name, IDP_String(prop), 0);
443                         break;
444                 case IDP_FLOAT:
445                         PRINT("%g.\n", IDP_Float(prop));
446                         fail = av_opt_set_double(c, prop->name, IDP_Float(prop), 0);
447                         break;
448                 case IDP_INT:
449                         PRINT("%d.\n", IDP_Int(prop));
450
451                         if (param) {
452                                 if (IDP_Int(prop)) {
453                                         fail = av_opt_set(c, name, param, 0);
454                                 }
455                                 else {
456                                         return;
457                                 }
458                         }
459                         else {
460                                 fail = av_opt_set_int(c, prop->name, IDP_Int(prop), 0);
461                         }
462                         break;
463         }
464
465         if (fail) {
466                 PRINT("ffmpeg-option not supported: %s! Skipping.\n", prop->name);
467         }
468 }
469
470 static int ffmpeg_proprty_valid(AVCodecContext *c, const char *prop_name, IDProperty *curr)
471 {
472         int valid = 1;
473
474         if (strcmp(prop_name, "video") == 0) {
475                 if (strcmp(curr->name, "bf") == 0) {
476                         /* flash codec doesn't support b frames */
477                         valid &= c->codec_id != CODEC_ID_FLV1;
478                 }
479         }
480
481         return valid;
482 }
483
484 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char *prop_name)
485 {
486         IDProperty *prop;
487         void *iter;
488         IDProperty *curr;
489
490         if (!rd->ffcodecdata.properties) {
491                 return;
492         }
493         
494         prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name);
495         if (!prop) {
496                 return;
497         }
498
499         iter = IDP_GetGroupIterator(prop);
500
501         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
502                 if (ffmpeg_proprty_valid(c, prop_name, curr))
503                         set_ffmpeg_property_option(c, curr);
504         }
505 }
506
507 /* prepare a video stream for the output file */
508
509 static AVStream *alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext *of,
510                                     int rectx, int recty, char *error, int error_size)
511 {
512         AVStream *st;
513         AVCodecContext *c;
514         AVCodec *codec;
515
516         error[0] = '\0';
517
518         st = avformat_new_stream(of, NULL);
519         if (!st) return NULL;
520         st->id = 0;
521
522         /* Set up the codec context */
523         
524         c = st->codec;
525         c->codec_id = codec_id;
526         c->codec_type = AVMEDIA_TYPE_VIDEO;
527
528         /* Get some values from the current render settings */
529         
530         c->width = rectx;
531         c->height = recty;
532
533         /* FIXME: Really bad hack (tm) for NTSC support */
534         if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
535                 c->time_base.den = 2997;
536                 c->time_base.num = 100;
537         }
538         else if ((float) ((int) rd->frs_sec_base) == rd->frs_sec_base) {
539                 c->time_base.den = rd->frs_sec;
540                 c->time_base.num = (int) rd->frs_sec_base;
541         }
542         else {
543                 c->time_base.den = rd->frs_sec * 100000;
544                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
545         }
546         
547         c->gop_size = ffmpeg_gop_size;
548         c->bit_rate = ffmpeg_video_bitrate * 1000;
549         c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
550         c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
551         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
552
553 #if 0
554         /* this options are not set in ffmpeg.c and leads to artifacts with MPEG-4
555          * see #33586: Encoding to mpeg4 makes first frame(s) blocky
556          */
557         c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
558         c->rc_buffer_aggressivity = 1.0;
559 #endif
560
561         c->me_method = ME_EPZS;
562         
563         codec = avcodec_find_encoder(c->codec_id);
564         if (!codec)
565                 return NULL;
566         
567         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
568
569         if (codec->pix_fmts) {
570                 c->pix_fmt = codec->pix_fmts[0];
571         }
572         else {
573                 /* makes HuffYUV happy ... */
574                 c->pix_fmt = PIX_FMT_YUV422P;
575         }
576
577         if (ffmpeg_type == FFMPEG_XVID) {
578                 /* arghhhh ... */
579                 c->pix_fmt = PIX_FMT_YUV420P;
580                 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
581         }
582
583         if (codec_id == CODEC_ID_H264) {
584                 /* correct wrong default ffmpeg param which crash x264 */
585                 c->qmin = 10;
586                 c->qmax = 51;
587         }
588         
589         /* Keep lossless encodes in the RGB domain. */
590         if (codec_id == CODEC_ID_HUFFYUV) {
591                 /* HUFFYUV was PIX_FMT_YUV422P before */
592                 c->pix_fmt = PIX_FMT_RGB32;
593         }
594
595         if (codec_id == CODEC_ID_FFV1) {
596                 c->pix_fmt = PIX_FMT_RGB32;
597         }
598
599         if (codec_id == CODEC_ID_QTRLE) {
600                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
601                         c->pix_fmt = PIX_FMT_ARGB;
602                 }
603         }
604
605         if (codec_id == CODEC_ID_PNG) {
606                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
607                         c->pix_fmt = PIX_FMT_ARGB;
608                 }
609         }
610
611         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
612 #if 0
613             || !strcmp(of->oformat->name, "mp4")
614             || !strcmp(of->oformat->name, "mov")
615             || !strcmp(of->oformat->name, "3gp")
616 #endif
617             )
618         {
619                 PRINT("Using global header\n");
620                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
621         }
622         
623         /* Determine whether we are encoding interlaced material or not */
624         if (rd->mode & R_FIELDS) {
625                 PRINT("Encoding interlaced video\n");
626                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
627                 c->flags |= CODEC_FLAG_INTERLACED_ME;
628         }
629
630         /* xasp & yasp got float lately... */
631
632         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);
633
634         set_ffmpeg_properties(rd, c, "video");
635         
636         if (avcodec_open2(c, codec, NULL) < 0) {
637                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
638                 return NULL;
639         }
640
641         if (codec_id == CODEC_ID_QTRLE) {
642                 /* normally it should be enough to have buffer with actual image size,
643                  * but some codecs like QTRLE might store extra information in this buffer,
644                  * so it should be a way larger */
645
646                 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
647                  * (from FFmpeg sources) */
648                 int size = c->width * c->height;
649                 video_buffersize = 7 * size + 10000;
650         }
651         else
652                 video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
653
654         video_buffer = (uint8_t *)MEM_mallocN(video_buffersize * sizeof(uint8_t), "FFMPEG video buffer");
655         
656         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
657
658         img_convert_ctx = sws_getContext(c->width, c->height, PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
659                                          NULL, NULL, NULL);
660         return st;
661 }
662
663 static AVStream *alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext *of, char *error, int error_size)
664 {
665         AVStream *st;
666         AVCodecContext *c;
667         AVCodec *codec;
668
669         error[0] = '\0';
670
671         st = avformat_new_stream(of, NULL);
672         if (!st) return NULL;
673         st->id = 1;
674
675         c = st->codec;
676         c->codec_id = codec_id;
677         c->codec_type = AVMEDIA_TYPE_AUDIO;
678
679         c->sample_rate = rd->ffcodecdata.audio_mixrate;
680         c->bit_rate = ffmpeg_audio_bitrate * 1000;
681         c->sample_fmt = AV_SAMPLE_FMT_S16;
682         c->channels = rd->ffcodecdata.audio_channels;
683
684         if (request_float_audio_buffer(codec_id)) {
685                 /* mainly for AAC codec which is experimental */
686                 c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
687                 c->sample_fmt = AV_SAMPLE_FMT_FLT;
688         }
689
690         codec = avcodec_find_encoder(c->codec_id);
691         if (!codec) {
692                 //XXX error("Couldn't find a valid audio codec");
693                 return NULL;
694         }
695
696         if (codec->sample_fmts) {
697                 /* check if the prefered sample format for this codec is supported.
698                  * this is because, depending on the version of libav, and with the whole ffmpeg/libav fork situation,
699                  * you have various implementations around. float samples in particular are not always supported.
700                  */
701                 const enum AVSampleFormat *p = codec->sample_fmts;
702                 for (; *p!=-1; p++) {
703                         if (*p == st->codec->sample_fmt)
704                                 break;
705                 }
706                 if (*p == -1) {
707                         /* sample format incompatible with codec. Defaulting to a format known to work */
708                         st->codec->sample_fmt = codec->sample_fmts[0];
709                 }
710         }
711
712         if (codec->supported_samplerates) {
713                 const int *p = codec->supported_samplerates;
714                 int best = 0;
715                 int best_dist = INT_MAX;
716                 for (; *p; p++) {
717                         int dist = abs(st->codec->sample_rate - *p);
718                         if (dist < best_dist) {
719                                 best_dist = dist;
720                                 best = *p;
721                         }
722                 }
723                 /* best is the closest supported sample rate (same as selected if best_dist == 0) */
724                 st->codec->sample_rate = best;
725         }
726
727         set_ffmpeg_properties(rd, c, "audio");
728
729         if (avcodec_open2(c, codec, NULL) < 0) {
730                 //XXX error("Couldn't initialize audio codec");
731                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
732                 return NULL;
733         }
734
735         /* need to prevent floating point exception when using vorbis audio codec,
736          * initialize this value in the same way as it's done in FFmpeg iteslf (sergey) */
737         st->codec->time_base.num = 1;
738         st->codec->time_base.den = st->codec->sample_rate;
739
740 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
741         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
742 #endif
743
744         if (c->frame_size == 0)
745                 // used to be if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
746                 // not sure if that is needed anymore, so let's try out if there are any
747                 // complaints regarding some ffmpeg versions users might have
748                 audio_input_samples = FF_MIN_BUFFER_SIZE * 8 / c->bits_per_coded_sample / c->channels;
749         else {
750                 audio_input_samples = c->frame_size;
751 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
752                 if (c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
753                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
754 #endif
755         }
756
757         audio_deinterleave = av_sample_fmt_is_planar(c->sample_fmt);
758
759         audio_sample_size = av_get_bytes_per_sample(c->sample_fmt);
760
761         audio_input_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * audio_sample_size);
762 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
763         audio_output_buffer = (uint8_t *) av_malloc(audio_outbuf_size);
764 #endif
765
766         if (audio_deinterleave)
767                 audio_deinterleave_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * audio_sample_size);
768
769         audio_time = 0.0f;
770
771         return st;
772 }
773 /* essential functions -- start, append, end */
774
775 static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
776 {
777         char buffer[32];
778
779         BLI_snprintf(buffer, sizeof(buffer), "%d", value);
780
781         av_dict_set(dict, key, buffer, 0);
782 }
783
784 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
785 {
786         /* Handle to the output file */
787         AVFormatContext *of;
788         AVOutputFormat *fmt;
789         AVDictionary *opts = NULL;
790         char name[256], error[1024];
791         const char **exts;
792
793         ffmpeg_type = rd->ffcodecdata.type;
794         ffmpeg_codec = rd->ffcodecdata.codec;
795         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
796         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
797         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
798         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
799         ffmpeg_autosplit = rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT;
800         
801         /* Determine the correct filename */
802         BKE_ffmpeg_filepath_get(name, rd);
803         PRINT("Starting output to %s(ffmpeg)...\n"
804                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
805                 "  video_bitrate=%d, audio_bitrate=%d,\n"
806                 "  gop_size=%d, autosplit=%d\n"
807                 "  render width=%d, render height=%d\n",
808                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
809                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
810                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
811         
812         exts = get_file_extensions(ffmpeg_type);
813         if (!exts) {
814                 BKE_report(reports, RPT_ERROR, "No valid formats found");
815                 return 0;
816         }
817         fmt = av_guess_format(NULL, exts[0], NULL);
818         if (!fmt) {
819                 BKE_report(reports, RPT_ERROR, "No valid formats found");
820                 return 0;
821         }
822
823         of = avformat_alloc_context();
824         if (!of) {
825                 BKE_report(reports, RPT_ERROR, "Error opening output file");
826                 return 0;
827         }
828         
829         of->oformat = fmt;
830         of->packet_size = rd->ffcodecdata.mux_packet_size;
831         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
832                 ffmpeg_dict_set_int(&opts, "muxrate", rd->ffcodecdata.mux_rate);
833         }
834         else {
835                 av_dict_set(&opts, "muxrate", "0", 0);
836         }
837
838         ffmpeg_dict_set_int(&opts, "preload", (int)(0.5 * AV_TIME_BASE));
839
840         of->max_delay = (int)(0.7 * AV_TIME_BASE);
841
842         fmt->audio_codec = ffmpeg_audio_codec;
843
844         BLI_strncpy(of->filename, name, sizeof(of->filename));
845         /* set the codec to the user's selection */
846         switch (ffmpeg_type) {
847                 case FFMPEG_AVI:
848                 case FFMPEG_MOV:
849                 case FFMPEG_MKV:
850                         fmt->video_codec = ffmpeg_codec;
851                         break;
852                 case FFMPEG_OGG:
853                         fmt->video_codec = CODEC_ID_THEORA;
854                         break;
855                 case FFMPEG_DV:
856                         fmt->video_codec = CODEC_ID_DVVIDEO;
857                         break;
858                 case FFMPEG_MPEG1:
859                         fmt->video_codec = CODEC_ID_MPEG1VIDEO;
860                         break;
861                 case FFMPEG_MPEG2:
862                         fmt->video_codec = CODEC_ID_MPEG2VIDEO;
863                         break;
864                 case FFMPEG_H264:
865                         fmt->video_codec = CODEC_ID_H264;
866                         break;
867                 case FFMPEG_XVID:
868                         fmt->video_codec = CODEC_ID_MPEG4;
869                         break;
870                 case FFMPEG_FLV:
871                         fmt->video_codec = CODEC_ID_FLV1;
872                         break;
873                 case FFMPEG_MPEG4:
874                 default:
875                         fmt->video_codec = CODEC_ID_MPEG4;
876                         break;
877         }
878         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
879                 if (rectx != 720) {
880                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
881                         return 0;
882                 }
883                 if (rd->frs_sec != 25 && recty != 480) {
884                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
885                         return 0;
886                 }
887                 if (rd->frs_sec == 25 && recty != 576) {
888                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
889                         return 0;
890                 }
891         }
892         
893         if (ffmpeg_type == FFMPEG_DV) {
894                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
895                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
896                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
897                         av_dict_free(&opts);
898                         return 0;
899                 }
900         }
901         
902         if (fmt->video_codec != CODEC_ID_NONE) {
903                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty, error, sizeof(error));
904                 PRINT("alloc video stream %p\n", video_stream);
905                 if (!video_stream) {
906                         if (error[0])
907                                 BKE_report(reports, RPT_ERROR, error);
908                         else
909                                 BKE_report(reports, RPT_ERROR, "Error initializing video stream");
910
911                         av_dict_free(&opts);
912                         return 0;
913                 }
914         }
915
916         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
917                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of, error, sizeof(error));
918                 if (!audio_stream) {
919                         if (error[0])
920                                 BKE_report(reports, RPT_ERROR, error);
921                         else
922                                 BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
923                         av_dict_free(&opts);
924                         return 0;
925                 }
926         }
927         if (!(fmt->flags & AVFMT_NOFILE)) {
928                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
929                         BKE_report(reports, RPT_ERROR, "Could not open file for writing");
930                         av_dict_free(&opts);
931                         return 0;
932                 }
933         }
934         if (avformat_write_header(of, NULL) < 0) {
935                 BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
936                 av_dict_free(&opts);
937                 avio_close(of->pb);
938                 return 0;
939         }
940
941         outfile = of;
942         av_dump_format(of, 0, name, 1);
943         av_dict_free(&opts);
944
945         return 1;
946 }
947
948 /**
949  * Writes any delayed frames in the encoder. This function is called before 
950  * closing the encoder.
951  *
952  * <p>
953  * Since an encoder may use both past and future frames to predict 
954  * inter-frames (H.264 B-frames, for example), it can output the frames 
955  * in a different order from the one it was given.
956  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
957  * them in the order 1, 4, 2, 3 - first the two frames used for prediction,
958  * and then the bidirectionally-predicted frames. What this means in practice 
959  * is that the encoder may not immediately produce one output frame for each 
960  * input frame. These delayed frames must be flushed before we close the 
961  * stream. We do this by calling avcodec_encode_video with NULL for the last 
962  * parameter.
963  * </p>
964  */
965 static void flush_ffmpeg(void)
966 {
967         int outsize = 0;
968         int ret = 0;
969         
970         AVCodecContext *c = video_stream->codec;
971         /* get the delayed frames */
972         while (1) {
973                 AVPacket packet;
974                 av_init_packet(&packet);
975                 
976                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
977                 if (outsize < 0) {
978                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
979                         break;
980                 }
981                 if (outsize == 0) {
982                         break;
983                 }
984                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
985                         packet.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_stream->time_base);
986                         PRINT("Video Frame PTS: %d\n", (int) packet.pts);
987                 }
988                 else {
989                         PRINT("Video Frame PTS: not set\n");
990                 }
991                 if (c->coded_frame->key_frame) {
992                         packet.flags |= AV_PKT_FLAG_KEY;
993                 }
994                 packet.stream_index = video_stream->index;
995                 packet.data = video_buffer;
996                 packet.size = outsize;
997                 ret = av_interleaved_write_frame(outfile, &packet);
998                 if (ret != 0) {
999                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
1000                         break;
1001                 }
1002         }
1003         avcodec_flush_buffers(video_stream->codec);
1004 }
1005
1006 /* **********************************************************************
1007  * * public interface
1008  * ********************************************************************** */
1009
1010 /* Get the output filename-- similar to the other output formats */
1011 void BKE_ffmpeg_filepath_get(char *string, RenderData *rd)
1012 {
1013         char autosplit[20];
1014
1015         const char **exts = get_file_extensions(rd->ffcodecdata.type);
1016         const char **fe = exts;
1017
1018         if (!string || !exts) return;
1019
1020         strcpy(string, rd->pic);
1021         BLI_path_abs(string, G.main->name);
1022
1023         BLI_make_existing_file(string);
1024
1025         autosplit[0] = 0;
1026
1027         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
1028                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
1029         }
1030
1031         if (rd->scemode & R_EXTENSION) {
1032                 while (*fe) {
1033                         if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0) {
1034                                 break;
1035                         }
1036                         fe++;
1037                 }
1038
1039                 if (*fe == NULL) {
1040                         strcat(string, autosplit);
1041
1042                         BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
1043                         strcat(string, *exts);
1044                 }
1045                 else {
1046                         *(string + strlen(string) - strlen(*fe)) = 0;
1047                         strcat(string, autosplit);
1048                         strcat(string, *fe);
1049                 }
1050         }
1051         else {
1052                 if (BLI_path_frame_check_chars(string)) {
1053                         BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
1054                 }
1055
1056                 strcat(string, autosplit);
1057         }
1058 }
1059
1060 int BKE_ffmpeg_start(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
1061 {
1062         int success;
1063
1064         ffmpeg_autosplit_count = 0;
1065
1066         success = start_ffmpeg_impl(rd, rectx, recty, reports);
1067 #ifdef WITH_AUDASPACE
1068         if (audio_stream) {
1069                 AVCodecContext *c = audio_stream->codec;
1070                 AUD_DeviceSpecs specs;
1071                 specs.channels = c->channels;
1072
1073                 switch (av_get_packed_sample_fmt(c->sample_fmt)) {
1074                         case AV_SAMPLE_FMT_U8:
1075                                 specs.format = AUD_FORMAT_U8;
1076                                 break;
1077                         case AV_SAMPLE_FMT_S16:
1078                                 specs.format = AUD_FORMAT_S16;
1079                                 break;
1080                         case AV_SAMPLE_FMT_S32:
1081                                 specs.format = AUD_FORMAT_S32;
1082                                 break;
1083                         case AV_SAMPLE_FMT_FLT:
1084                                 specs.format = AUD_FORMAT_FLOAT32;
1085                                 break;
1086                         case AV_SAMPLE_FMT_DBL:
1087                                 specs.format = AUD_FORMAT_FLOAT64;
1088                                 break;
1089                         default:
1090                                 return -31415;
1091                 }
1092
1093                 specs.rate = rd->ffcodecdata.audio_mixrate;
1094                 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
1095 #ifdef FFMPEG_CODEC_TIME_BASE
1096                 c->time_base.den = specs.rate;
1097                 c->time_base.num = 1;
1098 #endif
1099         }
1100 #endif
1101         return success;
1102 }
1103
1104 static void end_ffmpeg_impl(int is_autosplit);
1105
1106 #ifdef WITH_AUDASPACE
1107 static void write_audio_frames(double to_pts)
1108 {
1109         int finished = 0;
1110
1111         while (audio_stream && !finished) {
1112                 if ((audio_time >= to_pts) ||
1113                     (write_audio_frame()))
1114                 {
1115                         finished = 1;
1116                 }
1117         }
1118 }
1119 #endif
1120
1121 int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
1122 {
1123         AVFrame *avframe;
1124         int success = 1;
1125
1126         PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);
1127
1128 /* why is this done before writing the video frame and again at end_ffmpeg? */
1129 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
1130
1131         if (video_stream) {
1132                 avframe = generate_video_frame((unsigned char *) pixels, reports);
1133                 success = (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));
1134
1135                 if (ffmpeg_autosplit) {
1136                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
1137                                 end_ffmpeg_impl(TRUE);
1138                                 ffmpeg_autosplit_count++;
1139                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
1140                         }
1141                 }
1142         }
1143
1144 #ifdef WITH_AUDASPACE
1145         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / (double)rd->frs_sec_base));
1146 #endif
1147         return success;
1148 }
1149
1150 static void end_ffmpeg_impl(int is_autosplit)
1151 {
1152         unsigned int i;
1153         
1154         PRINT("Closing ffmpeg...\n");
1155
1156 #if 0
1157         if (audio_stream) { /* SEE UPPER */
1158                 write_audio_frames();
1159         }
1160 #endif
1161
1162 #ifdef WITH_AUDASPACE
1163         if (is_autosplit == FALSE) {
1164                 if (audio_mixdown_device) {
1165                         AUD_closeReadDevice(audio_mixdown_device);
1166                         audio_mixdown_device = 0;
1167                 }
1168         }
1169 #endif
1170
1171         if (video_stream && video_stream->codec) {
1172                 PRINT("Flushing delayed frames...\n");
1173                 flush_ffmpeg();
1174         }
1175         
1176         if (outfile) {
1177                 av_write_trailer(outfile);
1178         }
1179         
1180         /* Close the video codec */
1181
1182         if (video_stream && video_stream->codec) {
1183                 avcodec_close(video_stream->codec);
1184                 PRINT("zero video stream %p\n", video_stream);
1185                 video_stream = 0;
1186         }
1187
1188         
1189         /* Close the output file */
1190         if (outfile) {
1191                 for (i = 0; i < outfile->nb_streams; i++) {
1192                         if (&outfile->streams[i]) {
1193                                 av_freep(&outfile->streams[i]);
1194                         }
1195                 }
1196         }
1197         /* free the temp buffer */
1198         if (current_frame) {
1199                 delete_picture(current_frame);
1200                 current_frame = 0;
1201         }
1202         if (outfile && outfile->oformat) {
1203                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1204                         avio_close(outfile->pb);
1205                 }
1206         }
1207         if (outfile) {
1208                 av_free(outfile);
1209                 outfile = 0;
1210         }
1211         if (video_buffer) {
1212                 MEM_freeN(video_buffer);
1213                 video_buffer = 0;
1214         }
1215         if (audio_input_buffer) {
1216                 av_free(audio_input_buffer);
1217                 audio_input_buffer = 0;
1218         }
1219 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
1220         if (audio_output_buffer) {
1221                 av_free(audio_output_buffer);
1222                 audio_output_buffer = 0;
1223         }
1224 #endif
1225
1226         if (audio_deinterleave_buffer) {
1227                 av_free(audio_deinterleave_buffer);
1228                 audio_deinterleave_buffer = 0;
1229         }
1230
1231         if (img_convert_ctx) {
1232                 sws_freeContext(img_convert_ctx);
1233                 img_convert_ctx = 0;
1234         }
1235 }
1236
1237 void BKE_ffmpeg_end(void)
1238 {
1239         end_ffmpeg_impl(FALSE);
1240 }
1241
1242 /* properties */
1243
1244 void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1245 {
1246         struct IDProperty *prop = (struct IDProperty *) prop_;
1247         IDProperty *group;
1248         
1249         if (!rd->ffcodecdata.properties) {
1250                 return;
1251         }
1252
1253         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1254         if (group && prop) {
1255                 IDP_FreeFromGroup(group, prop);
1256         }
1257 }
1258
1259 IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
1260 {
1261         AVCodecContext c;
1262         const AVOption *o;
1263         const AVOption *parent;
1264         IDProperty *group;
1265         IDProperty *prop;
1266         IDPropertyTemplate val;
1267         int idp_type;
1268         char name[256];
1269         
1270         val.i = 0;
1271
1272         avcodec_get_context_defaults3(&c, NULL);
1273
1274         o = c.av_class->option + opt_index;
1275         parent = c.av_class->option + parent_index;
1276
1277         if (!rd->ffcodecdata.properties) {
1278                 rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1279         }
1280
1281         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1282         
1283         if (!group) {
1284                 group = IDP_New(IDP_GROUP, &val, type);
1285                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1286         }
1287
1288         if (parent_index) {
1289                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1290         }
1291         else {
1292                 BLI_strncpy(name, o->name, sizeof(name));
1293         }
1294
1295         PRINT("ffmpeg_property_add: %s %d %d %s\n", type, parent_index, opt_index, name);
1296
1297         prop = IDP_GetPropertyFromGroup(group, name);
1298         if (prop) {
1299                 return prop;
1300         }
1301
1302         switch (o->type) {
1303                 case AV_OPT_TYPE_INT:
1304                 case AV_OPT_TYPE_INT64:
1305                         val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1306                         idp_type = IDP_INT;
1307                         break;
1308                 case AV_OPT_TYPE_DOUBLE:
1309                 case AV_OPT_TYPE_FLOAT:
1310                         val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1311                         idp_type = IDP_FLOAT;
1312                         break;
1313                 case AV_OPT_TYPE_STRING:
1314                         val.string.str = (char *)"                                                                               ";
1315                         val.string.len = 80;
1316 /*              val.str = (char *)"                                                                               ";*/
1317                         idp_type = IDP_STRING;
1318                         break;
1319                 case AV_OPT_TYPE_CONST:
1320                         val.i = 1;
1321                         idp_type = IDP_INT;
1322                         break;
1323                 default:
1324                         return NULL;
1325         }
1326         prop = IDP_New(idp_type, &val, name);
1327         IDP_AddToGroup(group, prop);
1328         return prop;
1329 }
1330
1331 /* not all versions of ffmpeg include that, so here we go ... */
1332
1333 static const AVOption *my_av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
1334 {
1335         AVClass *c = *(AVClass **)v;
1336         const AVOption *o = c->option;
1337
1338         for (; o && o->name; o++) {
1339                 if (!strcmp(o->name, name) &&
1340                     (!unit || (o->unit && !strcmp(o->unit, unit))) &&
1341                     (o->flags & mask) == flags)
1342                 {
1343                         return o;
1344                 }
1345         }
1346         return NULL;
1347 }
1348
1349 int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *str)
1350 {
1351         AVCodecContext c;
1352         const AVOption *o = 0;
1353         const AVOption *p = 0;
1354         char name_[128];
1355         char *name;
1356         char *param;
1357         IDProperty *prop = NULL;
1358         
1359         avcodec_get_context_defaults3(&c, NULL);
1360
1361         strncpy(name_, str, sizeof(name_));
1362
1363         name = name_;
1364         while (*name == ' ') name++;
1365
1366         param = strchr(name, ':');
1367
1368         if (!param) {
1369                 param = strchr(name, ' ');
1370         }
1371         if (param) {
1372                 *param++ = 0;
1373                 while (*param == ' ') param++;
1374         }
1375         
1376         o = my_av_find_opt(&c, name, NULL, 0, 0);
1377         if (!o) {
1378                 return 0;
1379         }
1380         if (param && o->type == AV_OPT_TYPE_CONST) {
1381                 return 0;
1382         }
1383         if (param && o->type != AV_OPT_TYPE_CONST && o->unit) {
1384                 p = my_av_find_opt(&c, param, o->unit, 0, 0);
1385                 if (p) {
1386                         prop = BKE_ffmpeg_property_add(rd, (char *) type, p - c.av_class->option, o - c.av_class->option);
1387                 }
1388         }
1389         else {
1390                 prop = BKE_ffmpeg_property_add(rd, (char *) type, o - c.av_class->option, 0);
1391         }
1392                 
1393
1394         if (!prop) {
1395                 return 0;
1396         }
1397
1398         if (param && !p) {
1399                 switch (prop->type) {
1400                         case IDP_INT:
1401                                 IDP_Int(prop) = atoi(param);
1402                                 break;
1403                         case IDP_FLOAT:
1404                                 IDP_Float(prop) = atof(param);
1405                                 break;
1406                         case IDP_STRING:
1407                                 strncpy(IDP_String(prop), param, prop->len);
1408                                 break;
1409                 }
1410         }
1411         return 1;
1412 }
1413
1414 static void ffmpeg_set_expert_options(RenderData *rd)
1415 {
1416         int codec_id = rd->ffcodecdata.codec;
1417
1418         if (rd->ffcodecdata.properties)
1419                 IDP_FreeProperty(rd->ffcodecdata.properties);
1420
1421         if (codec_id == CODEC_ID_H264) {
1422                 /*
1423                  * All options here are for x264, but must be set via ffmpeg.
1424                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1425                  * to get a list.
1426                  */
1427
1428                 /*
1429                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1430                  * crashes Blender for some reason. Either way - this is no big deal.
1431                  */
1432                 BKE_ffmpeg_property_add_string(rd, "video", "coder:vlc");
1433
1434                 /*
1435                  * The other options were taken from the libx264-default.preset
1436                  * included in the ffmpeg distribution.
1437                  */
1438 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1439                 BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1440                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1441                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1442                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1443                 BKE_ffmpeg_property_add_string(rd, "video", "me:hex");
1444                 BKE_ffmpeg_property_add_string(rd, "video", "subq:6");
1445                 BKE_ffmpeg_property_add_string(rd, "video", "me_range:16");
1446                 BKE_ffmpeg_property_add_string(rd, "video", "qdiff:4");
1447                 BKE_ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1448                 BKE_ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1449                 BKE_ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1450                 BKE_ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1451                 BKE_ffmpeg_property_add_string(rd, "video", "bf:3");
1452                 BKE_ffmpeg_property_add_string(rd, "video", "refs:2");
1453                 BKE_ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1454                 BKE_ffmpeg_property_add_string(rd, "video", "directpred:3");
1455                 BKE_ffmpeg_property_add_string(rd, "video", "trellis:0");
1456                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1457                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1458                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1459                 BKE_ffmpeg_property_add_string(rd, "video", "wpredp:2");
1460
1461                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1462                         BKE_ffmpeg_property_add_string(rd, "video", "cqp:0");
1463         }
1464         else if (codec_id == CODEC_ID_DNXHD) {
1465                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1466                         BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd");
1467         }
1468 }
1469
1470 void BKE_ffmpeg_preset_set(RenderData *rd, int preset)
1471 {
1472         int isntsc = (rd->frs_sec != 25);
1473
1474         if (rd->ffcodecdata.properties)
1475                 IDP_FreeProperty(rd->ffcodecdata.properties);
1476
1477         switch (preset) {
1478                 case FFMPEG_PRESET_VCD:
1479                         rd->ffcodecdata.type = FFMPEG_MPEG1;
1480                         rd->ffcodecdata.video_bitrate = 1150;
1481                         rd->xsch = 352;
1482                         rd->ysch = isntsc ? 240 : 288;
1483                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1484                         rd->ffcodecdata.rc_max_rate = 1150;
1485                         rd->ffcodecdata.rc_min_rate = 1150;
1486                         rd->ffcodecdata.rc_buffer_size = 40 * 8;
1487                         rd->ffcodecdata.mux_packet_size = 2324;
1488                         rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1489                         break;
1490
1491                 case FFMPEG_PRESET_SVCD:
1492                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1493                         rd->ffcodecdata.video_bitrate = 2040;
1494                         rd->xsch = 480;
1495                         rd->ysch = isntsc ? 480 : 576;
1496                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1497                         rd->ffcodecdata.rc_max_rate = 2516;
1498                         rd->ffcodecdata.rc_min_rate = 0;
1499                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1500                         rd->ffcodecdata.mux_packet_size = 2324;
1501                         rd->ffcodecdata.mux_rate = 0;
1502                         break;
1503
1504                 case FFMPEG_PRESET_DVD:
1505                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1506                         rd->ffcodecdata.video_bitrate = 6000;
1507
1508                         /* Don't set resolution, see [#21351]
1509                          * rd->xsch = 720;
1510                          * rd->ysch = isntsc ? 480 : 576; */
1511
1512                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1513                         rd->ffcodecdata.rc_max_rate = 9000;
1514                         rd->ffcodecdata.rc_min_rate = 0;
1515                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1516                         rd->ffcodecdata.mux_packet_size = 2048;
1517                         rd->ffcodecdata.mux_rate = 10080000;
1518                         break;
1519
1520                 case FFMPEG_PRESET_DV:
1521                         rd->ffcodecdata.type = FFMPEG_DV;
1522                         rd->xsch = 720;
1523                         rd->ysch = isntsc ? 480 : 576;
1524                         break;
1525
1526                 case FFMPEG_PRESET_H264:
1527                         rd->ffcodecdata.type = FFMPEG_AVI;
1528                         rd->ffcodecdata.codec = CODEC_ID_H264;
1529                         rd->ffcodecdata.video_bitrate = 6000;
1530                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1531                         rd->ffcodecdata.rc_max_rate = 9000;
1532                         rd->ffcodecdata.rc_min_rate = 0;
1533                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1534                         rd->ffcodecdata.mux_packet_size = 2048;
1535                         rd->ffcodecdata.mux_rate = 10080000;
1536
1537                         break;
1538
1539                 case FFMPEG_PRESET_THEORA:
1540                 case FFMPEG_PRESET_XVID:
1541                         if (preset == FFMPEG_PRESET_XVID) {
1542                                 rd->ffcodecdata.type = FFMPEG_AVI;
1543                                 rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1544                         }
1545                         else if (preset == FFMPEG_PRESET_THEORA) {
1546                                 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1547                                 rd->ffcodecdata.codec = CODEC_ID_THEORA;
1548                         }
1549
1550                         rd->ffcodecdata.video_bitrate = 6000;
1551                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1552                         rd->ffcodecdata.rc_max_rate = 9000;
1553                         rd->ffcodecdata.rc_min_rate = 0;
1554                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1555                         rd->ffcodecdata.mux_packet_size = 2048;
1556                         rd->ffcodecdata.mux_rate = 10080000;
1557                         break;
1558
1559         }
1560
1561         ffmpeg_set_expert_options(rd);
1562 }
1563
1564 void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
1565 {
1566         int audio = 0;
1567
1568         if (imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1569                 if (rd->ffcodecdata.type <= 0 ||
1570                     rd->ffcodecdata.codec <= 0 ||
1571                     rd->ffcodecdata.audio_codec <= 0 ||
1572                     rd->ffcodecdata.video_bitrate <= 1)
1573                 {
1574                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1575
1576                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_DVD);
1577                 }
1578                 if (rd->ffcodecdata.type == FFMPEG_OGG) {
1579                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1580                 }
1581
1582                 audio = 1;
1583         }
1584         else if (imf->imtype == R_IMF_IMTYPE_H264) {
1585                 if (rd->ffcodecdata.codec != CODEC_ID_H264) {
1586                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
1587                         audio = 1;
1588                 }
1589         }
1590         else if (imf->imtype == R_IMF_IMTYPE_XVID) {
1591                 if (rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1592                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_XVID);
1593                         audio = 1;
1594                 }
1595         }
1596         else if (imf->imtype == R_IMF_IMTYPE_THEORA) {
1597                 if (rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1598                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_THEORA);
1599                         audio = 1;
1600                 }
1601         }
1602
1603         if (audio && rd->ffcodecdata.audio_codec < 0) {
1604                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1605                 rd->ffcodecdata.audio_bitrate = 128;
1606         }
1607 }
1608
1609 void BKE_ffmpeg_codec_settings_verify(RenderData *rd)
1610 {
1611         ffmpeg_set_expert_options(rd);
1612 }
1613
1614 int BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd)
1615 {
1616         int codec = rd->ffcodecdata.codec;
1617
1618         if (codec == CODEC_ID_QTRLE)
1619                 return TRUE;
1620
1621         if (codec == CODEC_ID_PNG)
1622                 return TRUE;
1623
1624 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1625         if (codec == CODEC_ID_FFV1)
1626                 return TRUE;
1627 #endif
1628
1629         return FALSE;
1630 }
1631
1632 #endif