FaadDecoderPlugin.cxx 10.9 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 The Music Player Daemon Project
3 4
 * http://www.musicpd.org
 *
5 6 7 8 9 10 11 12 13
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h"
21
#include "FaadDecoderPlugin.hxx"
22 23
#include "../DecoderAPI.hxx"
#include "../DecoderBuffer.hxx"
Max Kellermann's avatar
Max Kellermann committed
24
#include "input/InputStream.hxx"
25
#include "CheckAudioFormat.hxx"
26
#include "tag/TagHandler.hxx"
27
#include "util/ConstBuffer.hxx"
28 29
#include "util/Error.hxx"
#include "util/Domain.hxx"
30
#include "Log.hxx"
31

32 33
#include <neaacdec.h>

34
#include <assert.h>
Max Kellermann's avatar
Max Kellermann committed
35
#include <string.h>
36 37
#include <unistd.h>

Max Kellermann's avatar
Max Kellermann committed
38
static const unsigned adts_sample_rates[] =
Avuton Olrich's avatar
Avuton Olrich committed
39 40 41
    { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
	16000, 12000, 11025, 8000, 7350, 0, 0, 0
};
42

43
static constexpr Domain faad_decoder_domain("faad_decoder");
44

45 46 47 48
/**
 * Check whether the buffer head is an AAC frame, and return the frame
 * length.  Returns 0 if it is not a frame.
 */
Max Kellermann's avatar
Max Kellermann committed
49
static size_t
50
adts_check_frame(const unsigned char *data)
51 52
{
	/* check syncword */
53
	if (!((data[0] == 0xFF) && ((data[1] & 0xF6) == 0xF0)))
54 55
		return 0;

56 57 58
	return (((unsigned int)data[3] & 0x3) << 11) |
		(((unsigned int)data[4]) << 3) |
		(data[5] >> 5);
59 60
}

Max Kellermann's avatar
Max Kellermann committed
61 62 63 64
/**
 * Find the next AAC frame in the buffer.  Returns 0 if no frame is
 * found or if not enough data is available.
 */
