FaadDecoderPlugin.cxx 11.5 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 70 71 72
		auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_need(buffer, 8));
		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
			decoder_buffer_clear(buffer);
80 81 82
			continue;
		}

83
		if (p > data.data) {
84
			/* discard data before 0xff */
85
			decoder_buffer_consume(buffer, 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 94 95 96 97
		if (frame_length == 0) {
			/* it's just some random 0xff byte; discard it
			   and continue searching */
			decoder_buffer_consume(buffer, 1);
			continue;
		}

98 99 100 101
		if (decoder_buffer_need(buffer, frame_length).IsNull()) {
			/* not enough data; discard this frame to
			   prevent a possible buffer overflow */
			decoder_buffer_clear(buffer);
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 float
111
adts_song_duration(DecoderBuffer *buffer)
Avuton Olrich's avatar
Avuton Olrich committed
112
{
113 114
	const InputStream &is = decoder_buffer_get_stream(buffer);
	const bool estimate = !is.CheapSeeking();
115
	if (estimate && !is.KnownSize())
116 117
		return -1;

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 129 130
			auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
			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
		}

		decoder_buffer_consume(buffer, frame_length);
138 139 140 141 142 143 144 145 146 147 148 149 150

		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()
				- decoder_buffer_available(buffer);
			if (offset <= 0)
				return -1;

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

157
	if (sample_rate == 0)
158 159
		return -1;

160 161 162
	float frames_per_second = (float)sample_rate / 1024.0;
	assert(frames_per_second > 0);

163
	return (float)frames / frames_per_second;
164 165
}

166
static float
167
faad_song_duration(DecoderBuffer *buffer, InputStream &is)
168
{
169 170
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_need(buffer, 5));
	if (data.IsNull())
171
		return -1;
172

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

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

Avuton Olrich's avatar
Avuton Olrich committed
180
		tagsize += 10;
181

182
		if (!decoder_buffer_skip(buffer, tagsize))
183 184
			return -1;

185 186
		data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_need(buffer, 5));
		if (data.IsNull())
187
			return -1;
188 189
	}

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

		if (!is.IsSeekable())
			return -1;

196
		float song_length = adts_song_duration(buffer);
197

198
		is.LockSeek(tagsize, IgnoreError());
199

200
		decoder_buffer_clear(buffer);
201

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

		if (!is.KnownSize())
			return -1;

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

211
		if (8 + skip_size > data.size)
212 213
			/* not enough data yet; skip parsing this
			   header */
214
			return -1;
215

Max Kellermann's avatar
Max Kellermann committed
216
		unsigned bit_rate = ((data.data[4 + skip_size] & 0x0F) << 19) |
217 218 219
			(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
220

221
		const auto size = is.GetSize();
222
		if (bit_rate != 0)
223
			return size * 8.0 / bit_rate;
224
		else
225
			return size;
226 227
	} else
		return -1;
228 229
}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
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;
}

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

259
	uint8_t channels;
260
	uint32_t sample_rate;
261 262 263 264
#ifdef HAVE_FAAD_LONG
	/* neaacdec.h declares all arguments as "unsigned long", but
	   internally expects uint32_t pointers.  To avoid gcc
	   warnings, use this workaround. */
265
	unsigned long *sample_rate_p = (unsigned long *)(void *)&sample_rate;
266
#else
267
	uint32_t *sample_rate_p = &sample_rate;
268
#endif
269 270
	long nbytes = NeAACDecInit(decoder,
				   /* deconst hack, libfaad requires this */
Max Kellermann's avatar
Max Kellermann committed
271 272
				   const_cast<unsigned char *>(data.data),
				   data.size,
273
				   sample_rate_p, &channels);
274
	if (nbytes < 0) {
275
		error.Set(faad_decoder_domain, "Not an AAC stream");
276
		return false;
277
	}
278

279
	decoder_buffer_consume(buffer, nbytes);
280

281
	return audio_format_init_checked(audio_format, sample_rate,
282
					 SampleFormat::S16, channels, error);
283 284 285
}

/**
286
 * Wrapper for NeAACDecDecode() which works around some API
287 288 289
 * inconsistencies in libfaad.
 */
static const void *
290
faad_decoder_decode(NeAACDecHandle decoder, DecoderBuffer *buffer,
291
		    NeAACDecFrameInfo *frame_info)
292
{
293 294
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
	if (data.IsEmpty())
295
		return nullptr;
296

297
	return NeAACDecDecode(decoder, frame_info,
298
			      /* deconst hack, libfaad requires this */
299 300
			      const_cast<uint8_t *>(data.data),
			      data.size);
301 302
}

303 304 305 306 307
/**
 * Get a song file's total playing time in seconds, as a float.
 * Returns 0 if the duration is unknown, and a negative value if the
 * file is invalid.
 */
