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 115 116 117 118
	const InputStream &is = decoder_buffer_get_stream(buffer);
	const bool estimate = !is.CheapSeeking();
	const auto file_size = is.GetSize();
	if (estimate && file_size <= 0)
		return -1;

119
	unsigned sample_rate = 0;
120 121

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

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

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

		decoder_buffer_consume(buffer, frame_length);
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

		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;

			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
	const auto size = is.GetSize();
170
	const size_t fileread = size >= 0 ? size : 0;
171

172 173
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_need(buffer, 5));
	if (data.IsNull())
174
		return -1;
175

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

180 181
		tagsize = (data.data[6] << 21) | (data.data[7] << 14) |
		    (data.data[8] << 7) | (data.data[9] << 0);
182

Avuton Olrich's avatar
Avuton Olrich committed
183
		tagsize += 10;
184

185
		if (!decoder_buffer_skip(buffer, tagsize))
186 187
			return -1;

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

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

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

199
		float song_length = adts_song_duration(buffer);
200

201
		is.LockSeek(tagsize, IgnoreError());
202

203
		decoder_buffer_clear(buffer);
204

205
		return song_length;
206
	} else if (data.size >= 5 && memcmp(data.data, "ADIF", 4) == 0) {
207
		/* obtain the duration from the ADIF header */
208
		size_t skip_size = (data.data[4] & 0x80) ? 9 : 0;
209

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

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

		if (fileread != 0 && bit_rate != 0)
221
			return fileread * 8.0 / bit_rate;
222
		else
223 224 225
			return fileread;
	} else
		return -1;
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
{
Max Kellermann's avatar
Max Kellermann committed
251 252
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
	if (data.IsEmpty()) {
253
		error.Set(faad_decoder_domain, "Empty file");
254
		return false;
255
	}
256

257
	uint8_t channels;
258
	uint32_t sample_rate;
259 260 261 262
#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. */
263
	unsigned long *sample_rate_p = (unsigned long *)(void *)&sample_rate;
264
#else
265
	uint32_t *sample_rate_p = &sample_rate;
266
#endif
267 268
	long nbytes = NeAACDecInit(decoder,
				   /* deconst hack, libfaad requires this */
Max Kellermann's avatar
Max Kellermann committed
269 270
				   const_cast<unsigned char *>(data.data),
				   data.size,
271
				   sample_rate_p, &channels);
272
	if (nbytes < 0) {
273
		error.Set(faad_decoder_domain, "Not an AAC stream");
274
		return false;
275
	}
276

277
	decoder_buffer_consume(buffer, nbytes);
278

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

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

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

301 302 303 304 305
/**
 * 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
306
static float
307
faad_get_file_time_float(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
308
{
309 310
	DecoderBuffer *buffer =
		decoder_buffer_new(nullptr, is,
311
				   FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
312
	float length = faad_song_duration(buffer, is);
313

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

317
		decoder_buffer_fill(buffer);
318

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

324
		NeAACDecClose(decoder);
325
	}
326

327
	decoder_buffer_free(buffer);
328

329 330 331
	return length;
}

332 333 334 335 336
/**
 * 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
337
static int
338
faad_get_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
339
{
340 341 342
	float length = faad_get_file_time_float(is);
	if (length < 0)
		return -1;
343

344
	return int(length + 0.5);
345 346
}

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

353 354
	if (adts_find_frame(buffer) == 0)
		return;
355

356 357
	/* initialize it */

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

365 366
	/* initialize the MPD core */

367
	decoder_initialized(mpd_decoder, audio_format, false, total_time);
368

369 370
	/* the decoder loop */

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

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

381 382
		/* decode it */

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

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

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

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

409
		decoder_buffer_consume(buffer, frame_info.bytesconsumed);
410

411 412
		/* update bit rate and position */

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

419 420
		/* send PCM samples to MPD */

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

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);
439

440 441
	/* cleanup */

442
	NeAACDecClose(decoder);
443
	decoder_buffer_free(buffer);
444 445
}

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

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

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

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