Max Kellermann's avatar
Max Kellermann committed
65
static size_t
66
adts_find_frame(DecoderBuffer &buffer)
Max Kellermann's avatar
Max Kellermann committed
67
{
68
	while (true) {
69
		auto data = ConstBuffer<uint8_t>::FromVoid(buffer.Need(8));
70 71 72
		if (data.IsNull())
			/* failed */
			return 0;
Max Kellermann's avatar
Max Kellermann committed
73

74
		/* find the 0xff marker */
75 76
		const uint8_t *p = (const uint8_t *)
			memchr(data.data, 0xff, data.size);
77
		if (p == nullptr) {
78
			/* no marker - discard the buffer */
79
			buffer.Clear();
80 81 82
			continue;
		}

83
		if (p > data.data) {
84
			/* discard data before 0xff */
85
			buffer.Consume(p - data.data);
86 87
			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
88 89

		/* is it a frame? */
Max Kellermann's avatar
Max Kellermann committed
90
		const size_t frame_length = adts_check_frame(data.data);
91 92 93
		if (frame_length == 0) {
			/* it's just some random 0xff byte; discard it
			   and continue searching */
94
			buffer.Consume(1);
95 96 97
			continue;
		}

98
		if (buffer.Need(frame_length).IsNull()) {
99 100
			/* not enough data; discard this frame to
			   prevent a possible buffer overflow */
101
			buffer.Clear();
102 103
			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
104

105 106 107
		/* found a full frame! */
		return frame_length;
	}
Max Kellermann's avatar
Max Kellermann committed
108 109
}

110
static SignedSongTime
111
adts_song_duration(DecoderBuffer &buffer)
Avuton Olrich's avatar
Avuton Olrich committed
112
{
113
	const InputStream &is = buffer.GetStream();
114
	const bool estimate = !is.CheapSeeking();
115
	if (estimate && !is.KnownSize())
116
		return SignedSongTime::Negative();
117

118
	unsigned sample_rate = 0;
119 120

	/* Read all frames to ensure correct time and bitrate */
121 122
	unsigned frames = 0;
	for (;; frames++) {
123
		const unsigned frame_length = adts_find_frame(buffer);
124 125
		if (frame_length == 0)
			break;
126

127
		if (frames == 0) {
128
			auto data = ConstBuffer<uint8_t>::FromVoid(buffer.Read());
129 130
			assert(!data.IsEmpty());
			assert(frame_length <= data.size);
131

132
			sample_rate = adts_sample_rates[(data.data[2] & 0x3c) >> 2];
133 134
			if (sample_rate == 0)
				break;
135 136
		}

137
		buffer.Consume(frame_length);
138 139 140 141 142 143 144 145 146

		if (estimate && frames == 128) {
			/* if this is a remote file, don't slurp the
			   whole file just for checking the song
			   duration; instead, stop after some time and
			   extrapolate the song duration from what we
			   have until now */

			const auto offset = is.GetOffset()
147
				- buffer.GetAvailable();
148
			if (offset <= 0)
149
				return SignedSongTime::Negative();
150

151
			const auto file_size = is.GetSize();
152 153 154
			frames = (frames * file_size) / offset;
			break;
		}
155 156
	}

157
	if (sample_rate == 0)
158
		return SignedSongTime::Negative();
159

160 161
	return SignedSongTime::FromScale<uint64_t>(frames * uint64_t(1024),
						   sample_rate);
162 163
}

164
static SignedSongTime
165
faad_song_duration(DecoderBuffer &buffer, InputStream &is)
166
{
167
	auto data = ConstBuffer<uint8_t>::FromVoid(buffer.Need(5));
168
	if (data.IsNull())
169
		return SignedSongTime::Negative();
170

171
	size_t tagsize = 0;
172
	if (data.size >= 10 && !memcmp(data.data, "ID3", 3)) {
173 174
		/* skip the ID3 tag */

175 176
		tagsize = (data.data[6] << 21) | (data.data[7] << 14) |
		    (data.data[8] << 7) | (data.data[9] << 0);
177

Avuton Olrich's avatar
Avuton Olrich committed
178
		tagsize += 10;
179

180
		if (!buffer.Skip(tagsize))
181
			return SignedSongTime::Negative();
182

183
		data = ConstBuffer<uint8_t>::FromVoid(buffer.Need(5));
184
		if (data.IsNull())
185
			return SignedSongTime::Negative();
186 187
	}

Max Kellermann's avatar
Max Kellermann committed
188
	if (data.size >= 8 && adts_check_frame(data.data) > 0) {
189
		/* obtain the duration from the ADTS header */
190 191

		if (!is.IsSeekable())
192
			return SignedSongTime::Negative();
193

194
		auto song_length = adts_song_duration(buffer);
195

196
		is.LockSeek(tagsize, IgnoreError());
197

198
		buffer.Clear();
199

200
		return song_length;
201
	} else if (data.size >= 5 && memcmp(data.data, "ADIF", 4) == 0) {
202
		/* obtain the duration from the ADIF header */
203 204

		if (!is.KnownSize())
205
			return SignedSongTime::Negative();
206

207
		size_t skip_size = (data.data[4] & 0x80) ? 9 : 0;
208

209
		if (8 + skip_size > data.size)
210 211
			/* not enough data yet; skip parsing this
			   header */
212
			return SignedSongTime::Negative();
213

Max Kellermann's avatar
Max Kellermann committed
214
		unsigned bit_rate = ((data.data[4 + skip_size] & 0x0F) << 19) |
215 216 217
			(data.data[5 + skip_size] << 11) |
			(data.data[6 + skip_size] << 3) |
			(data.data[7 + skip_size] & 0xE0);
Max Kellermann's avatar
Max Kellermann committed
218

219
		const auto size = is.GetSize();
220
		if (bit_rate == 0)
221
			return SignedSongTime::Negative();
222

223
		return SongTime::FromScale(size, bit_rate / 8);
224
	} else
225
		return SignedSongTime::Negative();
226 227
}

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
static NeAACDecHandle
faad_decoder_new()
{
	const NeAACDecHandle decoder = NeAACDecOpen();

	NeAACDecConfigurationPtr config =
		NeAACDecGetCurrentConfiguration(decoder);
	config->outputFormat = FAAD_FMT_16BIT;
	config->downMatrix = 1;
	config->dontUpSampleImplicitSBR = 0;
	NeAACDecSetConfiguration(decoder, config);

	return decoder;
}

243
/**
244
 * Wrapper for NeAACDecInit() which works around some API
245 246 247
 * inconsistencies in libfaad.
 */
static bool
248
faad_decoder_init(NeAACDecHandle decoder, DecoderBuffer &buffer,
249
		  AudioFormat &audio_format, Error &error)
250
{
251
	auto data = ConstBuffer<uint8_t>::FromVoid(buffer.Read());
Max Kellermann's avatar
Max Kellermann committed
252
	if (data.IsEmpty()) {
253
		error.Set(faad_decoder_domain, "Empty file");
254
		return false;
255
	}
256

257
	uint8_t channels;
258
	unsigned long sample_rate;
259 260
	long nbytes = NeAACDecInit(decoder,
				   /* deconst hack, libfaad requires this */
Max Kellermann's avatar
Max Kellermann committed
261 262
				   const_cast<unsigned char *>(data.data),
				   data.size,
263
				   &sample_rate, &channels);
264
	if (nbytes < 0) {
265
		error.Set(faad_decoder_domain, "Not an AAC stream");
266
		return false;
267
	}
268

269
	buffer.Consume(nbytes);
270

271
	return audio_format_init_checked(audio_format, sample_rate,
272
					 SampleFormat::S16, channels, error);
273 274 275
}

/**
276
 * Wrapper for NeAACDecDecode() which works around some API
277 278 279
 * inconsistencies in libfaad.
 */
static const void *
280
faad_decoder_decode(NeAACDecHandle decoder, DecoderBuffer &buffer,
281
		    NeAACDecFrameInfo *frame_info)
282
{
283
	auto data = ConstBuffer<uint8_t>::FromVoid(buffer.Read());
284
	if (data.IsEmpty())
285
		return nullptr;
286

287
	return NeAACDecDecode(decoder, frame_info,
288
			      /* deconst hack, libfaad requires this */
289 290
			      const_cast<uint8_t *>(data.data),
			      data.size);
291 292
}

293
/**
294 295 296 297
 * Determine a song file's total playing time.
 *
 * The first return value specifies whether the file was recognized.
 * The second return value is the duration.
298
 */
299 300
static std::pair<bool, SignedSongTime>
faad_get_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
301
{
302 303
	DecoderBuffer buffer(nullptr, is,
			     FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
304
	auto duration = faad_song_duration(buffer, is);
305
	bool recognized = !duration.IsNegative();
306

307
	if (!recognized) {
308
		NeAACDecHandle decoder = faad_decoder_new();
309

310
		buffer.Fill();
311

312
		AudioFormat audio_format;
313
		if (faad_decoder_init(decoder, buffer, audio_format,
314
				      IgnoreError()))
315
			recognized = true;
316

317
		NeAACDecClose(decoder);
318
	}
319

320
	return std::make_pair(recognized, duration);
321 322
}

323
static void
324
faad_stream_decode(Decoder &mpd_decoder, InputStream &is,
325
		   DecoderBuffer &buffer, const NeAACDecHandle decoder)
326
{
327
	const auto total_time = faad_song_duration(buffer, is);
328

329 330
	if (adts_find_frame(buffer) == 0)
		return;
331

332 333
	/* initialize it */

334
	Error error;
335 336
	AudioFormat audio_format;
	if (!faad_decoder_init(decoder, buffer, audio_format, error)) {
337
		LogError(error);
338 339 340
		return;
	}

341 342
	/* initialize the MPD core */

343
	decoder_initialized(mpd_decoder, audio_format, false, total_time);
344

345 346
	/* the decoder loop */

347
	DecoderCommand cmd;
348
	unsigned bit_rate = 0;
349
	do {
350 351
		/* find the next frame */

352
		const size_t frame_size = adts_find_frame(buffer);
353
		if (frame_size == 0)
354
			/* end of file */
355 356
			break;

357 358
		/* decode it */

359 360 361
		NeAACDecFrameInfo frame_info;
		const void *const decoded =
			faad_decoder_decode(decoder, buffer, &frame_info);
362

Max Kellermann's avatar
Max Kellermann committed
363
		if (frame_info.error > 0) {
364 365 366
			FormatWarning(faad_decoder_domain,
				      "error decoding AAC stream: %s",
				      NeAACDecGetErrorMessage(frame_info.error));
367 368 369
			break;
		}

370
		if (frame_info.channels != audio_format.channels) {
371 372 373
			FormatDefault(faad_decoder_domain,
				      "channel count changed from %u to %u",
				      audio_format.channels, frame_info.channels);
374 375
			break;
		}
376

377
		if (frame_info.samplerate != audio_format.sample_rate) {
378 379 380 381
			FormatDefault(faad_decoder_domain,
				      "sample rate changed from %u to %lu",
				      audio_format.sample_rate,
				      (unsigned long)frame_info.samplerate);
382
			break;
383 384
		}

385
		buffer.Consume(frame_info.bytesconsumed);
386

387 388
		/* update bit rate and position */

Max Kellermann's avatar
Max Kellermann committed
389
		if (frame_info.samples > 0) {
Max Kellermann's avatar
Max Kellermann committed
390
			bit_rate = frame_info.bytesconsumed * 8.0 *
391
			    frame_info.channels * audio_format.sample_rate /
Max Kellermann's avatar
Max Kellermann committed
392
			    frame_info.samples / 1000 + 0.5;
393 394
		}

395 396
		/* send PCM samples to MPD */

Max Kellermann's avatar
Max Kellermann committed
397
		cmd = decoder_data(mpd_decoder, is, decoded,
398
				   (size_t)frame_info.samples * 2,
399
				   bit_rate);
400
	} while (cmd != DecoderCommand::STOP);
401 402 403 404 405
}

static void
faad_stream_decode(Decoder &mpd_decoder, InputStream &is)
{
406 407
	DecoderBuffer buffer(&mpd_decoder, is,
			     FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
408 409 410 411 412

	/* create the libfaad decoder */

	const NeAACDecHandle decoder = faad_decoder_new();

413
	faad_stream_decode(mpd_decoder, is, buffer, decoder);
414

415 416
	/* cleanup */

417
	NeAACDecClose(decoder);
418 419
}

420
static bool
421
faad_scan_stream(InputStream &is,
422
		 const struct tag_handler *handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
423
{
424 425
	auto result = faad_get_file_time(is);
	if (!result.first)
426
		return false;
Warren Dukes's avatar
Warren Dukes committed
427

428 429 430
	if (!result.second.IsNegative())
		tag_handler_invoke_duration(handler, handler_ctx,
					    SongTime(result.second));
431
	return true;
Warren Dukes's avatar
Warren Dukes committed
432 433
}

434
static const char *const faad_suffixes[] = { "aac", nullptr };
Max Kellermann's avatar
Max Kellermann committed
435
static const char *const faad_mime_types[] = {
436
	"audio/aac", "audio/aacp", nullptr
Max Kellermann's avatar
Max Kellermann committed
437
};
Warren Dukes's avatar
Warren Dukes committed
438

439
const DecoderPlugin faad_decoder_plugin = {
440 441 442 443 444 445 446 447 448 449
	"faad",
	nullptr,
	nullptr,
	faad_stream_decode,
	nullptr,
	nullptr,
	faad_scan_stream,
	nullptr,
	faad_suffixes,
	faad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
450
};