File: AudioDecoder.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-3
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,740 kB
  • sloc: cpp: 595,005; ansic: 21,741; python: 1,174; sh: 457; makefile: 243; xml: 181
file content (230 lines) | stat: -rw-r--r-- 6,503 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#include "cutscene/ffmpeg/AudioDecoder.h"

#include "tracing/tracing.h"

namespace {
const int OUT_CH_LAYOUT = AV_CH_LAYOUT_STEREO;
const int OUT_SAMPLE_RATE = 48000;
const AVSampleFormat OUT_SAMPLE_FORMAT = AV_SAMPLE_FMT_S16;
const int OUT_NUM_CHANNELS = av_popcount64(OUT_CH_LAYOUT);

const int DEFAULT_SRC_NUM_SAMPLES = 1024;

SwrContext* getSWRContext(uint64_t layout, int rate, AVSampleFormat inFmt) {
	auto swr = swr_alloc();

	av_opt_set_int(swr, "in_channel_layout", layout, 0);
	av_opt_set_int(swr, "in_sample_rate", rate, 0);
	av_opt_set_int(swr, "in_sample_fmt", inFmt, 0);

	av_opt_set_int(swr, "out_channel_layout", OUT_CH_LAYOUT, 0);
	av_opt_set_int(swr, "out_sample_rate", OUT_SAMPLE_RATE, 0);
	av_opt_set_int(swr, "out_sample_fmt", OUT_SAMPLE_FORMAT, 0);

	swr_init(swr);

	return swr;
}

int alloc_array_and_samples(uint8_t*** outData, int* linesize, int channels, int samples, AVSampleFormat format) {
	auto planes = av_sample_fmt_is_planar(format) ? channels : 1;

	*outData = reinterpret_cast<uint8_t**>(av_mallocz(planes * sizeof(**outData)));


	auto ret = av_samples_alloc(*outData, linesize, channels, samples, format, 0);

	if (ret < 0) {
		av_freep(outData);
	}

	return ret;
}

int64_t getDelay(SwrContext* ctx, int64_t sampleRate) {
#ifdef WITH_LIBAV
	return avresample_get_delay(ctx);
#else
	return swr_get_delay(ctx, sampleRate);
#endif
}

int resample_convert(SwrContext* ctx, uint8_t** output,
					 int out_plane_size, int out_samples, uint8_t** input,
					 int in_plane_size, int in_samples) {
#ifdef WITH_LIBAV
	return avresample_convert(ctx, output, out_plane_size, out_samples, input, in_plane_size, in_samples);
#else
	(void)out_plane_size;
	(void)in_plane_size;

	return swr_convert(ctx, output, out_samples, (const uint8_t**) input, in_samples);
#endif
}
}

