Orientation for 3D cursor
[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         c->me_method = ME_EPZS;
619         
620         codec = avcodec_find_encoder(c->codec_id);
621         if (!codec)
622                 return NULL;
623         
624         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
625
626         if (codec->pix_fmts) {
627                 c->pix_fmt = codec->pix_fmts[0];
628         }
629         else {
630                 /* makes HuffYUV happy ... */
631                 c->pix_fmt = AV_PIX_FMT_YUV422P;
632         }
633
634         if (context->ffmpeg_type == FFMPEG_XVID) {
635                 /* arghhhh ... */
636                 c->pix_fmt = AV_PIX_FMT_YUV420P;
637                 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
638         }
639
640         if (codec_id == AV_CODEC_ID_H264) {
641                 /* correct wrong default ffmpeg param which crash x264 */
642                 c->qmin = 10;
643                 c->qmax = 51;
644         }
645         
646         /* Keep lossless encodes in the RGB domain. */
647         if (codec_id == AV_CODEC_ID_HUFFYUV) {
648                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
649                         c->pix_fmt = AV_PIX_FMT_BGRA;
650                 }
651                 else {
652                         c->pix_fmt = AV_PIX_FMT_RGB32;
653                 }
654         }
655
656         if (codec_id == AV_CODEC_ID_FFV1) {
657                 c->pix_fmt = AV_PIX_FMT_RGB32;
658         }
659
660         if (codec_id == AV_CODEC_ID_QTRLE) {
661                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
662                         c->pix_fmt = AV_PIX_FMT_ARGB;
663                 }
664         }
665
666         if (codec_id == AV_CODEC_ID_PNG) {
667                 if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
668                         c->pix_fmt = AV_PIX_FMT_RGBA;
669                 }
670         }
671
672         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
673 #if 0
674             || STREQ(of->oformat->name, "mp4")
675             || STREQ(of->oformat->name, "mov")
676             || STREQ(of->oformat->name, "3gp")
677 #endif
678             )
679         {
680                 PRINT("Using global header\n");
681                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
682         }
683         
684         /* xasp & yasp got float lately... */
685
686         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);
687         st->avg_frame_rate = av_inv_q(c->time_base);
688
689         set_ffmpeg_properties(rd, c, "video", &opts);
690
691         if (avcodec_open2(c, codec, &opts) < 0) {
692                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
693                 av_dict_free(&opts);
694                 return NULL;
695         }
696         av_dict_free(&opts);
697
698         context->current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
699
700         context->img_convert_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
701                                                   NULL, NULL, NULL);
702         return st;
703 }
704
705 static AVStream *alloc_audio_stream(FFMpegContext *context, RenderData *rd, int codec_id, AVFormatContext *of, char *error, int error_size)
706 {
707         AVStream *st;
708         AVCodecContext *c;
709         AVCodec *codec;
710         AVDictionary *opts = NULL;
711
712         error[0] = '\0';
713
714         st = avformat_new_stream(of, NULL);
715         if (!st) return NULL;
716         st->id = 1;
717
718         c = st->codec;
719         c->codec_id = codec_id;
720         c->codec_type = AVMEDIA_TYPE_AUDIO;
721
722         c->sample_rate = rd->ffcodecdata.audio_mixrate;
723         c->bit_rate = context->ffmpeg_audio_bitrate * 1000;
724         c->sample_fmt = AV_SAMPLE_FMT_S16;
725         c->channels = rd->ffcodecdata.audio_channels;
726
727         if (request_float_audio_buffer(codec_id)) {
728                 /* mainly for AAC codec which is experimental */
729                 c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
730                 c->sample_fmt = AV_SAMPLE_FMT_FLT;
731         }
732
733         codec = avcodec_find_encoder(c->codec_id);
734         if (!codec) {
735                 //XXX error("Couldn't find a valid audio codec");
736                 return NULL;
737         }
738
739         if (codec->sample_fmts) {
740                 /* check if the preferred sample format for this codec is supported.
741                  * this is because, depending on the version of libav, and with the whole ffmpeg/libav fork situation,
742                  * you have various implementations around. float samples in particular are not always supported.
743                  */
744                 const enum AVSampleFormat *p = codec->sample_fmts;
745                 for (; *p != -1; p++) {
746                         if (*p == st->codec->sample_fmt)
747                                 break;
748                 }
749                 if (*p == -1) {
750                         /* sample format incompatible with codec. Defaulting to a format known to work */
751                         st->codec->sample_fmt = codec->sample_fmts[0];
752                 }
753         }
754
755         if (codec->supported_samplerates) {
756                 const int *p = codec->supported_samplerates;
757                 int best = 0;
758                 int best_dist = INT_MAX;
759                 for (; *p; p++) {
760                         int dist = abs(st->codec->sample_rate - *p);
761                         if (dist < best_dist) {
762                                 best_dist = dist;
763                                 best = *p;
764                         }
765                 }
766                 /* best is the closest supported sample rate (same as selected if best_dist == 0) */
767                 st->codec->sample_rate = best;
768         }
769
770         if (of->oformat->flags & AVFMT_GLOBALHEADER) {
771                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
772         }
773
774         set_ffmpeg_properties(rd, c, "audio", &opts);
775
776         if (avcodec_open2(c, codec, &opts) < 0) {
777                 //XXX error("Couldn't initialize audio codec");
778                 BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
779                 av_dict_free(&opts);
780                 return NULL;
781         }
782         av_dict_free(&opts);
783
784         /* need to prevent floating point exception when using vorbis audio codec,
785          * initialize this value in the same way as it's done in FFmpeg itself (sergey) */
786         st->codec->time_base.num = 1;
787         st->codec->time_base.den = st->codec->sample_rate;
788
789 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
790         context->audio_outbuf_size = FF_MIN_BUFFER_SIZE;
791 #endif
792
793         if (c->frame_size == 0)
794                 // used to be if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
795                 // not sure if that is needed anymore, so let's try out if there are any
796                 // complaints regarding some ffmpeg versions users might have
797                 context->audio_input_samples = FF_MIN_BUFFER_SIZE * 8 / c->bits_per_coded_sample / c->channels;
798         else {
799                 context->audio_input_samples = c->frame_size;
800 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
801                 if (c->frame_size * c->channels * sizeof(int16_t) * 4 > context->audio_outbuf_size)
802                         context->audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
803 #endif
804         }
805
806         context->audio_deinterleave = av_sample_fmt_is_planar(c->sample_fmt);
807
808         context->audio_sample_size = av_get_bytes_per_sample(c->sample_fmt);
809
810         context->audio_input_buffer = (uint8_t *) av_malloc(context->audio_input_samples * c->channels * context->audio_sample_size);
811 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
812         context->audio_output_buffer = (uint8_t *) av_malloc(context->audio_outbuf_size);
813 #endif
814
815         if (context->audio_deinterleave)
816                 context->audio_deinterleave_buffer = (uint8_t *) av_malloc(context->audio_input_samples * c->channels * context->audio_sample_size);
817
818         context->audio_time = 0.0f;
819
820         return st;
821 }
822 /* essential functions -- start, append, end */
823
824 static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
825 {
826         char buffer[32];
827
828         BLI_snprintf(buffer, sizeof(buffer), "%d", value);
829
830         av_dict_set(dict, key, buffer, 0);
831 }
832
833 static void ffmpeg_dict_set_float(AVDictionary **dict, const char *key, float value)
834 {
835         char buffer[32];
836
837         BLI_snprintf(buffer, sizeof(buffer), "%.8f", value);
838
839         av_dict_set(dict, key, buffer, 0);
840 }
841
842 static void ffmpeg_add_metadata_callback(void *data, const char *propname, char *propvalue, int len)
843 {
844         AVDictionary **metadata = (AVDictionary **)data;
845         av_dict_set(metadata, propname, propvalue, 0);
846 }
847
848 static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int rectx, int recty, const char *suffix, ReportList *reports)
849 {
850         /* Handle to the output file */
851         AVFormatContext *of;
852         AVOutputFormat *fmt;
853         AVDictionary *opts = NULL;
854         char name[FILE_MAX], error[1024];
855         const char **exts;
856
857         context->ffmpeg_type = rd->ffcodecdata.type;
858         context->ffmpeg_codec = rd->ffcodecdata.codec;
859         context->ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
860         context->ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
861         context->ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
862         context->ffmpeg_gop_size = rd->ffcodecdata.gop_size;
863         context->ffmpeg_autosplit = rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT;
864         context->ffmpeg_crf = rd->ffcodecdata.constant_rate_factor;
865         context->ffmpeg_preset = rd->ffcodecdata.ffmpeg_preset;
866
867         if ((rd->ffcodecdata.flags & FFMPEG_USE_MAX_B_FRAMES) != 0) {
868                 context->ffmpeg_max_b_frames = rd->ffcodecdata.max_b_frames;
869         }
870
871         /* Determine the correct filename */
872         ffmpeg_filepath_get(context, name, rd, context->ffmpeg_preview, suffix);
873         PRINT("Starting output to %s(ffmpeg)...\n"
874                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
875                 "  video_bitrate=%d, audio_bitrate=%d,\n"
876                 "  gop_size=%d, autosplit=%d\n"
877                 "  render width=%d, render height=%d\n",
878                 name, context->ffmpeg_type, context->ffmpeg_codec, context->ffmpeg_audio_codec,
879                 context->ffmpeg_video_bitrate, context->ffmpeg_audio_bitrate,
880                 context->ffmpeg_gop_size, context->ffmpeg_autosplit, rectx, recty);
881         
882         exts = get_file_extensions(context->ffmpeg_type);
883         if (!exts) {
884                 BKE_report(reports, RPT_ERROR, "No valid formats found");
885                 return 0;
886         }
887         fmt = av_guess_format(NULL, exts[0], NULL);
888         if (!fmt) {
889                 BKE_report(reports, RPT_ERROR, "No valid formats found");
890                 return 0;
891         }
892
893         of = avformat_alloc_context();
894         if (!of) {
895                 BKE_report(reports, RPT_ERROR, "Error opening output file");
896                 return 0;
897         }
898
899
900         /* Returns after this must 'goto fail;' */
901
902         of->oformat = fmt;
903
904         /* Only bother with setting packet size & mux rate when CRF is not used. */
905         if (context->ffmpeg_crf == 0) {
906                 of->packet_size = rd->ffcodecdata.mux_packet_size;
907                 if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE) {
908                         ffmpeg_dict_set_int(&opts, "muxrate", rd->ffcodecdata.mux_rate);
909                 }
910                 else {
911                         av_dict_set(&opts, "muxrate", "0", 0);
912                 }
913         }
914
915         ffmpeg_dict_set_int(&opts, "preload", (int)(0.5 * AV_TIME_BASE));
916
917         of->max_delay = (int)(0.7 * AV_TIME_BASE);
918
919         fmt->audio_codec = context->ffmpeg_audio_codec;
920
921         BLI_strncpy(of->filename, name, sizeof(of->filename));
922         /* set the codec to the user's selection */
923         switch (context->ffmpeg_type) {
924                 case FFMPEG_AVI:
925                 case FFMPEG_MOV:
926                 case FFMPEG_MKV:
927                         fmt->video_codec = context->ffmpeg_codec;
928                         break;
929                 case FFMPEG_OGG:
930                         fmt->video_codec = AV_CODEC_ID_THEORA;
931                         break;
932                 case FFMPEG_DV:
933                         fmt->video_codec = AV_CODEC_ID_DVVIDEO;
934                         break;
935                 case FFMPEG_MPEG1:
936                         fmt->video_codec = AV_CODEC_ID_MPEG1VIDEO;
937                         break;
938                 case FFMPEG_MPEG2:
939                         fmt->video_codec = AV_CODEC_ID_MPEG2VIDEO;
940                         break;
941                 case FFMPEG_H264:
942                         fmt->video_codec = AV_CODEC_ID_H264;
943                         break;
944                 case FFMPEG_XVID:
945                         fmt->video_codec = AV_CODEC_ID_MPEG4;
946                         break;
947                 case FFMPEG_FLV:
948                         fmt->video_codec = AV_CODEC_ID_FLV1;
949                         break;
950                 case FFMPEG_MPEG4:
951                 default:
952                         fmt->video_codec = context->ffmpeg_codec;
953                         break;
954         }
955         if (fmt->video_codec == AV_CODEC_ID_DVVIDEO) {
956                 if (rectx != 720) {
957                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
958                         goto fail;
959                 }
960                 if (rd->frs_sec != 25 && recty != 480) {
961                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
962                         goto fail;
963                 }
964                 if (rd->frs_sec == 25 && recty != 576) {
965                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
966                         goto fail;
967                 }
968         }
969         
970         if (context->ffmpeg_type == FFMPEG_DV) {
971                 fmt->audio_codec = AV_CODEC_ID_PCM_S16LE;
972                 if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
973                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
974                         goto fail;
975                 }
976         }
977         
978         if (fmt->video_codec != AV_CODEC_ID_NONE) {
979                 context->video_stream = alloc_video_stream(context, rd, fmt->video_codec, of, rectx, recty, error, sizeof(error));
980                 PRINT("alloc video stream %p\n", context->video_stream);
981                 if (!context->video_stream) {
982                         if (error[0])
983                                 BKE_report(reports, RPT_ERROR, error);
984                         else
985                                 BKE_report(reports, RPT_ERROR, "Error initializing video stream");
986                         goto fail;
987                 }
988         }
989
990         if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE) {
991                 context->audio_stream = alloc_audio_stream(context, rd, fmt->audio_codec, of, error, sizeof(error));
992                 if (!context->audio_stream) {
993                         if (error[0])
994                                 BKE_report(reports, RPT_ERROR, error);
995                         else
996                                 BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
997                         goto fail;
998                 }
999         }
1000         if (!(fmt->flags & AVFMT_NOFILE)) {
1001                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
1002                         BKE_report(reports, RPT_ERROR, "Could not open file for writing");
1003                         goto fail;
1004                 }
1005         }
1006
1007         if (context->stamp_data != NULL) {
1008                 BKE_stamp_info_callback(&of->metadata, context->stamp_data, ffmpeg_add_metadata_callback, false);
1009         }
1010
1011         if (avformat_write_header(of, NULL) < 0) {
1012                 BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
1013                 goto fail;
1014         }
1015
1016         context->outfile = of;
1017         av_dump_format(of, 0, name, 1);
1018         av_dict_free(&opts);
1019
1020         return 1;
1021
1022
1023 fail:
1024         if (of->pb) {
1025                 avio_close(of->pb);
1026         }
1027
1028         if (context->video_stream && context->video_stream->codec) {
1029                 avcodec_close(context->video_stream->codec);
1030                 context->video_stream = NULL;
1031         }
1032
1033         if (context->audio_stream && context->audio_stream->codec) {
1034                 avcodec_close(context->audio_stream->codec);
1035                 context->audio_stream = NULL;
1036         }
1037
1038         av_dict_free(&opts);
1039         avformat_free_context(of);
1040         return 0;
1041 }
1042
1043 /**
1044  * Writes any delayed frames in the encoder. This function is called before 
1045  * closing the encoder.
1046  *
1047  * <p>
1048  * Since an encoder may use both past and future frames to predict 
1049  * inter-frames (H.264 B-frames, for example), it can output the frames 
1050  * in a different order from the one it was given.
1051  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
1052  * them in the order 1, 4, 2, 3 - first the two frames used for prediction,
1053  * and then the bidirectionally-predicted frames. What this means in practice 
1054  * is that the encoder may not immediately produce one output frame for each 
1055  * input frame. These delayed frames must be flushed before we close the 
1056  * stream. We do this by calling avcodec_encode_video with NULL for the last 
1057  * parameter.
1058  * </p>
1059  */
1060 static void flush_ffmpeg(FFMpegContext *context)
1061 {
1062         int ret = 0;
1063         
1064         AVCodecContext *c = context->video_stream->codec;
1065         /* get the delayed frames */
1066         while (1) {
1067                 int got_output;
1068                 AVPacket packet = { 0 };
1069                 av_init_packet(&packet);
1070                 
1071                 ret = avcodec_encode_video2(c, &packet, NULL, &got_output);
1072                 if (ret < 0) {
1073                         fprintf(stderr, "Error encoding delayed frame %d\n", ret);
1074                         break;
1075                 }
1076                 if (!got_output) {
1077                         break;
1078                 }
1079                 if (packet.pts != AV_NOPTS_VALUE) {
1080                         packet.pts = av_rescale_q(packet.pts, c->time_base, context->video_stream->time_base);
1081                         PRINT("Video Frame PTS: %d\n", (int) packet.pts);
1082                 }
1083                 else {
1084                         PRINT("Video Frame PTS: not set\n");
1085                 }
1086                 if (packet.dts != AV_NOPTS_VALUE) {
1087                         packet.dts = av_rescale_q(packet.dts, c->time_base, context->video_stream->time_base);
1088                         PRINT("Video Frame DTS: %d\n", (int) packet.dts);
1089                 }
1090                 else {
1091                         PRINT("Video Frame DTS: not set\n");
1092                 }
1093
1094                 packet.stream_index = context->video_stream->index;
1095                 ret = av_interleaved_write_frame(context->outfile, &packet);
1096                 if (ret != 0) {
1097                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
1098                         break;
1099                 }
1100         }
1101         avcodec_flush_buffers(context->video_stream->codec);
1102 }
1103
1104 /* **********************************************************************
1105  * * public interface
1106  * ********************************************************************** */
1107
1108 /* Get the output filename-- similar to the other output formats */
1109 static void ffmpeg_filepath_get(FFMpegContext *context, char *string, RenderData *rd, bool preview, const char *suffix)
1110 {
1111         char autosplit[20];
1112
1113         const char **exts = get_file_extensions(rd->ffcodecdata.type);
1114         const char **fe = exts;
1115         int sfra, efra;
1116
1117         if (!string || !exts) return;
1118
1119         if (preview) {
1120                 sfra = rd->psfra;
1121                 efra = rd->pefra;
1122         }
1123         else {
1124                 sfra = rd->sfra;
1125                 efra = rd->efra;
1126         }
1127
1128         strcpy(string, rd->pic);
1129         BLI_path_abs(string, G.main->name);
1130
1131         BLI_make_existing_file(string);
1132
1133         autosplit[0] = '\0';
1134
1135         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
1136                 if (context) {
1137                         sprintf(autosplit, "_%03d", context->ffmpeg_autosplit_count);
1138                 }
1139         }
1140
1141         if (rd->scemode & R_EXTENSION) {
1142                 while (*fe) {
1143                         if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0) {
1144                                 break;
1145                         }
1146                         fe++;
1147                 }
1148
1149                 if (*fe == NULL) {
1150                         strcat(string, autosplit);
1151
1152                         BLI_path_frame_range(string, sfra, efra, 4);
1153                         strcat(string, *exts);
1154                 }
1155                 else {
1156                         *(string + strlen(string) - strlen(*fe)) = '\0';
1157                         strcat(string, autosplit);
1158                         strcat(string, *fe);
1159                 }
1160         }
1161         else {
1162                 if (BLI_path_frame_check_chars(string)) {
1163                         BLI_path_frame_range(string, sfra, efra, 4);
1164                 }
1165
1166                 strcat(string, autosplit);
1167         }
1168
1169         BLI_path_suffix(string, FILE_MAX, suffix, "");
1170 }
1171
1172 void BKE_ffmpeg_filepath_get(char *string, RenderData *rd, bool preview, const char *suffix)
1173 {
1174         ffmpeg_filepath_get(NULL, string, rd, preview, suffix);
1175 }
1176
1177 int BKE_ffmpeg_start(void *context_v, struct Scene *scene, RenderData *rd, int rectx, int recty,
1178                      ReportList *reports, bool preview, const char *suffix)
1179 {
1180         int success;
1181         FFMpegContext *context = context_v;
1182
1183         context->ffmpeg_autosplit_count = 0;
1184         context->ffmpeg_preview = preview;
1185         context->stamp_data = BKE_stamp_info_from_scene_static(scene);
1186
1187         success = start_ffmpeg_impl(context, rd, rectx, recty, suffix, reports);
1188 #ifdef WITH_AUDASPACE
1189         if (context->audio_stream) {
1190                 AVCodecContext *c = context->audio_stream->codec;
1191                 AUD_DeviceSpecs specs;
1192                 specs.channels = c->channels;
1193
1194                 switch (av_get_packed_sample_fmt(c->sample_fmt)) {
1195                         case AV_SAMPLE_FMT_U8:
1196                                 specs.format = AUD_FORMAT_U8;
1197                                 break;
1198                         case AV_SAMPLE_FMT_S16:
1199                                 specs.format = AUD_FORMAT_S16;
1200                                 break;
1201                         case AV_SAMPLE_FMT_S32:
1202                                 specs.format = AUD_FORMAT_S32;
1203                                 break;
1204                         case AV_SAMPLE_FMT_FLT:
1205                                 specs.format = AUD_FORMAT_FLOAT32;
1206                                 break;
1207                         case AV_SAMPLE_FMT_DBL:
1208                                 specs.format = AUD_FORMAT_FLOAT64;
1209                                 break;
1210                         default:
1211                                 return -31415;
1212                 }
1213
1214                 specs.rate = rd->ffcodecdata.audio_mixrate;
1215                 context->audio_mixdown_device = BKE_sound_mixdown(scene, specs, preview ? rd->psfra : rd->sfra, rd->ffcodecdata.audio_volume);
1216 #ifdef FFMPEG_CODEC_TIME_BASE
1217                 c->time_base.den = specs.rate;
1218                 c->time_base.num = 1;
1219 #endif
1220         }
1221 #endif
1222         return success;
1223 }
1224
1225 static void end_ffmpeg_impl(FFMpegContext *context, int is_autosplit);
1226
1227 #ifdef WITH_AUDASPACE
1228 static void write_audio_frames(FFMpegContext *context, double to_pts)
1229 {
1230         int finished = 0;
1231
1232         while (context->audio_stream && !finished) {
1233                 if ((context->audio_time >= to_pts) ||
1234                     (write_audio_frame(context)))
1235                 {
1236                         finished = 1;
1237                 }
1238         }
1239 }
1240 #endif
1241
1242 int BKE_ffmpeg_append(void *context_v, RenderData *rd, int start_frame, int frame, int *pixels,
1243                       int rectx, int recty, const char *suffix, ReportList *reports)
1244 {
1245         FFMpegContext *context = context_v;
1246         AVFrame *avframe;
1247         int success = 1;
1248
1249         PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);
1250
1251 /* why is this done before writing the video frame and again at end_ffmpeg? */
1252 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
1253
1254         if (context->video_stream) {
1255                 avframe = generate_video_frame(context, (unsigned char *) pixels, reports);
1256                 success = (avframe && write_video_frame(context, rd, frame - start_frame, avframe, reports));
1257
1258                 if (context->ffmpeg_autosplit) {
1259                         if (avio_tell(context->outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
1260                                 end_ffmpeg_impl(context, true);
1261                                 context->ffmpeg_autosplit_count++;
1262                                 success &= start_ffmpeg_impl(context, rd, rectx, recty, suffix, reports);
1263                         }
1264                 }
1265         }
1266
1267 #ifdef WITH_AUDASPACE
1268         write_audio_frames(context, (frame - start_frame) / (((double)rd->frs_sec) / (double)rd->frs_sec_base));
1269 #endif
1270         return success;
1271 }
1272
1273 static void end_ffmpeg_impl(FFMpegContext *context, int is_autosplit)
1274 {
1275         PRINT("Closing ffmpeg...\n");
1276
1277 #if 0
1278         if (context->audio_stream) { /* SEE UPPER */
1279                 write_audio_frames(context);
1280         }
1281 #endif
1282
1283 #ifdef WITH_AUDASPACE
1284         if (is_autosplit == false) {
1285                 if (context->audio_mixdown_device) {
1286                         AUD_Device_free(context->audio_mixdown_device);
1287                         context->audio_mixdown_device = NULL;
1288                 }
1289         }
1290 #endif
1291
1292         if (context->video_stream && context->video_stream->codec) {
1293                 PRINT("Flushing delayed frames...\n");
1294                 flush_ffmpeg(context);
1295         }
1296         
1297         if (context->outfile) {
1298                 av_write_trailer(context->outfile);
1299         }
1300         
1301         /* Close the video codec */
1302
1303         if (context->video_stream != NULL && context->video_stream->codec != NULL) {
1304                 avcodec_close(context->video_stream->codec);
1305                 PRINT("zero video stream %p\n", context->video_stream);
1306                 context->video_stream = NULL;
1307         }
1308
1309         if (context->audio_stream != NULL && context->audio_stream->codec != NULL) {
1310                 avcodec_close(context->audio_stream->codec);
1311                 context->audio_stream = NULL;
1312         }
1313
1314         /* free the temp buffer */
1315         if (context->current_frame != NULL) {
1316                 delete_picture(context->current_frame);
1317                 context->current_frame = NULL;
1318         }
1319         if (context->outfile != NULL && context->outfile->oformat) {
1320                 if (!(context->outfile->oformat->flags & AVFMT_NOFILE)) {
1321                         avio_close(context->outfile->pb);
1322                 }
1323         }
1324         if (context->outfile != NULL) {
1325                 avformat_free_context(context->outfile);
1326                 context->outfile = NULL;
1327         }
1328         if (context->audio_input_buffer != NULL) {
1329                 av_free(context->audio_input_buffer);
1330                 context->audio_input_buffer = NULL;
1331         }
1332 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
1333         if (context->audio_output_buffer != NULL) {
1334                 av_free(context->audio_output_buffer);
1335                 context->audio_output_buffer = NULL;
1336         }
1337 #endif
1338
1339         if (context->audio_deinterleave_buffer != NULL) {
1340                 av_free(context->audio_deinterleave_buffer);
1341                 context->audio_deinterleave_buffer = NULL;
1342         }
1343
1344         if (context->img_convert_ctx != NULL) {
1345                 sws_freeContext(context->img_convert_ctx);
1346                 context->img_convert_ctx = NULL;
1347         }
1348 }
1349
1350 void BKE_ffmpeg_end(void *context_v)
1351 {
1352         FFMpegContext *context = context_v;
1353         end_ffmpeg_impl(context, false);
1354 }
1355
1356 /* properties */
1357
1358 void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1359 {
1360         struct IDProperty *prop = (struct IDProperty *) prop_;
1361         IDProperty *group;
1362         
1363         if (!rd->ffcodecdata.properties) {
1364                 return;
1365         }
1366
1367         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1368         if (group && prop) {
1369                 IDP_FreeFromGroup(group, prop);
1370         }
1371 }
1372
1373 static IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, const AVOption *o, const AVOption *parent)
1374 {
1375         AVCodecContext c;
1376         IDProperty *group;
1377         IDProperty *prop;
1378         IDPropertyTemplate val;
1379         int idp_type;
1380         char name[256];
1381         
1382         val.i = 0;
1383
1384         avcodec_get_context_defaults3(&c, NULL);
1385
1386         if (!rd->ffcodecdata.properties) {
1387                 rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
1388         }
1389
1390         group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
1391         
1392         if (!group) {
1393                 group = IDP_New(IDP_GROUP, &val, type);
1394                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1395         }
1396
1397         if (parent) {
1398                 BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
1399         }
1400         else {
1401                 BLI_strncpy(name, o->name, sizeof(name));
1402         }
1403
1404         PRINT("ffmpeg_property_add: %s %s\n", type, name);
1405
1406         prop = IDP_GetPropertyFromGroup(group, name);
1407         if (prop) {
1408                 return prop;
1409         }
1410
1411         switch (o->type) {
1412                 case AV_OPT_TYPE_INT:
1413                 case AV_OPT_TYPE_INT64:
1414                         val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1415                         idp_type = IDP_INT;
1416                         break;
1417                 case AV_OPT_TYPE_DOUBLE:
1418                 case AV_OPT_TYPE_FLOAT:
1419                         val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1420                         idp_type = IDP_FLOAT;
1421                         break;
1422                 case AV_OPT_TYPE_STRING:
1423                         val.string.str = (char *)"                                                                               ";
1424                         val.string.len = 80;
1425 /*              val.str = (char *)"                                                                               ";*/
1426                         idp_type = IDP_STRING;
1427                         break;
1428                 case AV_OPT_TYPE_CONST:
1429                         val.i = 1;
1430                         idp_type = IDP_INT;
1431                         break;
1432                 default:
1433                         return NULL;
1434         }
1435         prop = IDP_New(idp_type, &val, name);
1436         IDP_AddToGroup(group, prop);
1437         return prop;
1438 }
1439
1440 /* not all versions of ffmpeg include that, so here we go ... */
1441
1442 int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *str)
1443 {
1444         AVCodecContext c;
1445         const AVOption *o = NULL;
1446         const AVOption *p = NULL;
1447         char name_[128];
1448         char *name;
1449         char *param;
1450         IDProperty *prop = NULL;
1451         
1452         avcodec_get_context_defaults3(&c, NULL);
1453
1454         BLI_strncpy(name_, str, sizeof(name_));
1455
1456         name = name_;
1457         while (*name == ' ') name++;
1458
1459         param = strchr(name, ':');
1460
1461         if (!param) {
1462                 param = strchr(name, ' ');
1463         }
1464         if (param) {
1465                 *param++ = '\0';
1466                 while (*param == ' ') param++;
1467         }
1468         
1469         o = av_opt_find(&c, name, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
1470         if (!o) {
1471                 PRINT("Ignoring unknown expert option %s\n", str);
1472                 return 0;
1473         }
1474         if (param && o->type == AV_OPT_TYPE_CONST) {
1475                 return 0;
1476         }
1477         if (param && o->type != AV_OPT_TYPE_CONST && o->unit) {
1478                 p = av_opt_find(&c, param, o->unit, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
1479                 if (p) {
1480                         prop = BKE_ffmpeg_property_add(rd, (char *) type, p, o);
1481                 }
1482                 else {
1483                         PRINT("Ignoring unknown expert option %s\n", str);
1484                 }
1485         }
1486         else {
1487                 prop = BKE_ffmpeg_property_add(rd, (char *) type, o, NULL);
1488         }
1489                 
1490
1491         if (!prop) {
1492                 return 0;
1493         }
1494
1495         if (param && !p) {
1496                 switch (prop->type) {
1497                         case IDP_INT:
1498                                 IDP_Int(prop) = atoi(param);
1499                                 break;
1500                         case IDP_FLOAT:
1501                                 IDP_Float(prop) = atof(param);
1502                                 break;
1503                         case IDP_STRING:
1504                                 strncpy(IDP_String(prop), param, prop->len);
1505                                 break;
1506                 }
1507         }
1508         return 1;
1509 }
1510
1511 static void ffmpeg_set_expert_options(RenderData *rd)
1512 {
1513         int codec_id = rd->ffcodecdata.codec;
1514
1515         if (rd->ffcodecdata.properties)
1516                 IDP_FreeProperty(rd->ffcodecdata.properties);
1517
1518         if (codec_id == AV_CODEC_ID_H264) {
1519                 /*
1520                  * All options here are for x264, but must be set via ffmpeg.
1521                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1522                  * to get a list.
1523                  */
1524
1525                 /*
1526                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1527                  * crashes Blender for some reason. Either way - this is no big deal.
1528                  */
1529                 BKE_ffmpeg_property_add_string(rd, "video", "coder:vlc");
1530
1531                 /*
1532                  * The other options were taken from the libx264-default.preset
1533                  * included in the ffmpeg distribution.
1534                  */
1535 //              ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
1536                 BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1537                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");  // Deprecated.
1538                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");  // Deprecated.
1539                 BKE_ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");  // Deprecated.
1540                 BKE_ffmpeg_property_add_string(rd, "video", "me:hex");
1541                 BKE_ffmpeg_property_add_string(rd, "video", "subq:6");
1542                 BKE_ffmpeg_property_add_string(rd, "video", "me_range:16");
1543                 BKE_ffmpeg_property_add_string(rd, "video", "qdiff:4");
1544                 BKE_ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1545                 BKE_ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1546                 BKE_ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1547                 BKE_ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1548                 BKE_ffmpeg_property_add_string(rd, "video", "bf:3");
1549                 BKE_ffmpeg_property_add_string(rd, "video", "refs:2");
1550                 BKE_ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1551
1552                 BKE_ffmpeg_property_add_string(rd, "video", "trellis:0");
1553                 BKE_ffmpeg_property_add_string(rd, "video", "weightb:1");
1554 #ifdef FFMPEG_HAVE_DEPRECATED_FLAGS2
1555                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1556                 BKE_ffmpeg_property_add_string(rd, "video", "directpred:3");
1557                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1558                 BKE_ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1559 #else
1560                 BKE_ffmpeg_property_add_string(rd, "video", "8x8dct:1");
1561                 BKE_ffmpeg_property_add_string(rd, "video", "fast-pskip:1");
1562                 BKE_ffmpeg_property_add_string(rd, "video", "wpredp:2");
1563 #endif
1564         }
1565         else if (codec_id == AV_CODEC_ID_DNXHD) {
1566                 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
1567                         BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd");
1568         }
1569 }
1570
1571 void BKE_ffmpeg_preset_set(RenderData *rd, int preset)
1572 {
1573         int isntsc = (rd->frs_sec != 25);
1574
1575         if (rd->ffcodecdata.properties)
1576                 IDP_FreeProperty(rd->ffcodecdata.properties);
1577
1578         switch (preset) {
1579                 case FFMPEG_PRESET_VCD:
1580                         rd->ffcodecdata.type = FFMPEG_MPEG1;
1581                         rd->ffcodecdata.video_bitrate = 1150;
1582                         rd->xsch = 352;
1583                         rd->ysch = isntsc ? 240 : 288;
1584                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1585                         rd->ffcodecdata.rc_max_rate = 1150;
1586                         rd->ffcodecdata.rc_min_rate = 1150;
1587                         rd->ffcodecdata.rc_buffer_size = 40 * 8;
1588                         rd->ffcodecdata.mux_packet_size = 2324;
1589                         rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1590                         break;
1591
1592                 case FFMPEG_PRESET_SVCD:
1593                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1594                         rd->ffcodecdata.video_bitrate = 2040;
1595                         rd->xsch = 480;
1596                         rd->ysch = isntsc ? 480 : 576;
1597                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1598                         rd->ffcodecdata.rc_max_rate = 2516;
1599                         rd->ffcodecdata.rc_min_rate = 0;
1600                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1601                         rd->ffcodecdata.mux_packet_size = 2324;
1602                         rd->ffcodecdata.mux_rate = 0;
1603                         break;
1604
1605                 case FFMPEG_PRESET_DVD:
1606                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1607                         rd->ffcodecdata.video_bitrate = 6000;
1608
1609                         /* Don't set resolution, see [#21351]
1610                          * rd->xsch = 720;
1611                          * rd->ysch = isntsc ? 480 : 576; */
1612
1613                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1614                         rd->ffcodecdata.rc_max_rate = 9000;
1615                         rd->ffcodecdata.rc_min_rate = 0;
1616                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1617                         rd->ffcodecdata.mux_packet_size = 2048;
1618                         rd->ffcodecdata.mux_rate = 10080000;
1619                         break;
1620
1621                 case FFMPEG_PRESET_DV:
1622                         rd->ffcodecdata.type = FFMPEG_DV;
1623                         rd->xsch = 720;
1624                         rd->ysch = isntsc ? 480 : 576;
1625                         break;
1626
1627                 case FFMPEG_PRESET_H264:
1628                         rd->ffcodecdata.type = FFMPEG_AVI;
1629                         rd->ffcodecdata.codec = AV_CODEC_ID_H264;
1630                         rd->ffcodecdata.video_bitrate = 6000;
1631                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1632                         rd->ffcodecdata.rc_max_rate = 9000;
1633                         rd->ffcodecdata.rc_min_rate = 0;
1634                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1635                         rd->ffcodecdata.mux_packet_size = 2048;
1636                         rd->ffcodecdata.mux_rate = 10080000;
1637
1638                         break;
1639
1640                 case FFMPEG_PRESET_THEORA:
1641                 case FFMPEG_PRESET_XVID:
1642                         if (preset == FFMPEG_PRESET_XVID) {
1643                                 rd->ffcodecdata.type = FFMPEG_AVI;
1644                                 rd->ffcodecdata.codec = AV_CODEC_ID_MPEG4;
1645                         }
1646                         else if (preset == FFMPEG_PRESET_THEORA) {
1647                                 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1648                                 rd->ffcodecdata.codec = AV_CODEC_ID_THEORA;
1649                         }
1650
1651                         rd->ffcodecdata.video_bitrate = 6000;
1652                         rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1653                         rd->ffcodecdata.rc_max_rate = 9000;
1654                         rd->ffcodecdata.rc_min_rate = 0;
1655                         rd->ffcodecdata.rc_buffer_size = 224 * 8;
1656                         rd->ffcodecdata.mux_packet_size = 2048;
1657                         rd->ffcodecdata.mux_rate = 10080000;
1658                         break;
1659
1660         }
1661
1662         ffmpeg_set_expert_options(rd);
1663 }
1664
1665 void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
1666 {
1667         int audio = 0;
1668
1669         if (imf->imtype == R_IMF_IMTYPE_FFMPEG) {
1670                 if (rd->ffcodecdata.type <= 0 ||
1671                     rd->ffcodecdata.codec <= 0 ||
1672                     rd->ffcodecdata.audio_codec <= 0 ||
1673                     rd->ffcodecdata.video_bitrate <= 1)
1674                 {
1675                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
1676                         rd->ffcodecdata.constant_rate_factor = FFM_CRF_MEDIUM;
1677                         rd->ffcodecdata.ffmpeg_preset = FFM_PRESET_GOOD;
1678                         rd->ffcodecdata.type = FFMPEG_MKV;
1679                 }
1680                 if (rd->ffcodecdata.type == FFMPEG_OGG) {
1681                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1682                 }
1683
1684                 audio = 1;
1685         }
1686         else if (imf->imtype == R_IMF_IMTYPE_H264) {
1687                 if (rd->ffcodecdata.codec != AV_CODEC_ID_H264) {
1688                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
1689                         audio = 1;
1690                 }
1691         }
1692         else if (imf->imtype == R_IMF_IMTYPE_XVID) {
1693                 if (rd->ffcodecdata.codec != AV_CODEC_ID_MPEG4) {
1694                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_XVID);
1695                         audio = 1;
1696                 }
1697         }
1698         else if (imf->imtype == R_IMF_IMTYPE_THEORA) {
1699                 if (rd->ffcodecdata.codec != AV_CODEC_ID_THEORA) {
1700                         BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_THEORA);
1701                         audio = 1;
1702                 }
1703         }
1704
1705         if (audio && rd->ffcodecdata.audio_codec < 0) {
1706                 rd->ffcodecdata.audio_codec = AV_CODEC_ID_NONE;
1707                 rd->ffcodecdata.audio_bitrate = 128;
1708         }
1709 }
1710
1711 void BKE_ffmpeg_codec_settings_verify(RenderData *rd)
1712 {
1713         ffmpeg_set_expert_options(rd);
1714 }
1715
1716 bool BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd)
1717 {
1718         int codec = rd->ffcodecdata.codec;
1719
1720         if (codec == AV_CODEC_ID_QTRLE)
1721                 return true;
1722
1723         if (codec == AV_CODEC_ID_PNG)
1724                 return true;
1725
1726         if (codec == AV_CODEC_ID_HUFFYUV)
1727                 return true;
1728
1729 #ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
1730         if (codec == AV_CODEC_ID_FFV1)
1731                 return true;
1732 #endif
1733
1734         return false;
1735 }
1736
1737 void *BKE_ffmpeg_context_create(void)
1738 {
1739         FFMpegContext *context;
1740
1741         /* new ffmpeg data struct */
1742         context = MEM_callocN(sizeof(FFMpegContext), "new ffmpeg context");
1743
1744         context->ffmpeg_codec = AV_CODEC_ID_MPEG4;
1745         context->ffmpeg_audio_codec = AV_CODEC_ID_NONE;
1746         context->ffmpeg_video_bitrate = 1150;
1747         context->ffmpeg_audio_bitrate = 128;
1748         context->ffmpeg_gop_size = 12;
1749         context->ffmpeg_autosplit = 0;
1750         context->ffmpeg_autosplit_count = 0;
1751         context->ffmpeg_preview = false;
1752         context->stamp_data = NULL;
1753
1754         return context;
1755 }
1756
1757 void BKE_ffmpeg_context_free(void *context_v)
1758 {
1759         FFMpegContext *context = context_v;
1760         if (context == NULL) {
1761                 return;
1762         }
1763         if (context->stamp_data) {
1764                 MEM_freeN(context->stamp_data);
1765         }
1766         MEM_freeN(context);
1767 }
1768
1769 #endif /* WITH_FFMPEG */