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