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