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