all repos — mgba @ 7149dd3102a6bbb7f73cae7da0c01dc784b0f601

mGBA Game Boy Advance Emulator

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#ifndef USE_LIBAV
292		AV_PIX_FMT_0BGR32,
293#else
294		AV_PIX_FMT_BGR32,
295#endif
296		encoder->videoFrame->width, encoder->videoFrame->height, encoder->video->pix_fmt,
297		SWS_POINT, 0, 0, 0);
298	av_image_alloc(encoder->videoFrame->data, encoder->videoFrame->linesize, encoder->video->width, encoder->video->height, encoder->video->pix_fmt, 32);
299
300	avio_open(&encoder->context->pb, outfile, AVIO_FLAG_WRITE);
301	avformat_write_header(encoder->context, 0);
302
303	return true;
304}
305
306void FFmpegEncoderClose(struct FFmpegEncoder* encoder) {
307	if (!encoder->context) {
308		return;
309	}
310	av_write_trailer(encoder->context);
311	avio_close(encoder->context->pb);
312
313	if (encoder->audioCodec) {
314		av_free(encoder->postaudioBuffer);
315		if (encoder->audioBuffer) {
316			av_free(encoder->audioBuffer);
317		}
318#if LIBAVCODEC_VERSION_MAJOR >= 55
319		av_frame_free(&encoder->audioFrame);
320#else
321		avcodec_free_frame(&encoder->audioFrame);
322#endif
323		avcodec_close(encoder->audio);
324
325		if (encoder->resampleContext) {
326			avresample_close(encoder->resampleContext);
327		}
328
329		if (encoder->absf) {
330			av_bitstream_filter_close(encoder->absf);
331			encoder->absf = 0;
332		}
333	}
334
335#if LIBAVCODEC_VERSION_MAJOR >= 55
336	av_frame_free(&encoder->videoFrame);
337#else
338	avcodec_free_frame(&encoder->videoFrame);
339#endif
340	avcodec_close(encoder->video);
341
342	sws_freeContext(encoder->scaleContext);
343
344	avformat_free_context(encoder->context);
345	encoder->context = 0;
346}
347
348bool FFmpegEncoderIsOpen(struct FFmpegEncoder* encoder) {
349	return !!encoder->context;
350}
351
352void _ffmpegPostAudioFrame(struct GBAAVStream* stream, int32_t left, int32_t right) {
353	struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
354	if (!encoder->context || !encoder->audioCodec) {
355		return;
356	}
357
358	encoder->audioBuffer[encoder->currentAudioSample * 2] = left;
359	encoder->audioBuffer[encoder->currentAudioSample * 2 + 1] = right;
360
361	++encoder->currentAudioFrame;
362	++encoder->currentAudioSample;
363
364	if ((encoder->currentAudioSample * 4) < encoder->audioBufferSize) {
365		return;
366	}
367	encoder->currentAudioSample = 0;
368
369	int channelSize = 2 * av_get_bytes_per_sample(encoder->audio->sample_fmt);
370	avresample_convert(encoder->resampleContext,
371		0, 0, 0,
372		(uint8_t**) &encoder->audioBuffer, 0, encoder->audioBufferSize / 4);
373	if (avresample_available(encoder->resampleContext) < encoder->audioFrame->nb_samples) {
374		return;
375	}
376#if LIBAVCODEC_VERSION_MAJOR >= 55
377	av_frame_make_writable(encoder->audioFrame);
378#endif
379	avresample_read(encoder->resampleContext, encoder->audioFrame->data, encoder->postaudioBufferSize / channelSize);
380
381	AVRational timeBase = { 1, PREFERRED_SAMPLE_RATE };
382	encoder->audioFrame->pts = encoder->nextAudioPts;
383	encoder->nextAudioPts = av_rescale_q(encoder->currentAudioFrame, timeBase, encoder->audioStream->time_base);
384
385	AVPacket packet;
386	av_init_packet(&packet);
387	packet.data = 0;
388	packet.size = 0;
389	int gotData;
390	avcodec_encode_audio2(encoder->audio, &packet, encoder->audioFrame, &gotData);
391	if (gotData) {
392		if (encoder->absf) {
393			AVPacket tempPacket = packet;
394			int success = av_bitstream_filter_filter(encoder->absf, encoder->audio, 0,
395				&tempPacket.data, &tempPacket.size,
396				packet.data, packet.size, 0);
397			if (success > 0) {
398#if LIBAVUTIL_VERSION_MAJOR >= 53
399				tempPacket.buf = av_buffer_create(tempPacket.data, tempPacket.size, av_buffer_default_free, 0, 0);
400#endif
401				av_free_packet(&packet);
402			}
403			packet = tempPacket;
404		}
405		packet.stream_index = encoder->audioStream->index;
406		av_interleaved_write_frame(encoder->context, &packet);
407	}
408	av_free_packet(&packet);
409}
410
411void _ffmpegPostVideoFrame(struct GBAAVStream* stream, struct GBAVideoRenderer* renderer) {
412	struct FFmpegEncoder* encoder = (struct FFmpegEncoder*) stream;
413	if (!encoder->context) {
414		return;
415	}
416	uint8_t* pixels;
417	unsigned stride;
418	renderer->getPixels(renderer, &stride, (void**) &pixels);
419	stride *= 4;
420
421	AVPacket packet;
422
423	av_init_packet(&packet);
424	packet.data = 0;
425	packet.size = 0;
426#if LIBAVCODEC_VERSION_MAJOR >= 55
427	av_frame_make_writable(encoder->videoFrame);
428#endif
429	encoder->videoFrame->pts = av_rescale_q(encoder->currentVideoFrame, encoder->video->time_base, encoder->videoStream->time_base);
430	++encoder->currentVideoFrame;
431
432	sws_scale(encoder->scaleContext, (const uint8_t* const*) &pixels, (const int*) &stride, 0, VIDEO_VERTICAL_PIXELS, encoder->videoFrame->data, encoder->videoFrame->linesize);
433
434	int gotData;
435	avcodec_encode_video2(encoder->video, &packet, encoder->videoFrame, &gotData);
436	if (gotData) {
437		if (encoder->videoStream->codec->coded_frame->key_frame) {
438			packet.flags |= AV_PKT_FLAG_KEY;
439		}
440		packet.stream_index = encoder->videoStream->index;
441		av_interleaved_write_frame(encoder->context, &packet);
442	}
443	av_free_packet(&packet);
444}