src/platform/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 "gba/video.h"
9
10#include <libavcodec/version.h>
11#include <libavcodec/avcodec.h>
12
13#include <libavutil/version.h>
14#if LIBAVUTIL_VERSION_MAJOR >= 53
15#include <libavutil/buffer.h>
16#endif
17#include <libavutil/imgutils.h>
18#include <libavutil/mathematics.h>
19#include <libavutil/opt.h>
20
21#include <libavresample/avresample.h>
22#include <libswscale/swscale.h>
23
24static void _ffmpegPostVideoFrame(struct GBAAVStream*, struct GBAVideoRenderer* renderer);
25static void _ffmpegPostAudioFrame(struct GBAAVStream*, int32_t left, int32_t right);
26
27enum {
28 PREFERRED_SAMPLE_RATE = 0x8000
29};
30
31void FFmpegEncoderInit(struct FFmpegEncoder* encoder) {
32 av_register_all();
33
34 encoder->d.postVideoFrame = _ffmpegPostVideoFrame;
35 encoder->d.postAudioFrame = _ffmpegPostAudioFrame;
36
37 encoder->audioCodec = 0;
38 encoder->videoCodec = 0;
39 encoder->containerFormat = 0;
40 FFmpegEncoderSetAudio(encoder, "flac", 0);
41 FFmpegEncoderSetVideo(encoder, "png", 0);
42 FFmpegEncoderSetContainer(encoder, "matroska");
43 FFmpegEncoderSetDimensions(encoder, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
44 encoder->resampleContext = 0;
45 encoder->absf = 0;
46 encoder->context = 0;
47}
48
49bool FFmpegEncoderSetAudio(struct FFmpegEncoder* encoder, const char* acodec, unsigned abr) {
50 static const struct {
51 int format;
52 int priority;
53 } priorities[] = {
54 { AV_SAMPLE_FMT_S16, 0 },
55 { AV_SAMPLE_FMT_S16P, 1 },
56 { AV_SAMPLE_FMT_S32, 2 },
57 { AV_SAMPLE_FMT_S32P, 2 },
58 { AV_SAMPLE_FMT_FLT, 3 },
59 { AV_SAMPLE_FMT_FLTP, 3 },
60 { AV_SAMPLE_FMT_DBL, 4 },
61 { AV_SAMPLE_FMT_DBLP, 4 }
62 };
63
64 if (!acodec) {
65 encoder->audioCodec = 0;
66 return true;
67 }
68
69 AVCodec* codec = avcodec_find_encoder_by_name(acodec);
70 if (!codec) {
71 return false;
72 }
73
74 if (!codec->sample_fmts) {
75 return false;
76 }
77 size_t i;
78 size_t j;
79 int priority = INT_MAX;
80 encoder->sampleFormat = AV_SAMPLE_FMT_NONE;
81 for (i = 0; codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; ++i) {
82 for (j = 0; j < sizeof(priorities) / sizeof(*priorities); ++j) {
83 if (codec->sample_fmts[i] == priorities[j].format && priority > priorities[j].priority) {
84 priority = priorities[j].priority;
85 encoder->sampleFormat = codec->sample_fmts[i];
86 }
87 }
88 }
89 if (encoder->sampleFormat == AV_SAMPLE_FMT_NONE) {
90 return false;
91 }
92 encoder->sampleRate = PREFERRED_SAMPLE_RATE;
93 if (codec->supported_samplerates) {
94 for (i = 0; codec->supported_samplerates[i]; ++i) {
95 if (codec->supported_samplerates[i] < PREFERRED_SAMPLE_RATE) {
96 continue;
97 }
98 if (encoder->sampleRate == PREFERRED_SAMPLE_RATE || encoder->sampleRate > codec->supported_samplerates[i]) {
99 encoder->sampleRate = codec->supported_samplerates[i];
100 }
101 }
102 } else if (codec->id == AV_CODEC_ID_AAC) {
103 // HACK: AAC doesn't support 32768Hz (it rounds to 32000), but libfaac doesn't tell us that
104 encoder->sampleRate = 44100;
105 }
106 encoder->audioCodec = acodec;
107 encoder->audioBitrate = abr;
108 return true;
109}
110
111bool FFmpegEncoderSetVideo(struct FFmpegEncoder* encoder, const char* vcodec, unsigned vbr) {
112 static const struct {
113 enum AVPixelFormat format;
114 int priority;
115 } priorities[] = {
116 { AV_PIX_FMT_RGB555, 0 },
117 { AV_PIX_FMT_BGR555, 0 },
118 { AV_PIX_FMT_RGB565, 1 },
119 { AV_PIX_FMT_BGR565, 1 },
120 { AV_PIX_FMT_RGB24, 2 },
121 { AV_PIX_FMT_BGR24, 2 },
122#ifndef USE_LIBAV
123 { AV_PIX_FMT_BGR0, 3 },
124 { AV_PIX_FMT_RGB0, 3 },
125 { AV_PIX_FMT_0BGR, 3 },
126 { AV_PIX_FMT_0RGB, 3 },
127#endif
128 { AV_PIX_FMT_YUV422P, 4 },
129 { AV_PIX_FMT_YUV444P, 5 },
130 { AV_PIX_FMT_YUV420P, 6 }
131 };
132 AVCodec* codec = avcodec_find_encoder_by_name(vcodec);
133 if (!codec) {
134 return false;
135 }
136
137 size_t i;
138 size_t j;
139 int priority = INT_MAX;
140 encoder->pixFormat = AV_PIX_FMT_NONE;
141 for (i = 0; codec->pix_fmts[i] != AV_PIX_FMT_NONE; ++i) {
142 for (j = 0; j < sizeof(priorities) / sizeof(*priorities); ++j) {
143 if (codec->pix_fmts[i] == priorities[j].format && priority > priorities[j].priority) {
144 priority = priorities[j].priority;
145 encoder->pixFormat = codec->pix_fmts[i];
146 }
147 }
148 }
149 if (encoder->pixFormat == AV_PIX_FMT_NONE) {
150 return false;
151 }
152 encoder->videoCodec = vcodec;
153 encoder->videoBitrate = vbr;
154 return true;
155}
156
157bool FFmpegEncoderSetContainer(struct FFmpegEncoder* encoder, const char* container) {
158 AVOutputFormat* oformat = av_guess_format(container, 0, 0);
159 if (!oformat) {
160 return false;
161 }
162 encoder->containerFormat = container;
163 return true;
164}
165
166void FFmpegEncoderSetDimensions(struct FFmpegEncoder* encoder, int width, int height) {
167 encoder->width = width > 0 ? width : VIDEO_HORIZONTAL_PIXELS;
168 encoder->height = height > 0 ? height : VIDEO_VERTICAL_PIXELS;
169}
170
171bool FFmpegEncoderVerifyContainer(struct FFmpegEncoder* encoder) {
172 AVOutputFormat* oformat = av_guess_format(encoder->containerFormat, 0, 0);
173 AVCodec* acodec = avcodec_find_encoder_by_name(encoder->audioCodec);
174 AVCodec* vcodec = avcodec_find_encoder_by_name(encoder->videoCodec);
175 if ((encoder->audioCodec && !acodec) || !vcodec || !oformat) {
176 return false;
177 }
178 if (encoder->audioCodec && !avformat_query_codec(oformat, acodec->id, FF_COMPLIANCE_EXPERIMENTAL)) {
179 return false;
180 }
181 if (!avformat_query_codec(oformat, vcodec->id, FF_COMPLIANCE_EXPERIMENTAL)) {
182 return false;
183 }
184 return true;
185}
186
187bool FFmpegEncoderOpen(struct FFmpegEncoder* encoder, const char* outfile) {
188 AVCodec* acodec = avcodec_find_encoder_by_name(encoder->audioCodec);
189 AVCodec* vcodec = avcodec_find_encoder_by_name(encoder->videoCodec);
190 if ((encoder->audioCodec && !acodec) || !vcodec || !FFmpegEncoderVerifyContainer(encoder)) {
191 return false;
192 }
193
194 encoder->currentAudioSample = 0;
195 encoder->currentAudioFrame = 0;
196 encoder->currentVideoFrame = 0;
197 encoder->nextAudioPts = 0;
198
199 AVOutputFormat* oformat = av_guess_format(encoder->containerFormat, 0, 0);
200#ifndef USE_LIBAV
201 avformat_alloc_output_context2(&encoder->context, oformat, 0, outfile);
202#else
203 encoder->context = avformat_alloc_context();
204 strncpy(encoder->context->filename, outfile, sizeof(encoder->context->filename));
205 encoder->context->oformat = oformat;
206#endif
207
208 if (acodec) {
209 encoder->audioStream = avformat_new_stream(encoder->context, acodec);
210 encoder->audio = encoder->audioStream->codec;
211 encoder->audio->bit_rate = encoder->audioBitrate;
212 encoder->audio->channels = 2;
213 encoder->audio->channel_layout = AV_CH_LAYOUT_STEREO;
214 encoder->audio->sample_rate = encoder->sampleRate;
215 encoder->audio->sample_fmt = encoder->sampleFormat;
216 AVDictionary* opts = 0;
217 av_dict_set(&opts, "strict", "-2", 0);
218 if (encoder->context->oformat->flags & AVFMT_GLOBALHEADER) {
219 encoder->audio->flags |= CODEC_FLAG_GLOBAL_HEADER;
220 }
221 avcodec_open2(encoder->audio, acodec, &opts);
222 av_dict_free(&opts);
223#if LIBAVCODEC_VERSION_MAJOR >= 55
224 encoder->audioFrame = av_frame_alloc();
225#else
226 encoder->audioFrame = avcodec_alloc_frame();
227#endif
228 if (!encoder->audio->frame_size) {
229 encoder->audio->frame_size = 1;
230 }
231 encoder->audioFrame->nb_samples = encoder->audio->frame_size;
232 encoder->audioFrame->format = encoder->audio->sample_fmt;
233 encoder->audioFrame->pts = 0;
234 encoder->resampleContext = avresample_alloc_context();
235 av_opt_set_int(encoder->resampleContext, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
236 av_opt_set_int(encoder->resampleContext, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
237 av_opt_set_int(encoder->resampleContext, "in_sample_rate", PREFERRED_SAMPLE_RATE, 0);
238 av_opt_set_int(encoder->resampleContext, "out_sample_rate", encoder->sampleRate, 0);
239 av_opt_set_int(encoder->resampleContext, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
240 av_opt_set_int(encoder->resampleContext, "out_sample_fmt", encoder->sampleFormat, 0);
241 avresample_open(encoder->resampleContext);
242 encoder->audioBufferSize = (encoder->audioFrame->nb_samples * PREFERRED_SAMPLE_RATE / encoder->sampleRate) * 4;
243 encoder->audioBuffer = av_malloc(encoder->audioBufferSize);
244 encoder->postaudioBufferSize = av_samples_get_buffer_size(0, encoder->audio->channels, encoder->audio->frame_size, encoder->audio->sample_fmt, 0);
245 encoder->postaudioBuffer = av_malloc(encoder->postaudioBufferSize);
246 avcodec_fill_audio_frame(encoder->audioFrame, encoder->audio->channels, encoder->audio->sample_fmt, (const uint8_t*) encoder->postaudioBuffer, encoder->postaudioBufferSize, 0);
247
248 if (encoder->audio->codec->id == AV_CODEC_ID_AAC &&
249 (strcasecmp(encoder->containerFormat, "mp4") ||
250 strcasecmp(encoder->containerFormat, "m4v") ||
251 strcasecmp(encoder->containerFormat, "mov"))) {
252 // MP4 container doesn't support the raw ADTS AAC format that the encoder spits out
253 encoder->absf = av_bitstream_filter_init("aac_adtstoasc");
254 }
255 }
256
257 encoder->videoStream = avformat_new_stream(encoder->context, vcodec);
258 encoder->video = encoder->videoStream->codec;
259 encoder->video->bit_rate = encoder->videoBitrate;
260 encoder->video->width = encoder->width;
261 encoder->video->height = encoder->height;
262 encoder->video->time_base = (AVRational) { VIDEO_TOTAL_LENGTH, GBA_ARM7TDMI_FREQUENCY };
263 encoder->video->pix_fmt = encoder->pixFormat;
264 encoder->video->gop_size = 60;
265 encoder->video->max_b_frames = 3;
266 if (encoder->context->oformat->flags & AVFMT_GLOBALHEADER) {
267 encoder->video->flags |= CODEC_FLAG_GLOBAL_HEADER;
268 }
269 if (strcmp(vcodec->name, "libx264") == 0) {
270 // Try to adaptively figure out when you can use a slower encoder
271 if (encoder->width * encoder->height > 1000000) {
272 av_opt_set(encoder->video->priv_data, "preset", "superfast", 0);
273 } else if (encoder->width * encoder->height > 500000) {
274 av_opt_set(encoder->video->priv_data, "preset", "veryfast", 0);
275 } else {
276 av_opt_set(encoder->video->priv_data, "preset", "faster", 0);
277 }
278 av_opt_set(encoder->video->priv_data, "tune", "zerolatency", 0);
279 }
280 avcodec_open2(encoder->video, vcodec, 0);
281#if LIBAVCODEC_VERSION_MAJOR >= 55
282 encoder->videoFrame = av_frame_alloc();
283#else
284 encoder->videoFrame = avcodec_alloc_frame();
285#endif
286 encoder->videoFrame->format = encoder->video->pix_fmt;
287 encoder->videoFrame->width = encoder->video->width;
288 encoder->videoFrame->height = encoder->video->height;
289 encoder->videoFrame->pts = 0;
290 encoder->scaleContext = sws_getContext(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS,
291#ifdef COLOR_16_BIT
292#ifdef COLOR_5_6_5
293 AV_PIX_FMT_RGB565,
294#else
295 AV_PIX_FMT_BGR555,
296#endif
297#else
298#ifndef USE_LIBAV
299 AV_PIX_FMT_0BGR32,
300#else
301 AV_PIX_FMT_BGR32,
302#endif
303#endif
304 encoder->videoFrame->width, encoder->videoFrame->height, encoder->video->pix_fmt,
305 SWS_POINT, 0, 0, 0);
306 av_image_alloc(encoder->videoFrame->data, encoder->videoFrame->linesize, encoder->video->width, encoder->video->height, encoder->video->pix_fmt, 32);
307
308 avio_open(&encoder->context->pb, outfile, AVIO_FLAG_WRITE);
309 avformat_write_header(encoder->context, 0);
310
311 return true;
312}
313
314void FFmpegEncoderClose(struct FFmpegEncoder* encoder) {
315 if (!encoder->context) {
316 return;
317 }
318 av_write_trailer(encoder->context);
319 avio_close(encoder->context->pb);
320
321 if (encoder->audioCodec) {
322 av_free(encoder->postaudioBuffer);
323 if (encoder->audioBuffer) {
324 av_free(encoder->audioBuffer);
325 }
326#if LIBAVCODEC_VERSION_MAJOR >= 55
327 av_frame_free(&encoder->audioFrame);
328#else
329 avcodec_free_frame(&encoder->audioFrame);
330#endif
331 avcodec_close(encoder->audio);
332
333 if (encoder->resampleContext) {
334 avresample_close(encoder->resampleContext);
335 }
336
337 if (encoder->absf) {
338 av_bitstream_filter_close(encoder->absf);
339 encoder->absf = 0;
340 }
341 }
342
343#if LIBAVCODEC_VERSION_MAJOR >= 55
344 av_frame_free(&encoder->videoFrame);
345#else
346 avcodec_free_frame(&encoder->videoFrame);
347#endif
348 avcodec_close(encoder->video);
349
350 sws_freeContext(encoder->scaleContext);
351
352 avformat_free_context(encoder->context);
353 encoder->context = 0;
354}
355
356bool FFmpegEncoderIsOpen(struct FFmpegEncoder* encoder) {
357 return !!encoder->context;
358}
359
360void _ffmpegPostAudioFrame(struct GBAAVStream* stream, int32_t left, int32_t right) {
361 struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
362 if (!encoder->context || !encoder->audioCodec) {
363 return;
364 }
365
366 encoder->audioBuffer[encoder->currentAudioSample * 2] = left;
367 encoder->audioBuffer[encoder->currentAudioSample * 2 + 1] = right;
368
369 ++encoder->currentAudioFrame;
370 ++encoder->currentAudioSample;
371
372 if ((encoder->currentAudioSample * 4) < encoder->audioBufferSize) {
373 return;
374 }
375 encoder->currentAudioSample = 0;
376
377 int channelSize = 2 * av_get_bytes_per_sample(encoder->audio->sample_fmt);
378 avresample_convert(encoder->resampleContext,
379 0, 0, 0,
380 (uint8_t**) &encoder->audioBuffer, 0, encoder->audioBufferSize / 4);
381 if (avresample_available(encoder->resampleContext) < encoder->audioFrame->nb_samples) {
382 return;
383 }
384#if LIBAVCODEC_VERSION_MAJOR >= 55
385 av_frame_make_writable(encoder->audioFrame);
386#endif
387 avresample_read(encoder->resampleContext, encoder->audioFrame->data, encoder->postaudioBufferSize / channelSize);
388
389 AVRational timeBase = { 1, PREFERRED_SAMPLE_RATE };
390 encoder->audioFrame->pts = encoder->nextAudioPts;
391 encoder->nextAudioPts = av_rescale_q(encoder->currentAudioFrame, timeBase, encoder->audioStream->time_base);
392
393 AVPacket packet;
394 av_init_packet(&packet);
395 packet.data = 0;
396 packet.size = 0;
397 int gotData;
398 avcodec_encode_audio2(encoder->audio, &packet, encoder->audioFrame, &gotData);
399 if (gotData) {
400 if (encoder->absf) {
401 AVPacket tempPacket = packet;
402 int success = av_bitstream_filter_filter(encoder->absf, encoder->audio, 0,
403 &tempPacket.data, &tempPacket.size,
404 packet.data, packet.size, 0);
405 if (success > 0) {
406#if LIBAVUTIL_VERSION_MAJOR >= 53
407 tempPacket.buf = av_buffer_create(tempPacket.data, tempPacket.size, av_buffer_default_free, 0, 0);
408#endif
409 av_free_packet(&packet);
410 }
411 packet = tempPacket;
412 }
413 packet.stream_index = encoder->audioStream->index;
414 av_interleaved_write_frame(encoder->context, &packet);
415 }
416 av_free_packet(&packet);
417}
418
419void _ffmpegPostVideoFrame(struct GBAAVStream* stream, struct GBAVideoRenderer* renderer) {
420 struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
421 if (!encoder->context) {
422 return;
423 }
424 uint8_t* pixels;
425 unsigned stride;
426 renderer->getPixels(renderer, &stride, (void**) &pixels);
427 stride *= BYTES_PER_PIXEL;
428
429 AVPacket packet;
430
431 av_init_packet(&packet);
432 packet.data = 0;
433 packet.size = 0;
434#if LIBAVCODEC_VERSION_MAJOR >= 55
435 av_frame_make_writable(encoder->videoFrame);
436#endif
437 encoder->videoFrame->pts = av_rescale_q(encoder->currentVideoFrame, encoder->video->time_base, encoder->videoStream->time_base);
438 ++encoder->currentVideoFrame;
439
440 sws_scale(encoder->scaleContext, (const uint8_t* const*) &pixels, (const int*) &stride, 0, VIDEO_VERTICAL_PIXELS, encoder->videoFrame->data, encoder->videoFrame->linesize);
441
442 int gotData;
443 avcodec_encode_video2(encoder->video, &packet, encoder->videoFrame, &gotData);
444 if (gotData) {
445 if (encoder->videoStream->codec->coded_frame->key_frame) {
446 packet.flags |= AV_PKT_FLAG_KEY;
447 }
448 packet.stream_index = encoder->videoStream->index;
449 av_interleaved_write_frame(encoder->context, &packet);
450 }
451 av_free_packet(&packet);
452}