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