namespace cutscene {
namespace ffmpeg {
AudioDecoder::AudioDecoder(DecoderStatus* status)
	: FFMPEGStreamDecoder(status) {
	m_audioBuffer.reserve(static_cast<size_t>(OUT_SAMPLE_RATE * OUT_NUM_CHANNELS / 2));

	m_resampleCtx = getSWRContext(m_status->audioCodecPars.channel_layout, m_status->audioCodecPars.sample_rate,
								  m_status->audioCodecPars.audio_format);

	/*
    * compute the number of converted samples: buffering is avoided
    * ensuring that the output buffer will contain at least all the
    * converted input samples
    */
	m_maxOutNumSamples = m_outNumSamples = static_cast<int>(av_rescale_rnd(DEFAULT_SRC_NUM_SAMPLES,
																		   OUT_SAMPLE_RATE,
																		   m_status->audioCodecPars.sample_rate,
																		   AV_ROUND_UP));

	auto ret = alloc_array_and_samples(&m_outData, &m_outLinesize, OUT_NUM_CHANNELS,
									   m_outNumSamples, OUT_SAMPLE_FORMAT);

	if (ret < 0) {
		mprintf(("FFMPEG: Failed to allocate samples array!\n"));
	}
}

AudioDecoder::~AudioDecoder() {
	if (m_outData) {
		av_freep(&m_outData[0]);
	}
	av_freep(&m_outData);

	swr_free(&m_resampleCtx);
}

void AudioDecoder::flushAudioBuffer() {
	if (m_audioBuffer.empty()) {
		// Nothing to do here
		return;
	}

	AudioFramePtr audioFrame(new AudioFrame());
	audioFrame->channels = OUT_NUM_CHANNELS;
	audioFrame->rate = OUT_SAMPLE_RATE;

	audioFrame->audioData.assign(m_audioBuffer.begin(), m_audioBuffer.end());

	pushFrame(std::move(audioFrame));
	m_audioBuffer.clear();
}

void AudioDecoder::handleDecodedFrame(AVFrame* frame) {
	/* compute destination number of samples */
	m_outNumSamples = static_cast<int>(av_rescale_rnd(getDelay(m_resampleCtx, frame->sample_rate)
														  + frame->nb_samples, OUT_SAMPLE_RATE, frame->sample_rate,
													  AV_ROUND_UP));

	if (m_outNumSamples > m_maxOutNumSamples) {
		av_freep(&m_outData[0]);
		auto ret = av_samples_alloc(m_outData, &m_outLinesize, OUT_NUM_CHANNELS, m_outNumSamples,
									OUT_SAMPLE_FORMAT, 1);
		if (ret < 0) {
			mprintf(("FFMPEG: Failed to allocate samples!!!\n"));
			return;
		}

		m_maxOutNumSamples = m_outNumSamples;
	}

	/* convert to destination format */
	auto ret = resample_convert(m_resampleCtx, m_outData, 0, m_outNumSamples,
								(uint8_t**) frame->data, 0, frame->nb_samples);
	if (ret < 0) {
		mprintf(("FFMPEG: Error while converting audio!\n"));
		return;
	}

	auto outBufsize = av_samples_get_buffer_size(&m_outLinesize, OUT_NUM_CHANNELS, ret, OUT_SAMPLE_FORMAT, 1);
	if (outBufsize < 0) {
		mprintf(("FFMPEG: Could not get sample buffer size!\n"));
		return;
	}

	auto begin = reinterpret_cast<short*>(m_outData[0]);
	auto end = reinterpret_cast<short*>(m_outData[0] + outBufsize);

	auto size = std::distance(begin, end);
	auto newSize = m_audioBuffer.size() + size;

	if (newSize <= m_audioBuffer.capacity()) {
		// We haven't filled the buffer yet
		m_audioBuffer.insert(m_audioBuffer.end(), begin, end);
	} else {
		flushAudioBuffer();
		m_audioBuffer.assign(begin, end);
	}
}

void AudioDecoder::decodePacket(AVPacket* packet) {
	TRACE_SCOPE(tracing::CutsceneFFmpegAudioDecoder);
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(57, 24, 255)
	int send_result;
	do {
		send_result = avcodec_send_packet(m_status->audioCodecCtx, packet);

		while (avcodec_receive_frame(m_status->audioCodecCtx, m_decodeFrame) == 0) {
			handleDecodedFrame(m_decodeFrame);
		}
	} while (send_result == AVERROR(EAGAIN));
#else
	int finishedFrame = 0;
	auto err = avcodec_decode_audio4(m_status->audioCodecCtx, m_decodeFrame, &finishedFrame, packet);

	if (err >= 0 && finishedFrame) {
		handleDecodedFrame(m_decodeFrame);
	}
#endif
}

void AudioDecoder::finishDecoding() {
	TRACE_SCOPE(tracing::CutsceneFFmpegAudioDecoder);
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(57, 24, 255)
	// Send flush packet
	avcodec_send_packet(m_status->audioCodecCtx, nullptr);

	// Handle those decoders that have a delay
	while (true) {
		auto ret = avcodec_receive_frame(m_status->audioCodecCtx, m_decodeFrame);

		if (ret == 0) {
			handleDecodedFrame(m_decodeFrame);
		}
		else {
			// Everything consumed or error
			break;
		}
	}
#else
    // Handle those decoders that have a delay
	AVPacket nullPacket;
	memset(&nullPacket, 0, sizeof(nullPacket));
	nullPacket.data = nullptr;
	nullPacket.size = 0;

	while (true) {
		int finishedFrame = 1;
		auto err = avcodec_decode_audio4(m_status->audioCodecCtx, m_decodeFrame, &finishedFrame, &nullPacket);

		if (err < 0 || !finishedFrame) {
			break;
		}

		handleDecodedFrame(m_decodeFrame);
	}
#endif

	// Push the last bits of audio data into the queue
	flushAudioBuffer();
}
void AudioDecoder::flushBuffers() {
	avcodec_flush_buffers(m_status->audioCodecCtx);
}
}
}