src/feature/ffmpeg/ffmpeg-encoder.c (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "ffmpeg-encoder.h"
7
8#include <mgba/core/core.h>
9#include <mgba/gba/interface.h>
10#include <mgba/internal/gba/gba.h>
11#include <mgba-util/math.h>
12
13#include <libavcodec/version.h>
14#include <libavcodec/avcodec.h>
15
16#include <libavfilter/buffersink.h>
17#include <libavfilter/buffersrc.h>
18
19#include <libavutil/version.h>
20#if LIBAVUTIL_VERSION_MAJOR >= 53
21#include <libavutil/buffer.h>
22#endif
23#include <libavutil/imgutils.h>
24#include <libavutil/mathematics.h>
25#include <libavutil/opt.h>
26
27#ifdef USE_LIBAVRESAMPLE
28#include <libavresample/avresample.h>
29#else
30#include <libswresample/swresample.h>
31#endif
32#include <libswscale/swscale.h>
33
34static void _ffmpegPostVideoFrame(struct mAVStream*, const color_t* pixels, size_t stride);
35static void _ffmpegPostAudioFrame(struct mAVStream*, int16_t left, int16_t right);
36static void _ffmpegSetVideoDimensions(struct mAVStream*, unsigned width, unsigned height);
37
38static bool _ffmpegWriteAudioFrame(struct FFmpegEncoder* encoder, struct AVFrame* audioFrame);
39static bool _ffmpegWriteVideoFrame(struct FFmpegEncoder* encoder, struct AVFrame* videoFrame);
40
41enum {
42 PREFERRED_SAMPLE_RATE = 0x8000
43};
44
45void FFmpegEncoderInit(struct FFmpegEncoder* encoder) {
46#if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
47 av_register_all();
48#endif
49
50 encoder->d.videoDimensionsChanged = _ffmpegSetVideoDimensions;
51 encoder->d.postVideoFrame = _ffmpegPostVideoFrame;
52 encoder->d.postAudioFrame = _ffmpegPostAudioFrame;
53 encoder->d.postAudioBuffer = 0;
54
55 encoder->audioCodec = NULL;
56 encoder->videoCodec = NULL;
57 encoder->containerFormat = NULL;
58 FFmpegEncoderSetAudio(encoder, "flac", 0);
59 FFmpegEncoderSetVideo(encoder, "libx264", 0, 0);
60 FFmpegEncoderSetContainer(encoder, "matroska");
61 FFmpegEncoderSetDimensions(encoder, GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
62 encoder->iwidth = GBA_VIDEO_HORIZONTAL_PIXELS;
63 encoder->iheight = GBA_VIDEO_VERTICAL_PIXELS;
64 encoder->frameskip = 1;
65 encoder->skipResidue = 0;
66 encoder->loop = false;
67 encoder->ipixFormat =
68#ifdef COLOR_16_BIT
69#ifdef COLOR_5_6_5
70 AV_PIX_FMT_RGB565;
71#else
72 AV_PIX_FMT_BGR555;
73#endif
74#else
75#ifndef USE_LIBAV
76 AV_PIX_FMT_0BGR32;
77#else
78 AV_PIX_FMT_BGR32;
79#endif
80#endif
81 encoder->resampleContext = NULL;
82 encoder->absf = NULL;
83 encoder->context = NULL;
84 encoder->scaleContext = NULL;
85 encoder->audio = NULL;
86 encoder->audioStream = NULL;
87 encoder->audioFrame = NULL;
88 encoder->audioBuffer = NULL;
89 encoder->postaudioBuffer = NULL;
90 encoder->video = NULL;
91 encoder->videoStream = NULL;
92 encoder->videoFrame = NULL;
93 encoder->graph = NULL;
94 encoder->source = NULL;
95 encoder->sink = NULL;
96 encoder->sinkFrame = NULL;
97 FFmpegEncoderSetInputFrameRate(encoder, VIDEO_TOTAL_LENGTH, GBA_ARM7TDMI_FREQUENCY);
98
99 int i;
100 for (i = 0; i < FFMPEG_FILTERS_MAX; ++i) {
101 encoder->filters[i] = NULL;
102 }
103}
104
105bool FFmpegEncoderSetAudio(struct FFmpegEncoder* encoder, const char* acodec, unsigned abr) {
106 static const struct {
107 int format;
108 int priority;
109 } priorities[] = {
110 { AV_SAMPLE_FMT_S16, 0 },
111 { AV_SAMPLE_FMT_S16P, 1 },
112 { AV_SAMPLE_FMT_S32, 2 },
113 { AV_SAMPLE_FMT_S32P, 2 },
114 { AV_SAMPLE_FMT_FLT, 3 },
115 { AV_SAMPLE_FMT_FLTP, 3 },
116 { AV_SAMPLE_FMT_DBL, 4 },
117 { AV_SAMPLE_FMT_DBLP, 4 }
118 };
119
120 if (!acodec) {
121 encoder->audioCodec = 0;
122 return true;
123 }
124
125 AVCodec* codec = avcodec_find_encoder_by_name(acodec);
126 if (!codec) {
127 return false;
128 }
129
130 if (!codec->sample_fmts) {
131 return false;
132 }
133 size_t i;
134 size_t j;
135 int priority = INT_MAX;
136 encoder->sampleFormat = AV_SAMPLE_FMT_NONE;
137 for (i = 0; codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; ++i) {
138 for (j = 0; j < sizeof(priorities) / sizeof(*priorities); ++j) {
139 if (codec->sample_fmts[i] == priorities[j].format && priority > priorities[j].priority) {
140 priority = priorities[j].priority;
141 encoder->sampleFormat = codec->sample_fmts[i];
142 }
143 }
144 }
145 if (encoder->sampleFormat == AV_SAMPLE_FMT_NONE) {
146 return false;
147 }
148 encoder->sampleRate = PREFERRED_SAMPLE_RATE;
149 if (codec->supported_samplerates) {
150 for (i = 0; codec->supported_samplerates[i]; ++i) {
151 if (codec->supported_samplerates[i] < PREFERRED_SAMPLE_RATE) {
152 continue;
153 }
154 if (encoder->sampleRate == PREFERRED_SAMPLE_RATE || encoder->sampleRate > codec->supported_samplerates[i]) {
155 encoder->sampleRate = codec->supported_samplerates[i];
156 }
157 }
158 } else if (codec->id == AV_CODEC_ID_AAC) {
159 // HACK: AAC doesn't support 32768Hz (it rounds to 32000), but libfaac doesn't tell us that
160 encoder->sampleRate = 44100;
161 }
162 encoder->audioCodec = acodec;
163 encoder->audioBitrate = abr;
164 return true;
165}
166
167bool FFmpegEncoderSetVideo(struct FFmpegEncoder* encoder, const char* vcodec, unsigned vbr, int frameskip) {
168 static const struct {
169 enum AVPixelFormat format;
170 int priority;
171 } priorities[] = {
172 { AV_PIX_FMT_RGB555, 0 },
173 { AV_PIX_FMT_BGR555, 0 },
174 { AV_PIX_FMT_RGB565, 1 },
175 { AV_PIX_FMT_BGR565, 1 },
176 { AV_PIX_FMT_RGB24, 2 },
177 { AV_PIX_FMT_BGR24, 2 },
178#ifndef USE_LIBAV
179 { AV_PIX_FMT_BGR0, 3 },
180 { AV_PIX_FMT_RGB0, 3 },
181 { AV_PIX_FMT_0BGR, 3 },
182 { AV_PIX_FMT_0RGB, 3 },
183#endif
184 { AV_PIX_FMT_RGB32, 4},
185 { AV_PIX_FMT_BGR32, 4},
186 { AV_PIX_FMT_YUV444P, 5 },
187 { AV_PIX_FMT_YUV422P, 6 },
188 { AV_PIX_FMT_YUV420P, 7 },
189 { AV_PIX_FMT_PAL8, 8 },
190 };
191
192 if (!vcodec) {
193 encoder->videoCodec = 0;
194 return true;
195 }
196
197 AVCodec* codec = avcodec_find_encoder_by_name(vcodec);
198 if (!codec) {
199 return false;
200 }
201
202 size_t i;
203 size_t j;
204 int priority = INT_MAX;
205 encoder->pixFormat = AV_PIX_FMT_NONE;
206 for (i = 0; codec->pix_fmts[i] != AV_PIX_FMT_NONE; ++i) {
207 for (j = 0; j < sizeof(priorities) / sizeof(*priorities); ++j) {
208 if (codec->pix_fmts[i] == priorities[j].format && priority > priorities[j].priority) {
209 priority = priorities[j].priority;
210 encoder->pixFormat = codec->pix_fmts[i];
211 }
212 }
213 }
214 if (encoder->pixFormat == AV_PIX_FMT_NONE) {
215 return false;
216 }
217 encoder->videoCodec = vcodec;
218 encoder->videoBitrate = vbr;
219 encoder->frameskip = frameskip + 1;
220 return true;
221}
222
223bool FFmpegEncoderSetContainer(struct FFmpegEncoder* encoder, const char* container) {
224 AVOutputFormat* oformat = av_guess_format(container, 0, 0);
225 if (!oformat) {
226 return false;
227 }
228 encoder->containerFormat = container;
229 return true;
230}
231
232void FFmpegEncoderSetDimensions(struct FFmpegEncoder* encoder, int width, int height) {
233 encoder->width = width > 0 ? width : GBA_VIDEO_HORIZONTAL_PIXELS;
234 encoder->height = height > 0 ? height : GBA_VIDEO_VERTICAL_PIXELS;
235}
236
237void FFmpegEncoderSetLooping(struct FFmpegEncoder* encoder, bool loop) {
238 encoder->loop = loop;
239}
240
241bool FFmpegEncoderVerifyContainer(struct FFmpegEncoder* encoder) {
242 AVOutputFormat* oformat = av_guess_format(encoder->containerFormat, 0, 0);
243 AVCodec* acodec = avcodec_find_encoder_by_name(encoder->audioCodec);
244 AVCodec* vcodec = avcodec_find_encoder_by_name(encoder->videoCodec);
245 if ((encoder->audioCodec && !acodec) || (encoder->videoCodec && !vcodec) || !oformat || (!acodec && !vcodec)) {
246 return false;
247 }
248 if (encoder->audioCodec && !avformat_query_codec(oformat, acodec->id, FF_COMPLIANCE_EXPERIMENTAL)) {
249 return false;
250 }
251 if (encoder->videoCodec && !avformat_query_codec(oformat, vcodec->id, FF_COMPLIANCE_EXPERIMENTAL)) {
252 return false;
253 }
254 return true;
255}
256
257bool FFmpegEncoderOpen(struct FFmpegEncoder* encoder, const char* outfile) {
258 AVCodec* acodec = avcodec_find_encoder_by_name(encoder->audioCodec);
259 AVCodec* vcodec = avcodec_find_encoder_by_name(encoder->videoCodec);
260 if ((encoder->audioCodec && !acodec) || (encoder->videoCodec && !vcodec) || !FFmpegEncoderVerifyContainer(encoder)) {
261 return false;
262 }
263
264 if (encoder->context) {
265 return false;
266 }
267
268 encoder->currentAudioSample = 0;
269 encoder->currentAudioFrame = 0;
270 encoder->currentVideoFrame = 0;
271 encoder->skipResidue = 0;
272
273 AVOutputFormat* oformat = av_guess_format(encoder->containerFormat, 0, 0);
274#ifndef USE_LIBAV
275 avformat_alloc_output_context2(&encoder->context, oformat, 0, outfile);
276#else
277 encoder->context = avformat_alloc_context();
278 strncpy(encoder->context->filename, outfile, sizeof(encoder->context->filename) - 1);
279 encoder->context->filename[sizeof(encoder->context->filename) - 1] = '\0';
280 encoder->context->oformat = oformat;
281#endif
282
283 if (acodec) {
284#ifdef FFMPEG_USE_CODECPAR
285 encoder->audioStream = avformat_new_stream(encoder->context, NULL);
286 encoder->audio = avcodec_alloc_context3(acodec);
287#else
288 encoder->audioStream = avformat_new_stream(encoder->context, acodec);
289 encoder->audio = encoder->audioStream->codec;
290#endif
291 encoder->audio->bit_rate = encoder->audioBitrate;
292 encoder->audio->channels = 2;
293 encoder->audio->channel_layout = AV_CH_LAYOUT_STEREO;
294 encoder->audio->sample_rate = encoder->sampleRate;
295 encoder->audio->sample_fmt = encoder->sampleFormat;
296 AVDictionary* opts = 0;
297 av_dict_set(&opts, "strict", "-2", 0);
298 if (encoder->context->oformat->flags & AVFMT_GLOBALHEADER) {
299#ifdef AV_CODEC_FLAG_GLOBAL_HEADER
300 encoder->audio->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
301#else
302 encoder->audio->flags |= CODEC_FLAG_GLOBAL_HEADER;
303#endif
304 }
305 int res = avcodec_open2(encoder->audio, acodec, &opts);
306 av_dict_free(&opts);
307 if (res < 0) {
308 FFmpegEncoderClose(encoder);
309 return false;
310 }
311#if LIBAVCODEC_VERSION_MAJOR >= 55
312 encoder->audioFrame = av_frame_alloc();
313#else
314 encoder->audioFrame = avcodec_alloc_frame();
315#endif
316 if (!encoder->audio->frame_size) {
317 encoder->audio->frame_size = 1;
318 }
319 encoder->audioFrame->nb_samples = encoder->audio->frame_size;
320 encoder->audioFrame->format = encoder->audio->sample_fmt;
321 encoder->audioFrame->pts = 0;
322#ifdef USE_LIBAVRESAMPLE
323 encoder->resampleContext = avresample_alloc_context();
324 av_opt_set_int(encoder->resampleContext, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
325 av_opt_set_int(encoder->resampleContext, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
326 av_opt_set_int(encoder->resampleContext, "in_sample_rate", PREFERRED_SAMPLE_RATE, 0);
327 av_opt_set_int(encoder->resampleContext, "out_sample_rate", encoder->sampleRate, 0);
328 av_opt_set_int(encoder->resampleContext, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
329 av_opt_set_int(encoder->resampleContext, "out_sample_fmt", encoder->sampleFormat, 0);
330 avresample_open(encoder->resampleContext);
331#else
332 encoder->resampleContext = swr_alloc_set_opts(NULL, AV_CH_LAYOUT_STEREO, encoder->sampleFormat, encoder->sampleRate,
333 AV_CH_LAYOUT_STEREO, AV_SAMPLE_FMT_S16, PREFERRED_SAMPLE_RATE, 0, NULL);
334 swr_init(encoder->resampleContext);
335#endif
336 encoder->audioBufferSize = (encoder->audioFrame->nb_samples * PREFERRED_SAMPLE_RATE / encoder->sampleRate) * 4;
337 encoder->audioBuffer = av_malloc(encoder->audioBufferSize);
338 encoder->postaudioBufferSize = av_samples_get_buffer_size(0, encoder->audio->channels, encoder->audio->frame_size, encoder->audio->sample_fmt, 0);
339 encoder->postaudioBuffer = av_malloc(encoder->postaudioBufferSize);
340 avcodec_fill_audio_frame(encoder->audioFrame, encoder->audio->channels, encoder->audio->sample_fmt, (const uint8_t*) encoder->postaudioBuffer, encoder->postaudioBufferSize, 0);
341
342 if (encoder->audio->codec->id == AV_CODEC_ID_AAC &&
343 (strcasecmp(encoder->containerFormat, "mp4") ||
344 strcasecmp(encoder->containerFormat, "m4v") ||
345 strcasecmp(encoder->containerFormat, "mov"))) {
346 // MP4 container doesn't support the raw ADTS AAC format that the encoder spits out
347#ifdef FFMPEG_USE_NEW_BSF
348 av_bsf_alloc(av_bsf_get_by_name("aac_adtstoasc"), &encoder->absf);
349 avcodec_parameters_from_context(encoder->absf->par_in, encoder->audio);
350 av_bsf_init(encoder->absf);
351#else
352 encoder->absf = av_bitstream_filter_init("aac_adtstoasc");
353#endif
354 }
355#ifdef FFMPEG_USE_CODECPAR
356 avcodec_parameters_from_context(encoder->audioStream->codecpar, encoder->audio);
357#endif
358 }
359
360 if (vcodec) {
361#ifdef FFMPEG_USE_CODECPAR
362 encoder->videoStream = avformat_new_stream(encoder->context, NULL);
363 encoder->video = avcodec_alloc_context3(vcodec);
364#else
365 encoder->videoStream = avformat_new_stream(encoder->context, vcodec);
366 encoder->video = encoder->videoStream->codec;
367#endif
368 encoder->video->bit_rate = encoder->videoBitrate;
369 encoder->video->width = encoder->width;
370 encoder->video->height = encoder->height;
371 encoder->video->time_base = (AVRational) { encoder->frameCycles * encoder->frameskip, encoder->cycles };
372 encoder->video->framerate = (AVRational) { encoder->cycles, encoder->frameCycles * encoder->frameskip };
373 encoder->videoStream->time_base = encoder->video->time_base;
374 encoder->videoStream->avg_frame_rate = encoder->video->framerate;
375 encoder->video->pix_fmt = encoder->pixFormat;
376 encoder->video->gop_size = 60;
377 encoder->video->max_b_frames = 3;
378 if (encoder->context->oformat->flags & AVFMT_GLOBALHEADER) {
379#ifdef AV_CODEC_FLAG_GLOBAL_HEADER
380 encoder->video->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
381#else
382 encoder->video->flags |= CODEC_FLAG_GLOBAL_HEADER;
383#endif
384 }
385
386 if (encoder->video->codec->id == AV_CODEC_ID_H264 &&
387 (strcasecmp(encoder->containerFormat, "mp4") ||
388 strcasecmp(encoder->containerFormat, "m4v") ||
389 strcasecmp(encoder->containerFormat, "mov"))) {
390 // QuickTime and a few other things require YUV420
391 encoder->video->pix_fmt = AV_PIX_FMT_YUV420P;
392 }
393#if LIBAVCODEC_VERSION_MAJOR >= 57
394 if (encoder->video->codec->id == AV_CODEC_ID_FFV1) {
395 av_opt_set(encoder->video->priv_data, "coder", "range_tab", 0);
396 }
397#endif
398
399 if (strcmp(vcodec->name, "libx264") == 0) {
400 // Try to adaptively figure out when you can use a slower encoder
401 if (encoder->width * encoder->height > 1000000) {
402 av_opt_set(encoder->video->priv_data, "preset", "superfast", 0);
403 } else if (encoder->width * encoder->height > 500000) {
404 av_opt_set(encoder->video->priv_data, "preset", "veryfast", 0);
405 } else {
406 av_opt_set(encoder->video->priv_data, "preset", "faster", 0);
407 }
408 if (encoder->videoBitrate == 0) {
409 av_opt_set(encoder->video->priv_data, "crf", "0", 0);
410 encoder->video->pix_fmt = AV_PIX_FMT_YUV444P;
411 }
412 }
413 if (strcmp(vcodec->name, "libvpx-vp9") == 0 && encoder->videoBitrate == 0) {
414 av_opt_set(encoder->video->priv_data, "lossless", "1", 0);
415 encoder->video->pix_fmt = AV_PIX_FMT_YUV444P;
416 }
417 if (strcmp(vcodec->name, "libwebp_anim") == 0 && encoder->videoBitrate == 0) {
418 av_opt_set(encoder->video->priv_data, "lossless", "1", 0);
419 encoder->video->pix_fmt = AV_PIX_FMT_RGB32;
420 }
421
422 if (encoder->pixFormat == AV_PIX_FMT_PAL8) {
423 encoder->graph = avfilter_graph_alloc();
424
425 const struct AVFilter* source = avfilter_get_by_name("buffer");
426 const struct AVFilter* sink = avfilter_get_by_name("buffersink");
427 const struct AVFilter* split = avfilter_get_by_name("split");
428 const struct AVFilter* palettegen = avfilter_get_by_name("palettegen");
429 const struct AVFilter* paletteuse = avfilter_get_by_name("paletteuse");
430
431 if (!source || !sink || !split || !palettegen || !paletteuse || !encoder->graph) {
432 FFmpegEncoderClose(encoder);
433 return false;
434 }
435
436 char args[256];
437 snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d",
438 encoder->video->width, encoder->video->height, encoder->ipixFormat,
439 encoder->video->time_base.num, encoder->video->time_base.den);
440
441 int res = 0;
442 res |= avfilter_graph_create_filter(&encoder->source, source, NULL, args, NULL, encoder->graph);
443 res |= avfilter_graph_create_filter(&encoder->sink, sink, NULL, NULL, NULL, encoder->graph);
444 res |= avfilter_graph_create_filter(&encoder->filters[0], split, NULL, NULL, NULL, encoder->graph);
445 res |= avfilter_graph_create_filter(&encoder->filters[1], palettegen, NULL, "reserve_transparent=off", NULL, encoder->graph);
446 res |= avfilter_graph_create_filter(&encoder->filters[2], paletteuse, NULL, "dither=none", NULL, encoder->graph);
447 if (res < 0) {
448 FFmpegEncoderClose(encoder);
449 return false;
450 }
451
452 res = 0;
453 res |= avfilter_link(encoder->source, 0, encoder->filters[0], 0);
454 res |= avfilter_link(encoder->filters[0], 0, encoder->filters[1], 0);
455 res |= avfilter_link(encoder->filters[0], 1, encoder->filters[2], 0);
456 res |= avfilter_link(encoder->filters[1], 0, encoder->filters[2], 1);
457 res |= avfilter_link(encoder->filters[2], 0, encoder->sink, 0);
458 if (res < 0 || avfilter_graph_config(encoder->graph, NULL) < 0) {
459 FFmpegEncoderClose(encoder);
460 return false;
461 }
462
463#if LIBAVCODEC_VERSION_MAJOR >= 55
464 encoder->sinkFrame = av_frame_alloc();
465#else
466 encoder->sinkFrame = avcodec_alloc_frame();
467#endif
468 }
469 AVDictionary* opts = 0;
470 av_dict_set(&opts, "strict", "-2", 0);
471 int res = avcodec_open2(encoder->video, vcodec, &opts);
472 av_dict_free(&opts);
473 if (res < 0) {
474 FFmpegEncoderClose(encoder);
475 return false;
476 }
477#if LIBAVCODEC_VERSION_MAJOR >= 55
478 encoder->videoFrame = av_frame_alloc();
479#else
480 encoder->videoFrame = avcodec_alloc_frame();
481#endif
482 encoder->videoFrame->format = encoder->video->pix_fmt != AV_PIX_FMT_PAL8 ? encoder->video->pix_fmt : encoder->ipixFormat;
483 encoder->videoFrame->width = encoder->video->width;
484 encoder->videoFrame->height = encoder->video->height;
485 encoder->videoFrame->pts = 0;
486 _ffmpegSetVideoDimensions(&encoder->d, encoder->iwidth, encoder->iheight);
487 av_image_alloc(encoder->videoFrame->data, encoder->videoFrame->linesize, encoder->videoFrame->width, encoder->videoFrame->height, encoder->videoFrame->format, 32);
488#ifdef FFMPEG_USE_CODECPAR
489 avcodec_parameters_from_context(encoder->videoStream->codecpar, encoder->video);
490#endif
491 }
492
493 if (strcmp(encoder->containerFormat, "gif") == 0) {
494 av_opt_set(encoder->context->priv_data, "loop", encoder->loop ? "0" : "-1", 0);
495 } else if (strcmp(encoder->containerFormat, "apng") == 0) {
496 av_opt_set(encoder->context->priv_data, "plays", encoder->loop ? "0" : "1", 0);
497 } else if (strcmp(encoder->containerFormat, "webp") == 0) {
498 av_opt_set(encoder->context->priv_data, "loop", encoder->loop ? "0" : "1", 0);
499 }
500
501 AVDictionary* opts = 0;
502 av_dict_set(&opts, "strict", "-2", 0);
503 bool res = avio_open(&encoder->context->pb, outfile, AVIO_FLAG_WRITE) < 0 || avformat_write_header(encoder->context, &opts) < 0;
504 av_dict_free(&opts);
505 if (res) {
506 FFmpegEncoderClose(encoder);
507 return false;
508 }
509 return true;
510}
511
512void FFmpegEncoderClose(struct FFmpegEncoder* encoder) {
513 if (encoder->audio) {
514 while (true) {
515 if (!_ffmpegWriteAudioFrame(encoder, NULL)) {
516 break;
517 }
518 }
519 }
520 if (encoder->video) {
521 if (encoder->graph) {
522 if (av_buffersrc_add_frame(encoder->source, NULL) >= 0) {
523 while (true) {
524 int res = av_buffersink_get_frame(encoder->sink, encoder->sinkFrame);
525 if (res < 0) {
526 break;
527 }
528 _ffmpegWriteVideoFrame(encoder, encoder->sinkFrame);
529 av_frame_unref(encoder->sinkFrame);
530 }
531 }
532 }
533 while (true) {
534 if (!_ffmpegWriteVideoFrame(encoder, NULL)) {
535 break;
536 }
537 }
538 }
539
540 if (encoder->context && encoder->context->pb) {
541 av_write_trailer(encoder->context);
542 avio_close(encoder->context->pb);
543 }
544
545 if (encoder->postaudioBuffer) {
546 av_free(encoder->postaudioBuffer);
547 encoder->postaudioBuffer = NULL;
548 }
549 if (encoder->audioBuffer) {
550 av_free(encoder->audioBuffer);
551 encoder->audioBuffer = NULL;
552 }
553
554 if (encoder->audioFrame) {
555#if LIBAVCODEC_VERSION_MAJOR >= 55
556 av_frame_free(&encoder->audioFrame);
557#else
558 avcodec_free_frame(&encoder->audioFrame);
559#endif
560 }
561 if (encoder->audio) {
562#ifdef FFMPEG_USE_CODECPAR
563 avcodec_free_context(&encoder->audio);
564#else
565 avcodec_close(encoder->audio);
566 encoder->audio = NULL;
567#endif
568 }
569
570 if (encoder->resampleContext) {
571#ifdef USE_LIBAVRESAMPLE
572 avresample_close(encoder->resampleContext);
573 encoder->resampleContext = NULL;
574#else
575 swr_free(&encoder->resampleContext);
576#endif
577 }
578
579 if (encoder->absf) {
580#ifdef FFMPEG_USE_NEW_BSF
581 av_bsf_free(&encoder->absf);
582#else
583 av_bitstream_filter_close(encoder->absf);
584 encoder->absf = NULL;
585#endif
586 }
587
588 if (encoder->videoFrame) {
589 av_freep(encoder->videoFrame->data);
590#if LIBAVCODEC_VERSION_MAJOR >= 55
591 av_frame_free(&encoder->videoFrame);
592#else
593 avcodec_free_frame(&encoder->videoFrame);
594#endif
595 }
596
597 if (encoder->sinkFrame) {
598#if LIBAVCODEC_VERSION_MAJOR >= 55
599 av_frame_free(&encoder->sinkFrame);
600#else
601 avcodec_free_frame(&encoder->sinkFrame);
602#endif
603 encoder->sinkFrame = NULL;
604 }
605
606 if (encoder->video) {
607#ifdef FFMPEG_USE_CODECPAR
608 avcodec_free_context(&encoder->video);
609#else
610 avcodec_close(encoder->video);
611 encoder->video = NULL;
612#endif
613 }
614
615 if (encoder->scaleContext) {
616 sws_freeContext(encoder->scaleContext);
617 encoder->scaleContext = NULL;
618 }
619
620 if (encoder->graph) {
621 avfilter_graph_free(&encoder->graph);
622 encoder->graph = NULL;
623 encoder->source = NULL;
624 encoder->sink = NULL;
625
626 int i;
627 for (i = 0; i < FFMPEG_FILTERS_MAX; ++i) {
628 encoder->filters[i] = NULL;
629 }
630 }
631
632 if (encoder->context) {
633 avformat_free_context(encoder->context);
634 encoder->context = NULL;
635 }
636}
637
638bool FFmpegEncoderIsOpen(struct FFmpegEncoder* encoder) {
639 return !!encoder->context;
640}
641
642void _ffmpegPostAudioFrame(struct mAVStream* stream, int16_t left, int16_t right) {
643 struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
644 if (!encoder->context || !encoder->audioCodec) {
645 return;
646 }
647
648 if (encoder->absf && !left) {
649 // XXX: AVBSF doesn't like silence. Figure out why.
650 left = 1;
651 }
652
653 encoder->audioBuffer[encoder->currentAudioSample * 2] = left;
654 encoder->audioBuffer[encoder->currentAudioSample * 2 + 1] = right;
655
656 ++encoder->currentAudioSample;
657
658 if (encoder->currentAudioSample * 4 < encoder->audioBufferSize) {
659 return;
660 }
661
662 int channelSize = 2 * av_get_bytes_per_sample(encoder->audio->sample_fmt);
663 encoder->currentAudioSample = 0;
664#ifdef USE_LIBAVRESAMPLE
665 avresample_convert(encoder->resampleContext, 0, 0, 0,
666 (uint8_t**) &encoder->audioBuffer, 0, encoder->audioBufferSize / 4);
667
668 if (avresample_available(encoder->resampleContext) < encoder->audioFrame->nb_samples) {
669 return;
670 }
671#if LIBAVCODEC_VERSION_MAJOR >= 55
672 av_frame_make_writable(encoder->audioFrame);
673#endif
674 int samples = avresample_read(encoder->resampleContext, encoder->audioFrame->data, encoder->postaudioBufferSize / channelSize);
675#else
676#if LIBAVCODEC_VERSION_MAJOR >= 55
677 av_frame_make_writable(encoder->audioFrame);
678#endif
679 if (swr_get_out_samples(encoder->resampleContext, 1) < encoder->audioFrame->nb_samples) {
680 swr_convert(encoder->resampleContext, NULL, 0, (const uint8_t**) &encoder->audioBuffer, encoder->audioBufferSize / 4);
681 return;
682 }
683 int samples = swr_convert(encoder->resampleContext, encoder->audioFrame->data, encoder->postaudioBufferSize / channelSize,
684 (const uint8_t**) &encoder->audioBuffer, encoder->audioBufferSize / 4);
685#endif
686
687 encoder->audioFrame->pts = encoder->currentAudioFrame;
688 encoder->currentAudioFrame += samples;
689
690 _ffmpegWriteAudioFrame(encoder, encoder->audioFrame);
691}
692
693bool _ffmpegWriteAudioFrame(struct FFmpegEncoder* encoder, struct AVFrame* audioFrame) {
694 AVPacket packet;
695 av_init_packet(&packet);
696 packet.data = 0;
697 packet.size = 0;
698
699 int gotData;
700#ifdef FFMPEG_USE_PACKETS
701 avcodec_send_frame(encoder->audio, audioFrame);
702 gotData = avcodec_receive_packet(encoder->audio, &packet);
703 gotData = (gotData == 0) && packet.size;
704#else
705 avcodec_encode_audio2(encoder->audio, &packet, audioFrame, &gotData);
706#endif
707 packet.pts = av_rescale_q(packet.pts, encoder->audio->time_base, encoder->audioStream->time_base);
708 packet.dts = packet.pts;
709
710 if (gotData) {
711 if (encoder->absf) {
712 AVPacket tempPacket;
713
714#ifdef FFMPEG_USE_NEW_BSF
715 int success = av_bsf_send_packet(encoder->absf, &packet);
716 if (success >= 0) {
717 success = av_bsf_receive_packet(encoder->absf, &tempPacket);
718 }
719#else
720 int success = av_bitstream_filter_filter(encoder->absf, encoder->audio, 0,
721 &tempPacket.data, &tempPacket.size,
722 packet.data, packet.size, 0);
723#endif
724
725 if (success >= 0) {
726#if LIBAVUTIL_VERSION_MAJOR >= 53
727 tempPacket.buf = av_buffer_create(tempPacket.data, tempPacket.size, av_buffer_default_free, 0, 0);
728#endif
729
730#ifdef FFMPEG_USE_PACKET_UNREF
731 av_packet_move_ref(&packet, &tempPacket);
732#else
733 av_free_packet(&packet);
734 packet = tempPacket;
735#endif
736
737 packet.stream_index = encoder->audioStream->index;
738 av_interleaved_write_frame(encoder->context, &packet);
739 }
740 } else {
741 packet.stream_index = encoder->audioStream->index;
742 av_interleaved_write_frame(encoder->context, &packet);
743 }
744 }
745#ifdef FFMPEG_USE_PACKET_UNREF
746 av_packet_unref(&packet);
747#else
748 av_free_packet(&packet);
749#endif
750 return gotData;
751}
752
753void _ffmpegPostVideoFrame(struct mAVStream* stream, const color_t* pixels, size_t stride) {
754 struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
755 if (!encoder->context || !encoder->videoCodec) {
756 return;
757 }
758 encoder->skipResidue = (encoder->skipResidue + 1) % encoder->frameskip;
759 if (encoder->skipResidue) {
760 return;
761 }
762 stride *= BYTES_PER_PIXEL;
763
764#if LIBAVCODEC_VERSION_MAJOR >= 55
765 av_frame_make_writable(encoder->videoFrame);
766#endif
767 if (encoder->video->codec->id == AV_CODEC_ID_WEBP) {
768 // TODO: Figure out why WebP is rescaling internally (should video frames not be rescaled externally?)
769 encoder->videoFrame->pts = encoder->currentVideoFrame;
770 } else {
771 encoder->videoFrame->pts = av_rescale_q(encoder->currentVideoFrame, encoder->video->time_base, encoder->videoStream->time_base);
772 }
773 ++encoder->currentVideoFrame;
774
775 sws_scale(encoder->scaleContext, (const uint8_t* const*) &pixels, (const int*) &stride, 0, encoder->iheight, encoder->videoFrame->data, encoder->videoFrame->linesize);
776
777 if (encoder->graph) {
778 if (av_buffersrc_add_frame(encoder->source, encoder->videoFrame) < 0) {
779 return;
780 }
781 while (true) {
782 int res = av_buffersink_get_frame(encoder->sink, encoder->sinkFrame);
783 if (res < 0) {
784 break;
785 }
786 _ffmpegWriteVideoFrame(encoder, encoder->sinkFrame);
787 av_frame_unref(encoder->sinkFrame);
788 }
789 } else {
790 _ffmpegWriteVideoFrame(encoder, encoder->videoFrame);
791 }
792}
793
794bool _ffmpegWriteVideoFrame(struct FFmpegEncoder* encoder, struct AVFrame* videoFrame) {
795 AVPacket packet;
796
797 av_init_packet(&packet);
798 packet.data = 0;
799 packet.size = 0;
800
801 int gotData;
802#ifdef FFMPEG_USE_PACKETS
803 avcodec_send_frame(encoder->video, videoFrame);
804 gotData = avcodec_receive_packet(encoder->video, &packet) == 0;
805#else
806 avcodec_encode_video2(encoder->video, &packet, videoFrame, &gotData);
807#endif
808 if (gotData) {
809#ifndef FFMPEG_USE_PACKET_UNREF
810 if (encoder->video->coded_frame->key_frame) {
811 packet.flags |= AV_PKT_FLAG_KEY;
812 }
813#endif
814 packet.stream_index = encoder->videoStream->index;
815 av_interleaved_write_frame(encoder->context, &packet);
816 }
817#ifdef FFMPEG_USE_PACKET_UNREF
818 av_packet_unref(&packet);
819#else
820 av_free_packet(&packet);
821#endif
822
823 return gotData;
824}
825
826static void _ffmpegSetVideoDimensions(struct mAVStream* stream, unsigned width, unsigned height) {
827 struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
828 if (!encoder->context || !encoder->videoCodec) {
829 return;
830 }
831 encoder->iwidth = width;
832 encoder->iheight = height;
833 if (encoder->scaleContext) {
834 sws_freeContext(encoder->scaleContext);
835 }
836 encoder->scaleContext = sws_getContext(encoder->iwidth, encoder->iheight, encoder->ipixFormat,
837 encoder->videoFrame->width, encoder->videoFrame->height, encoder->videoFrame->format,
838 SWS_POINT, 0, 0, 0);
839}
840
841void FFmpegEncoderSetInputFrameRate(struct FFmpegEncoder* encoder, int numerator, int denominator) {
842 reduceFraction(&numerator, &denominator);
843 encoder->frameCycles = numerator;
844 encoder->cycles = denominator;
845 if (encoder->video) {
846 encoder->video->framerate = (AVRational) { denominator, numerator * encoder->frameskip };
847 }
848}