Max Kellermann's avatar
Max Kellermann committed
308
static float
309
faad_get_file_time_float(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
310
{
311 312
	DecoderBuffer *buffer =
		decoder_buffer_new(nullptr, is,
313
				   FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
314
	float length = faad_song_duration(buffer, is);
315

Avuton Olrich's avatar
Avuton Olrich committed
316
	if (length < 0) {
317
		NeAACDecHandle decoder = faad_decoder_new();
318

319
		decoder_buffer_fill(buffer);
320

321 322 323
		AudioFormat audio_format;
		if (faad_decoder_init(decoder, buffer, audio_format,
				      IgnoreError()))
Avuton Olrich's avatar
Avuton Olrich committed
324
			length = 0;
325

326
		NeAACDecClose(decoder);
327
	}
328

329
	decoder_buffer_free(buffer);
330

331 332 333
	return length;
}

334 335 336 337 338
/**
 * Get a song file's total playing time in seconds, as an int.
 * Returns 0 if the duration is unknown, and a negative value if the
 * file is invalid.
 */
Max Kellermann's avatar
Max Kellermann committed
339
static int
340
faad_get_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
341
{
342 343 344
	float length = faad_get_file_time_float(is);
	if (length < 0)
		return -1;
345

346
	return int(length + 0.5);
347 348
}

349
static void
350 351
faad_stream_decode(Decoder &mpd_decoder, InputStream &is,
		   DecoderBuffer *buffer, const NeAACDecHandle decoder)
352
{
353
	const float total_time = faad_song_duration(buffer, is);
354

355 356
	if (adts_find_frame(buffer) == 0)
		return;
357

358 359
	/* initialize it */

360
	Error error;
361 362
	AudioFormat audio_format;
	if (!faad_decoder_init(decoder, buffer, audio_format, error)) {
363
		LogError(error);
364 365 366
		return;
	}

367 368
	/* initialize the MPD core */

369
	decoder_initialized(mpd_decoder, audio_format, false, total_time);
370

371 372
	/* the decoder loop */

373
	DecoderCommand cmd;
374
	unsigned bit_rate = 0;
375
	do {
376 377
		/* find the next frame */

378
		const size_t frame_size = adts_find_frame(buffer);
379
		if (frame_size == 0)
380
			/* end of file */
381 382
			break;

383 384
		/* decode it */

385 386 387
		NeAACDecFrameInfo frame_info;
		const void *const decoded =
			faad_decoder_decode(decoder, buffer, &frame_info);
388

Max Kellermann's avatar
Max Kellermann committed
389
		if (frame_info.error > 0) {
390 391 392
			FormatWarning(faad_decoder_domain,
				      "error decoding AAC stream: %s",
				      NeAACDecGetErrorMessage(frame_info.error));
393 394 395
			break;
		}

396
		if (frame_info.channels != audio_format.channels) {
397 398 399
			FormatDefault(faad_decoder_domain,
				      "channel count changed from %u to %u",
				      audio_format.channels, frame_info.channels);
400 401
			break;
		}
402

403
		if (frame_info.samplerate != audio_format.sample_rate) {
404 405 406 407
			FormatDefault(faad_decoder_domain,
				      "sample rate changed from %u to %lu",
				      audio_format.sample_rate,
				      (unsigned long)frame_info.samplerate);
408
			break;
409 410
		}

411
		decoder_buffer_consume(buffer, frame_info.bytesconsumed);
412

413 414
		/* update bit rate and position */

Max Kellermann's avatar
Max Kellermann committed
415
		if (frame_info.samples > 0) {
Max Kellermann's avatar
Max Kellermann committed
416
			bit_rate = frame_info.bytesconsumed * 8.0 *
417
			    frame_info.channels * audio_format.sample_rate /
Max Kellermann's avatar
Max Kellermann committed
418
			    frame_info.samples / 1000 + 0.5;
419 420
		}

421 422
		/* send PCM samples to MPD */

Max Kellermann's avatar
Max Kellermann committed
423
		cmd = decoder_data(mpd_decoder, is, decoded,
424
				   (size_t)frame_info.samples * 2,
425
				   bit_rate);
426
	} while (cmd != DecoderCommand::STOP);
427 428 429 430 431 432 433 434 435 436 437 438 439 440
}

static void
faad_stream_decode(Decoder &mpd_decoder, InputStream &is)
{
	DecoderBuffer *buffer =
		decoder_buffer_new(&mpd_decoder, is,
				   FAAD_MIN_STREAMSIZE * MAX_CHANNELS);

	/* create the libfaad decoder */

	const NeAACDecHandle decoder = faad_decoder_new();

	faad_stream_decode(mpd_decoder, is, buffer, decoder);
441

442 443
	/* cleanup */

444
	NeAACDecClose(decoder);
445
	decoder_buffer_free(buffer);
446 447
}

448
static bool
449
faad_scan_stream(InputStream &is,
450
		 const struct tag_handler *handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
451
{
452 453
	int file_time = faad_get_file_time(is);
	if (file_time < 0)
454
		return false;
Warren Dukes's avatar
Warren Dukes committed
455

456 457
	tag_handler_invoke_duration(handler, handler_ctx, file_time);
	return true;
Warren Dukes's avatar
Warren Dukes committed
458 459
}

460
static const char *const faad_suffixes[] = { "aac", nullptr };
Max Kellermann's avatar
Max Kellermann committed
461
static const char *const faad_mime_types[] = {
462
	"audio/aac", "audio/aacp", nullptr
Max Kellermann's avatar
Max Kellermann committed
463
};
Warren Dukes's avatar
Warren Dukes committed
464

465
const DecoderPlugin faad_decoder_plugin = {
466 467 468 469 470 471 472 473 474 475
	"faad",
	nullptr,
	nullptr,
	faad_stream_decode,
	nullptr,
	nullptr,
	faad_scan_stream,
	nullptr,
	faad_suffixes,
	faad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
476
};