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         ret = avcodec_encode_video2(c, &packet, frame, &got_output);
330
331         if (ret >= 0 && got_output) {
332                 if (packet.pts != AV_NOPTS_VALUE) {
333                         packet.pts = av_rescale_q(packet.pts, c->time_base, context->video_stream->time_base);
334                         PRINT("Video Frame PTS: %d\n", (int)packet.pts);
335                 }
336                 else {
337                         PRINT("Video Frame PTS: not set\n");
338                 }
339                 if (packet.dts != AV_NOPTS_VALUE) {
340                         packet.dts = av_rescale_q(packet.dts, c->time_base, context->video_stream->time_base);
341                         PRINT("Video Frame DTS: %d\n", (int)packet.dts);
342                 }
343                 else {
344                         PRINT("Video Frame DTS: not set\n");
345                 }
346
347                 packet.stream_index = context->video_stream->index;
348                 ret = av_interleaved_write_frame(context->outfile, &packet);
349                 success = (ret == 0);
350         }
351         else if (ret < 0) {
352                 success = 0;
353         }
354
355         if (!success)
356                 BKE_report(reports, RPT_ERROR, "Error writing frame");
357
358         return success;
359 }
360
361 /* read and encode a frame of audio from the buffer */
362 static AVFrame *generate_video_frame(FFMpegContext *context, uint8_t *pixels, ReportList *reports)
363 {
364         uint8_t *rendered_frame;
365
366         AVCodecContext *c = context->video_stream->codec;
367         int width = c->width;
368         int height = c->height;
369         AVFrame *rgb_frame;
370
371         if (c->pix_fmt != AV_PIX_FMT_BGR32) {
372                 rgb_frame = alloc_picture(AV_PIX_FMT_BGR32, width, height);
373                 if (!rgb_frame) {
374                         BKE_report(reports, RPT_ERROR, "Could not allocate temporary frame");
375                         return NULL;
376                 }
377         }
378         else {
379                 rgb_frame = context->current_frame;
380         }
381
382         rendered_frame = pixels;
383
384         /* Do RGBA-conversion and flipping in one step depending
385          * on CPU-Endianess */
386
387         if (ENDIAN_ORDER == L_ENDIAN) {
388                 int y;
389                 for (y = 0; y < height; y++) {
390                         uint8_t *target = rgb_frame->data[0] + width * 4 * (height - y - 1);
391                         uint8_t *src = rendered_frame + width * 4 * y;
392                         uint8_t *end = src + width * 4;
393                         while (src != end) {
394                                 target[3] = src[3];
395                                 target[2] = src[2];
396                                 target[1] = src[1];
397                                 target[0] = src[0];
398
399                                 target += 4;
400                                 src += 4;
401                         }
402                 }
403         }
404         else {
405                 int y;
406                 for (y = 0; y < height; y++) {
407                         uint8_t *target = rgb_frame->data[0] + width * 4 * (height - y - 1);
408                         uint8_t *src = rendered_frame + width * 4 * y;
409                         uint8_t *end = src + width * 4;
410                         while (src != end) {
411                                 target[3] = src[0];
412                                 target[2] = src[1];
413                                 target[1] = src[2];
414                                 target[0] = src[3];
415
416                                 target += 4;
417                                 src += 4;
418                         }
419                 }
420         }
421
422         if (c->pix_fmt != AV_PIX_FMT_BGR32) {
423                 sws_scale(context->img_convert_ctx, (const uint8_t *const *) rgb_frame->data,
424                           rgb_frame->linesize, 0, c->height,
425                           context->current_frame->data, context->current_frame->linesize);
426                 delete_picture(rgb_frame);
427         }
428
429         context->current_frame->format = AV_PIX_FMT_BGR32;
430         context->current_frame->width = width;
431         context->current_frame->height = height;
432
433         return context->current_frame;
434 }
435
436 static void set_ffmpeg_property_option(AVCodecContext *c, IDProperty *prop, AVDictionary **dictionary)
437 {
438         char name[128];
439         char *param;
440
441         PRINT("FFMPEG expert option: %s: ", prop->name);
442
443         BLI_strncpy(name, prop->name, sizeof(name));
444
445         param = strchr(name, ':');
446
447         if (param) {
448                 *param++ = '\0';
449         }
450
451         switch (prop->type) {
452                 case IDP_STRING:
453                         PRINT("%s.\n", IDP_String(prop));
454                         av_dict_set(dictionary, name, IDP_String(prop), 0);
455                         break;
456                 case IDP_FLOAT:
457                         PRINT("%g.\n", IDP_Float(prop));
458                         ffmpeg_dict_set_float(dictionary, prop->name, IDP_Float(prop));
459                         break;
460                 case IDP_INT:
461                         PRINT("%d.\n", IDP_Int(prop));
462
463                         if (param) {
464                                 if (IDP_Int(prop)) {
465                                         av_dict_set(dictionary, name, param, 0);
466                                 }
467                                 else {
468                                         return;
469                                 }
470                         }
471                         else {
472                                 ffmpeg_dict_set_int(dictionary, prop->name, IDP_Int(prop));
473                         }
474                         break;
475         }
476 }
477
478 static int ffmpeg_proprty_valid(AVCodecContext *c, const char *prop_name, IDProperty *curr)
479 {
480         int valid = 1;
481
482         if (STREQ(prop_name, "video")) {
483                 if (STREQ(curr->name, "bf")) {
484                         /* flash codec doesn't support b frames */
485                         valid &= c->codec_id != AV_CODEC_ID_FLV1;
486                 }
487         }
488
489         return valid;
490 }
491
492 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char *prop_name,
493                                   AVDictionary **dictionary)
494 {
495         IDProperty *prop;
496         IDProperty *curr;
497
498         /* TODO(sergey): This is actually rather stupid, because changing
499          * codec settings in render panel would also set expert options.
500          *
501          * But we need ti here in order to get rid of deprecated settings
502          * when opening old files in new blender.
503          *
504          * For as long we don't allow editing properties in the interface
505          * it's all good. bug if we allow editing them, we'll need to
506          * replace it with some smarter code which would port settings
507          * from deprecated to new one.
508          */
509         ffmpeg_set_expert_options(rd);
510
511         if (!rd->ffcodecdata.properties) {
512                 return;
513         }
514         
515         prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name);
516         if (!prop) {
517                 return;
518         }
519
520         for (curr = prop->data.group.first; curr; curr = curr->next) {
521                 if (ffmpeg_proprty_valid(c, prop_name, curr))
522                         set_ffmpeg_property_option(c, curr, dictionary);
523         }
524 }
525
526 /* prepare a video stream for the output file */
527
528 static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int codec_id, AVFormatContext *of,
529                                     int rectx, int recty, char *error, int error_size)
530 {
531         AVStream *st;
532         AVCodecContext *c;
533         AVCodec *codec;
534         AVDictionary *opts = NULL;
535
536         error[0] = '\0';
537
538         st = avformat_new_stream(of, NULL);
539         if (!st) return NULL;
540         st->id = 0;
541
542         /* Set up the codec context */
543         
544         c = st->codec;
545         c->codec_id = codec_id;
546         c->codec_type = AVMEDIA_TYPE_VIDEO;
547
548         /* Get some values from the current render settings */
549         
550         c->width = rectx;
551         c->height = recty;
552
553         /* FIXME: Really bad hack (tm) for NTSC support */
554         if (context->ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
555                 c->time_base.den = 2997;
556                 c->time_base.num = 100;
557         }
558         else if ((float) ((int) rd->frs_sec_base) == rd->frs_sec_base) {
559                 c->time_base.den = rd->frs_sec;
560                 c->time_base.num = (int) rd->frs_sec_base;
561         }
562         else {
563                 c->time_base.den = rd->frs_sec * 100000;
564                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
565         }
566         
567         c->gop_size = context->ffmpeg_gop_size;
568         c->max_b_frames = context->ffmpeg_max_b_frames;
569
570         if (context->ffmpeg_crf >= 0) {
571                 ffmpeg_dict_set_int(&opts, "crf", context->ffmpeg_crf);
572         }
573         else {
574                 c->bit_rate = context->ffmpeg_video_bitrate * 1000;
575                 c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
576                 c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
577                 c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
578         }
579
580         if (context->ffmpeg_preset) {
581                 /* 'preset' is used by h.264, 'deadline' is used by webm/vp9. I'm not
582                  * setting those properties conditionally based on the video codec,
583                  * as the FFmpeg encoder simply ignores unknown settings anyway. */
584                 char const *preset_name = NULL;  /* used by h.264 */
585                 char const *deadline_name = NULL; /* used by webm/vp9 */
586                 switch (context->ffmpeg_preset) {
587                         case FFM_PRESET_GOOD:
588                                 preset_name = "medium";
589                                 deadline_name = "good";
590                                 break;
591                         case FFM_PRESET_BEST:
592                                 preset_name = "slower";
593                                 deadline_name = "best";
594                                 break;
595                         case FFM_PRESET_REALTIME:
596                                 preset_name = "superfast";
597                                 deadline_name = "realtime";
598                                 break;
599                         default:
600                                 printf("Unknown preset number %i, ignoring.\n", context->ffmpeg_preset);
601                 }
602                 if (preset_name != NULL) {
603                         av_dict_set(&opts, "preset", preset_name, 0);
604                 }
605                 if (deadline_name != NULL) {
606                         av_dict_set(&opts, "deadline", deadline_name, 0);
607                 }
608         }
609
610 #if 0
611         /* this options are not set in ffmpeg.c and leads to artifacts with MPEG-4
612          * see #33586: Encoding to mpeg4 makes first frame(s) blocky
613          */
614         c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
615         c->rc_buffer_aggressivity = 1.0;
616 #endif
617
618         /* Deprecated and not doing anything since July 2015, deleted in recent ffmpeg */
619         //c->me_method = ME_EPZS;
620         
621         codec = avcodec_find_encoder(c->codec_id);
622         if (!codec)
623                 return NULL;
624         
625         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
626
627         if (codec->pix_fmts) {
628                 c->pix_fmt = codec->pix_fmts[0];
629         }
630         else {
631                 /* makes HuffYUV happy ... */
632                 c->pix_fmt = AV_PIX_FMT_YUV422P;
633         }
634
635         if (context->ffmpeg_type == FFMPEG_XVID) {
636                 /* arghhhh ... */
637                 c->pix_fmt = AV_PIX_FMT_YUV420P;
638                 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
639         }
640
641         if (codec_id == AV_CODEC_ID_H264) {
642                 /* correct wrong default ffmpeg param which crash x264 */
643                 c->qmin = 10;
644                 c->qmax = 51;
645         }
646         
647         /* Keep lossless encodes in the RGB domain. */
648         if (codec_id == AV_CODEC_ID_HUFFYUV) {
649                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
650                         c->pix_fmt = AV_PIX_FMT_BGRA;
651                 }
652                 else {
653                         c->pix_fmt = AV_PIX_FMT_RGB32;
654                 }
655         }
656
657         if (codec_id == AV_CODEC_ID_FFV1) {
658                 c->pix_fmt = AV_PIX_FMT_RGB32;
659         }
660
661         if (codec_id == AV_CODEC_ID_QTRLE) {
662                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
663                         c->pix_fmt = AV_PIX_FMT_ARGB;
664                 }
665         }
666
667         if (codec_id == AV_CODEC_ID_PNG) {
668                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
669                         c->pix_fmt = AV_PIX_FMT_RGBA;
670                 }
671         }
672
673         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
674 #if 0
675             || STREQ(of->oformat->name, "mp4")
676             || STREQ(of->oformat->name, "mov")
677             || STREQ(of->oformat->name, "3gp")
678 #endif
679             )
680         {
681                 PRINT("Using global header\n");
682                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
683         }
684         
685         /* xasp & yasp got float lately... */
686
687         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);
688         st->avg_frame_rate = av_inv_q(c->time_base);
689
690         set_ffmpeg_properties(rd, c, "video", &opts);
691
692         if (avcodec_open2(c, codec, &opts) < 0) {
693                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
694                 av_dict_free(&opts);
695                 return NULL;
696         }
697         av_dict_free(&opts);
698
699         context->current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
700
701         context->img_convert_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
702                                                   NULL, NULL, NULL);
703         return st;
704 }
705
706 static AVStream *alloc_audio_stream(FFMpegContext *context, RenderData *rd, int codec_id, AVFormatContext *of, char *error, int error_size)
707 {
708         AVStream *st;
709         AVCodecContext *c;
710         AVCodec *codec;
711         AVDictionary *opts = NULL;
712
713         error[0] = '\0';
714
715         st = avformat_new_stream(of, NULL);
716         if (!st) return NULL;
717         st->id = 1;
718
719         c = st->codec;
720         c->codec_id = codec_id;
721         c->codec_type = AVMEDIA_TYPE_AUDIO;
722
723         c->sample_rate = rd->ffcodecdata.audio_mixrate;
724         c->bit_rate = context->ffmpeg_audio_bitrate * 1000;
725         c->sample_fmt = AV_SAMPLE_FMT_S16;
726         c->channels = rd->ffcodecdata.audio_channels;
727
728         if (request_float_audio_buffer(codec_id)) {
729                 /* mainly for AAC codec which is experimental */
730                 c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
731                 c->sample_fmt = AV_SAMPLE_FMT_FLT;
732         }
733
734         codec = avcodec_find_encoder(c->codec_id);
735         if (!codec) {
736                 //XXX error("Couldn't find a valid audio codec");
737                 return NULL;
738         }
739
740         if (codec->sample_fmts) {
741                 /* check if the preferred sample format for this codec is supported.
742                  * this is because, depending on the version of libav, and with the whole ffmpeg/libav fork situation,
743                  * you have various implementations around. float samples in particular are not always supported.
744                  */
745                 const enum AVSampleFormat *p = codec->sample_fmts;
746                 for (; *p != -1; p++) {
747                         if (*p == st->codec->sample_fmt)
748                                 break;
749                 }
750                 if (*p == -1) {
751                         /* sample format incompatible with codec. Defaulting to a format known to work */
752                         st->codec->sample_fmt = codec->sample_fmts[0];
753                 }
754         }
755
756         if (codec->supported_samplerates) {
757                 const int *p = codec->supported_samplerates;
758                 int best = 0;
759                 int best_dist = INT_MAX;
760                 for (; *p; p++) {
761                         int dist = abs(st->codec->sample_rate - *p);
762                         if (dist < best_dist) {
763                                 best_dist = dist;
764                                 best = *p;
765                         }
766                 }
767                 /* best is the closest supported sample rate (same as selected if best_dist == 0) */
768                 st->codec->sample_rate = best;
769         }
770
771         if (of->oformat->flags & AVFMT_GLOBALHEADER) {
772                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
773         }
774
775         set_ffmpeg_properties(rd, c, "audio", &opts);
776
777         if (avcodec_open2(c, codec, &opts) < 0) {
778                 //XXX error("Couldn't initialize audio codec");
779                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
780                 av_dict_free(&opts);
781                 return NULL;
782         }
783         av_dict_free(&opts);
784
785         /* need to prevent floating point exception when using vorbis audio codec,
786          * initialize this value in the same way as it's done in FFmpeg itself (sergey) */
787         st->codec->time_base.num = 1;
788         st->codec->time_base.den = st->codec->sample_rate;
789
790 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
791         context->audio_outbuf_size = FF_MIN_BUFFER_SIZE;
792 #endif
793
794         if (c->frame_size == 0)
795                 // used to be if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
796                 // not sure if that is needed anymore, so let's try out if there are any
797                 // complaints regarding some ffmpeg versions users might have
798                 context->audio_input_samples = FF_MIN_BUFFER_SIZE * 8 / c->bits_per_coded_sample / c->channels;
799         else {
800                 context->audio_input_samples = c->frame_size;
801 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
802                 if (c->frame_size * c->channels * sizeof(int16_t) * 4 > context->audio_outbuf_size)
803                         context->audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
804 #endif
805         }
806
807         context->audio_deinterleave = av_sample_fmt_is_planar(c->sample_fmt);
808
809         context->audio_sample_size = av_get_bytes_per_sample(c->sample_fmt);
810
811         context->audio_input_buffer = (uint8_t *) av_malloc(context->audio_input_samples * c->channels * context->audio_sample_size);
812 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
813         context->audio_output_buffer = (uint8_t *) av_malloc(context->audio_outbuf_size);
814 #endif
815
816         if (context->audio_deinterleave)
817                 context->audio_deinterleave_buffer = (uint8_t *) av_malloc(context->audio_input_samples * c->channels * context->audio_sample_size);
818
819         context->audio_time = 0.0f;
820
821         return st;
822 }
823 /* essential functions -- start, append, end */
824
825 static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
826 {
827         char buffer[32];
828
829         BLI_snprintf(buffer, sizeof(buffer), "%d", value);
830
831         av_dict_set(dict, key, buffer, 0);
832 }
833
834 static void ffmpeg_dict_set_float(AVDictionary **dict, const char *key, float value)
835 {
836         char buffer[32];
837
838         BLI_snprintf(buffer, sizeof(buffer), "%.8f", value);
839
840         av_dict_set(dict, key, buffer, 0);
841 }
842
843 static void ffmpeg_add_metadata_callback(void *data, const char *propname, char *propvalue, int len)
844 {
845         AVDictionary **metadata = (AVDictionary **)data;
846         av_dict_set(metadata, propname, propvalue, 0);
847 }
848
849 static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int rectx, int recty, const char *suffix, ReportList *reports)
850 {
851         /* Handle to the output file */
852         AVFormatContext *of;
853         AVOutputFormat *fmt;
854         AVDictionary *opts = NULL;
855         char name[FILE_MAX], error[1024];
856         const char **exts;
857
858         context->ffmpeg_type = rd->ffcodecdata.type;
859         context->ffmpeg_codec = rd->ffcodecdata.codec;
860         context->ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
861         context->ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
862         context->ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
863         context->ffmpeg_gop_size = rd->ffcodecdata.gop_size;
864         context->ffmpeg_autosplit = rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT;
865         context->ffmpeg_crf = rd->ffcodecdata.constant_rate_factor;
866         context->ffmpeg_preset = rd->ffcodecdata.ffmpeg_preset;
867
868         if ((rd->ffcodecdata.flags & FFMPEG_USE_MAX_B_FRAMES) != 0) {
869                 context->ffmpeg_max_b_frames = rd->ffcodecdata.max_b_frames;
870         }
871
872         /* Determine the correct filename */
873         ffmpeg_filepath_get(context, name, rd, context->ffmpeg_preview, suffix);
874         PRINT("Starting output to %s(ffmpeg)...\n"
875                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
876                 "  video_bitrate=%d, audio_bitrate=%d,\n"
877                 "  gop_size=%d, autosplit=%d\n"
878                 "  render width=%d, render height=%d\n",
879                 name, context->ffmpeg_type, context->ffmpeg_codec, context->ffmpeg_audio_codec,
880                 context->ffmpeg_video_bitrate, context->ffmpeg_audio_bitrate,
881                 context->ffmpeg_gop_size, context->ffmpeg_autosplit, rectx, recty);
882         
883         exts = get_file_extensions(context->ffmpeg_type);
884         if (!exts) {
885                 BKE_report(reports, RPT_ERROR, "No valid formats found");
886                 return 0;
887         }
888         fmt = av_guess_format(NULL, exts[0], NULL);
889         if (!fmt) {
890                 BKE_report(reports, RPT_ERROR, "No valid formats found");
891                 return 0;
892         }
893
894         of = avformat_alloc_context();
895         if (!of) {
896                 BKE_report(reports, RPT_ERROR, "Error opening output file");
897                 return 0;
898         }
899
900
901         /* Returns after this must 'goto fail;' */
902
903         of->oformat = fmt;
904
905         /* Only bother with setting packet size & mux rate when CRF is not used. */
906         if (context->ffmpeg_crf == 0) {
907                 of->packet_size = rd->ffcodecdata.mux_packet_size;
908                 if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE) {
909                         ffmpeg_dict_set_int(&opts, "muxrate", rd->ffcodecdata.mux_rate);
910                 }
911                 else {
912                         av_dict_set(&opts, "muxrate", "0", 0);
913                 }
914         }
915
916         ffmpeg_dict_set_int(&opts, "preload", (int)(0.5 * AV_TIME_BASE));
917
918         of->max_delay = (int)(0.7 * AV_TIME_BASE);
919
920         fmt->audio_codec = context->ffmpeg_audio_codec;
921
922         BLI_strncpy(of->filename, name, sizeof(of->filename));
923         /* set the codec to the user's selection */
924         switch (context->ffmpeg_type) {
925                 case FFMPEG_AVI:
926                 case FFMPEG_MOV:
927                 case FFMPEG_MKV:
928                         fmt->video_codec = context->ffmpeg_codec;
929                         break;
930                 case FFMPEG_OGG:
931                         fmt->video_codec = AV_CODEC_ID_THEORA;
932                         break;
933                 case FFMPEG_DV:
934                         fmt->video_codec = AV_CODEC_ID_DVVIDEO;
935                         break;
936                 case FFMPEG_MPEG1:
937                         fmt->video_codec = AV_CODEC_ID_MPEG1VIDEO;
938                         break;
939                 case FFMPEG_MPEG2:
940                         fmt->video_codec = AV_CODEC_ID_MPEG2VIDEO;
941                         break;
942                 case FFMPEG_H264:
943                         fmt->video_codec = AV_CODEC_ID_H264;
944                         break;
945                 case FFMPEG_XVID:
946                         fmt->video_codec = AV_CODEC_ID_MPEG4;
947                         break;
948                 case FFMPEG_FLV:
949                         fmt->video_codec = AV_CODEC_ID_FLV1;
950                         break;
951                 case FFMPEG_MPEG4:
952                 default:
953                         fmt->video_codec = context->ffmpeg_codec;
954                         break;
955         }
956         if (fmt->video_codec == AV_CODEC_ID_DVVIDEO) {
957                 if (rectx != 720) {
958                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
959                         goto fail;
960                 }
961                 if (rd->frs_sec != 25 && recty != 480) {
962                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
963                         goto fail;
964                 }
965                 if (rd->frs_sec == 25 && recty != 576) {
966                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
967                         goto fail;
968                 }
969         }
970         
971         if (context->ffmpeg_type == FFMPEG_DV) {
972                 fmt->audio_codec = AV_CODEC_ID_PCM_S16LE;
973                 if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
974                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
975                         goto fail;
976                 }
977         }
978         
979         if (fmt->video_codec != AV_CODEC_ID_NONE) {
980                 context->video_stream = alloc_video_stream(context, rd, fmt->video_codec, of, rectx, recty, error, sizeof(error));
981                 PRINT("alloc video stream %p\n", context->video_stream);
982                 if (!context->video_stream) {
983                         if (error[0])
984                                 BKE_report(reports, RPT_ERROR, error);
985                         else
986                                 BKE_report(reports, RPT_ERROR, "Error initializing video stream");
987                         goto fail;
988                 }
989         }
990
991         if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE) {
992                 context->audio_stream = alloc_audio_stream(context, rd, fmt->audio_codec, of, error, sizeof(error));
993                 if (!context->audio_stream) {
994                         if (error[0])
995                                 BKE_report(reports, RPT_ERROR, error);
996                         else
997                                 BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
998                         goto fail;
999                 }
1000         }
1001         if (!(fmt->flags & AVFMT_NOFILE)) {
1002                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
1003                         BKE_report(reports, RPT_ERROR, "Could not open file for writing");
1004                         goto fail;
1005                 }
1006         }
1007
1008         if (context->stamp_data != NULL) {
1009                 BKE_stamp_info_callback(&of->metadata, context->stamp_data, ffmpeg_add_metadata_callback, false);
1010         }
1011
1012         if (avformat_write_header(of, NULL) < 0) {
1013                 BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
1014                 goto fail;
1015         }
1016
1017         context->outfile = of;
1018         av_dump_format(of, 0, name, 1);
1019         av_dict_free(&opts);
1020
1021         return 1;
1022
1023
1024 fail:
1025         if (of->pb) {
1026                 avio_close(of->pb);
1027         }
1028
1029         if (context->video_stream && context->video_stream->codec) {
1030                 avcodec_close(context->video_stream->codec);
1031                 context->video_stream = NULL;
1032         }
1033
1034         if (context->audio_stream && context->audio_stream->codec) {
1035                 avcodec_close(context->audio_stream->codec);
1036                 context->audio_stream = NULL;
1037         }
1038
1039         av_dict_free(&opts);
1040         avformat_free_context(of);
1041         return 0;
1042 }
1043
1044 /**
1045  * Writes any delayed frames in the encoder. This function is called before 
1046  * closing the encoder.
1047  *
1048  * <p>
1049  * Since an encoder may use both past and future frames to predict 
1050  * inter-frames (H.264 B-frames, for example), it can output the frames 
1051  * in a different order from the one it was given.
1052  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
1053  * them in the order 1, 4, 2, 3 - first the two frames used for prediction,
1054  * and then the bidirectionally-predicted frames. What this means in practice 
1055  * is that the encoder may not immediately produce one output frame for each 
1056  * input frame. These delayed frames must be flushed before we close the 
1057  * stream. We do this by calling avcodec_encode_video with NULL for the last 
1058  * parameter.
1059  * </p>
1060  */
1061 static void flush_ffmpeg(FFMpegContext *context)
1062 {
1063         int ret = 0;
1064         
1065         AVCodecContext *c = context->video_stream->codec;
1066         /* get the delayed frames */
1067         while (1) {
1068                 int got_output;
1069                 AVPacket packet = { 0 };
1070                 av_init_packet(&packet);
1071                 
1072                 ret = avcodec_encode_video2(c, &packet, NULL, &got_output);
1073                 if (ret < 0) {
1074                         fprintf(stderr, "Error encoding delayed frame %d\n", ret);
1075                         break;
1076                 }
1077                 if (!got_output) {
1078                         break;
1079                 }
1080                 if (packet.pts != AV_NOPTS_VALUE) {
1081                         packet.pts = av_rescale_q(packet.pts, c->time_base, context->video_stream->time_base);
1082                         PRINT("Video Frame PTS: %d\n", (int) packet.pts);
1083                 }
1084                 else {
1085                         PRINT("Video Frame PTS: not set\n");
1086                 }
1087                 if (packet.dts != AV_NOPTS_VALUE) {
1088                         packet.dts = av_rescale_q(packet.dts, c->time_base, context->video_stream->time_base);
1089                         PRINT("Video Frame DTS: %d\n", (int) packet.dts);
1090                 }
1091                 else {
1092                         PRINT("Video Frame DTS: not set\n");
1093                 }
1094
1095                 packet.stream_index = context->video_stream->index;
1096                 ret = av_interleaved_write_frame(context->outfile, &packet);
1097                 if (ret != 0) {
1098                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
1099                         break;
1100                 }
1101         }
1102         avcodec_flush_buffers(context->video_stream->codec);
1103 }
1104
1105 /* **********************************************************************
1106  * * public interface
1107  * ********************************************************************** */
1108
1109 /* Get the output filename-- similar to the other output formats */
1110 static void ffmpeg_filepath_get(FFMpegContext *context, char *string, RenderData *rd, bool preview, const char *suffix)
1111 {
1112         char autosplit[20];
1113
1114         const char **exts = get_file_extensions(rd->ffcodecdata.type);
1115         const char **fe = exts;
1116         int sfra, efra;
1117
1118         if (!string || !exts) return;
1119
1120         if (preview) {
1121                 sfra = rd->psfra;
1122                 efra = rd->pefra;
1123         }
1124         else {
1125                 sfra = rd->sfra;
1126                 efra = rd->efra;
1127         }
1128
1129         strcpy(string, rd->pic);
1130         BLI_path_abs(string, G.main->name);
1131
1132         BLI_make_existing_file(string);
1133
1134         autosplit[0] = '\0';
1135
1136         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
1137                 if (context) {
1138                         sprintf(autosplit, "_%03d", context->ffmpeg_autosplit_count);
1139                 }
1140         }
1141
1142         if (rd->scemode & R_EXTENSION) {
1143                 while (*fe) {
1144                         if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0) {
1145                                 break;
1146                         }
1147                         fe++;
1148                 }
1149
1150                 if (*fe == NULL) {
1151                         strcat(string, autosplit);
1152
1153                         BLI_path_frame_range(string, sfra, efra, 4);
1154                         strcat(string, *exts);
1155                 }
1156                 else {
1157                         *(string + strlen(string) - strlen(*fe)) = '\0';
1158                         strcat(string, autosplit);
1159                         strcat(string, *fe);
1160                 }
1161         }
1162         else {
1163                 if (BLI_path_frame_check_chars(string)) {
1164                         BLI_path_frame_range(string, sfra, efra, 4);
1165                 }
1166
1167                 strcat(string, autosplit);
1168         }
1169
1170         BLI_path_suffix(string, FILE_MAX, suffix, "");
1171 }
1172
1173 void BKE_ffmpeg_filepath_get(char *string, RenderData *rd, bool preview, const char *suffix)
1174 {
1175         ffmpeg_filepath_get(NULL, string, rd, preview, suffix);
1176 }
1177
1178 int BKE_ffmpeg_start(void *context_v, struct Scene *scene, RenderData *rd, int rectx, int recty,
1179                      ReportList *reports, bool preview, const char *suffix)
1180 {
1181         int success;
1182         FFMpegContext *context = context_v;
1183
1184         context->ffmpeg_autosplit_count = 0;
1185         context->ffmpeg_preview = preview;
1186         context->stamp_data = BKE_stamp_info_from_scene_static(scene);
1187
1188         success = start_ffmpeg_impl(context, rd, rectx, recty, suffix, reports);
1189 #ifdef WITH_AUDASPACE
1190         if (context->audio_stream) {
1191                 AVCodecContext *c = context->audio_stream->codec;
1192                 AUD_DeviceSpecs specs;
1193                 specs.channels = c->channels;
1194
1195                 switch (av_get_packed_sample_fmt(c->sample_fmt)) {
1196                         case AV_SAMPLE_FMT_U8:
1197                                 specs.format = AUD_FORMAT_U8;
1198                                 break;
1199                         case AV_SAMPLE_FMT_S16:
1200                                 specs.format = AUD_FORMAT_S16;
1201                                 break;
1202                         case AV_SAMPLE_FMT_S32:
1203                                 specs.format = AUD_FORMAT_S32;
1204                                 break;
1205                         case AV_SAMPLE_FMT_FLT:
1206                                 specs.format = AUD_FORMAT_FLOAT32;
1207                                 break;
1208                         case AV_SAMPLE_FMT_DBL:
1209                                 specs.format = AUD_FORMAT_FLOAT64;
1210                                 break;
1211                         default:
1212                                 return -31415;
1213                 }
1214
1215                 specs.rate = rd->ffcodecdata.audio_mixrate;
1216                 context->audio_mixdown_device = BKE_sound_mixdown(scene, specs, preview ? rd->psfra : rd->sfra, rd->ffcodecdata.audio_volume);
1217 #ifdef FFMPEG_CODEC_TIME_BASE
1218                 c->time_base.den = specs.rate;
1219                 c->time_base.num = 1;
1220 #endif
1221         }
1222 #endif
1223         return success;
1224 }
1225
1226 static void end_ffmpeg_impl(FFMpegContext *context, int is_autosplit);
1227
1228 #ifdef WITH_AUDASPACE
1229 static void write_audio_frames(FFMpegContext *context, double to_pts)
1230 {
1231         int finished = 0;
1232
1233         while (context->audio_stream && !finished) {
1234                 if ((context->audio_time >= to_pts) ||
1235                     (write_audio_frame(context)))
1236                 {
1237                         finished = 1;
1238                 }
1239         }
1240 }
1241 #endif
1242
1243 int BKE_ffmpeg_append(void *context_v, RenderData *rd, int start_frame, int frame, int *pixels,
1244                       int rectx, int recty, const char *suffix, ReportList *reports)
1245 {
1246         FFMpegContext *context = context_v;
1247         AVFrame *avframe;
1248         int success = 1;
1249
1250         PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);
1251
1252 /* why is this done before writing the video frame and again at end_ffmpeg? */
1253 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
1254
1255         if (context->video_stream) {
1256                 avframe = generate_video_frame(context, (unsigned char *) pixels, reports);
1257                 success = (avframe && write_video_frame(context, rd, frame - start_frame, avframe, reports));
1258
1259                 if (context->ffmpeg_autosplit) {
1260                         if (avio_tell(context->outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
1261                                 end_ffmpeg_impl(context, true);
1262                                 context->ffmpeg_autosplit_count++;
1263                                 success &= start_ffmpeg_impl(context, rd, rectx, recty, suffix, reports);
1264                         }
1265                 }
1266         }
1267
1268 #ifdef WITH_AUDASPACE
1269         write_audio_frames(context, (frame - start_frame) / (((double)rd->frs_sec) / (double)rd->frs_sec_base));
1270 #endif
1271         return success;
1272 }
1273
1274 static void end_ffmpeg_impl(FFMpegContext *context, int is_autosplit)
1275 {
1276         PRINT("Closing ffmpeg...\n");
1277
1278 #if 0
1279         if (context->audio_stream) { /* SEE UPPER */
1280                 write_audio_frames(context);
1281         }
1282 #endif
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 */