all repos — mgba @ ec0b206fee166975fdb3667dee22da0ce50a1107

mGBA Game Boy Advance Emulator

src/platform/ffmpeg/ffmpeg-encoder.c (view raw)

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