FaadDecoderPlugin.cxx 11.4 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>

38 39
#define AAC_MAX_CHANNELS	6

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

45
static constexpr Domain faad_decoder_domain("faad_decoder");
46

47 48 49 50
/**
 * 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
51
static size_t
52
adts_check_frame(const unsigned char *data)
53 54
{
	/* check syncword */
55
	if (!((data[0] == 0xFF) && ((data[1] & 0xF6) == 0xF0)))
56 57
		return 0;

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

Max Kellermann's avatar
Max Kellermann committed
63 64 65 66
/**
 * 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
67
static size_t
68
adts_find_frame(DecoderBuffer *buffer)
Max Kellermann's avatar
Max Kellermann committed
69
{
70
	while (true) {
71 72
		auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
		if (data.size < 8) {
73
			/* not enough data yet */
74
			if (!decoder_buffer_fill(buffer))
75 76
				/* failed */
				return 0;
77

78 79
			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
80

81
		/* find the 0xff marker */
82 83
		const uint8_t *p = (const uint8_t *)
			memchr(data.data, 0xff, data.size);
84
		if (p == nullptr) {
85
			/* no marker - discard the buffer */
86
			decoder_buffer_clear(buffer);
87 88 89
			continue;
		}

90
		if (p > data.data) {
91
			/* discard data before 0xff */
92
			decoder_buffer_consume(buffer, p - data.data);
93 94
			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
95 96

		/* is it a frame? */
97
		size_t frame_length = adts_check_frame(data.data);
98 99 100 101 102 103 104
		if (frame_length == 0) {
			/* it's just some random 0xff byte; discard it
			   and continue searching */
			decoder_buffer_consume(buffer, 1);
			continue;
		}

105
		if (data.size < frame_length) {
106 107 108
			/* available buffer size is smaller than the
			   frame will be - attempt to read more
			   data */
109
			if (!decoder_buffer_fill(buffer)) {
110 111 112
				/* not enough data; discard this frame
				   to prevent a possible buffer
				   overflow */
113
				decoder_buffer_clear(buffer);
114 115 116 117
			}

			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
118

119 120 121
		/* found a full frame! */
		return frame_length;
	}
Max Kellermann's avatar
Max Kellermann committed
122 123
}

124
static float
125
adts_song_duration(DecoderBuffer *buffer)
Avuton Olrich's avatar
Avuton Olrich committed
126
{
127
	unsigned sample_rate = 0;
128 129

	/* Read all frames to ensure correct time and bitrate */
130 131 132
	unsigned frames = 0;
	for (;; frames++) {
		unsigned frame_length = adts_find_frame(buffer);
133 134
		if (frame_length == 0)
			break;
135

136
		if (frames == 0) {
137 138 139
			auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
			assert(!data.IsEmpty());
			assert(frame_length <= data.size);
140

141
			sample_rate = adts_sample_rates[(data.data[2] & 0x3c) >> 2];
142 143 144
		}

		decoder_buffer_consume(buffer, frame_length);
145 146
	}

147
	float frames_per_second = (float)sample_rate / 1024.0;
148 149 150 151
	if (frames_per_second <= 0)
		return -1;

	return (float)frames / frames_per_second;
152 153
}

154
static float
155
faad_song_duration(DecoderBuffer *buffer, InputStream &is)
156
{
157
	const auto size = is.GetSize();
158
	const size_t fileread = size >= 0 ? size : 0;
159

160
	decoder_buffer_fill(buffer);
161 162
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
	if (data.IsEmpty())
163
		return -1;
164

165
	size_t tagsize = 0;
166
	if (data.size >= 10 && !memcmp(data.data, "ID3", 3)) {
167 168
		/* skip the ID3 tag */

169 170
		tagsize = (data.data[6] << 21) | (data.data[7] << 14) |
		    (data.data[8] << 7) | (data.data[9] << 0);
171

Avuton Olrich's avatar
Avuton Olrich committed
172
		tagsize += 10;
173

174
		bool success = decoder_buffer_skip(buffer, tagsize) &&
175 176 177 178
			decoder_buffer_fill(buffer);
		if (!success)
			return -1;

179 180
		data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
		if (data.IsEmpty())
181
			return -1;
182 183
	}

184 185
	if (is.IsSeekable() && data.size >= 2 &&
	    data.data[0] == 0xFF && ((data.data[1] & 0xF6) == 0xF0)) {
186
		/* obtain the duration from the ADTS header */
187
		float song_length = adts_song_duration(buffer);
188

189
		is.LockSeek(tagsize, IgnoreError());
190

191
		decoder_buffer_clear(buffer);
192
		decoder_buffer_fill(buffer);
193

194
		return song_length;
195
	} else if (data.size >= 5 && memcmp(data.data, "ADIF", 4) == 0) {
196
		/* obtain the duration from the ADIF header */
Max Kellermann's avatar
Max Kellermann committed
197
		unsigned bit_rate;
198
		size_t skip_size = (data.data[4] & 0x80) ? 9 : 0;
199

200
		if (8 + skip_size > data.size)
201 202
			/* not enough data yet; skip parsing this
			   header */
203
			return -1;
204

205 206 207 208
		bit_rate = ((data.data[4 + skip_size] & 0x0F) << 19) |
			(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
209 210

		if (fileread != 0 && bit_rate != 0)
211
			return fileread * 8.0 / bit_rate;
212
		else
213 214 215
			return fileread;
	} else
		return -1;
216 217
}

218
/**
219
 * Wrapper for NeAACDecInit() which works around some API
220 221 222
 * inconsistencies in libfaad.
 */
static bool
223
faad_decoder_init(NeAACDecHandle decoder, DecoderBuffer *buffer,
224
		  AudioFormat &audio_format, Error &error)
225
{
226
	uint32_t sample_rate;
227 228 229 230
#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. */
231
	unsigned long *sample_rate_p = (unsigned long *)(void *)&sample_rate;
232
#else
233
	uint32_t *sample_rate_p = &sample_rate;
234 235
#endif

236 237
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
	if (data.IsEmpty()) {
238
		error.Set(faad_decoder_domain, "Empty file");
239
		return false;
240
	}
241

242 243 244
	uint8_t channels;
	int32_t nbytes = NeAACDecInit(decoder,
				      /* deconst hack, libfaad requires this */
245 246
				      const_cast<uint8_t *>(data.data),
				      data.size,
247
				      sample_rate_p, &channels);
248
	if (nbytes < 0) {
249
		error.Set(faad_decoder_domain, "Not an AAC stream");
250
		return false;
251
	}
252

253
	decoder_buffer_consume(buffer, nbytes);
254

255
	return audio_format_init_checked(audio_format, sample_rate,
256
					 SampleFormat::S16, channels, error);
257 258 259
}

/**
260
 * Wrapper for NeAACDecDecode() which works around some API
261 262 263
 * inconsistencies in libfaad.
 */
static const void *
264
faad_decoder_decode(NeAACDecHandle decoder, DecoderBuffer *buffer,
265
		    NeAACDecFrameInfo *frame_info)
266
{
267 268
	auto data = ConstBuffer<uint8_t>::FromVoid(decoder_buffer_read(buffer));
	if (data.IsEmpty())
269
		return nullptr;
270

271
	return NeAACDecDecode(decoder, frame_info,
272
			      /* deconst hack, libfaad requires this */
273 274
			      const_cast<uint8_t *>(data.data),
			      data.size);
275 276
}

277 278 279 280 281
/**
 * 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
282
static float
283
faad_get_file_time_float(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
284
{
285 286 287 288
	DecoderBuffer *buffer =
		decoder_buffer_new(nullptr, is,
				   FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
	float length = faad_song_duration(buffer, is);
289

Avuton Olrich's avatar
Avuton Olrich committed
290
	if (length < 0) {
291
		NeAACDecHandle decoder = NeAACDecOpen();
292

293 294
		NeAACDecConfigurationPtr config =
			NeAACDecGetCurrentConfiguration(decoder);
295
		config->outputFormat = FAAD_FMT_16BIT;
296
		NeAACDecSetConfiguration(decoder, config);
297

298
		decoder_buffer_fill(buffer);
299

300 301 302
		AudioFormat audio_format;
		if (faad_decoder_init(decoder, buffer, audio_format,
				      IgnoreError()))
Avuton Olrich's avatar
Avuton Olrich committed
303
			length = 0;
304

305
		NeAACDecClose(decoder);
306
	}
307

308
	decoder_buffer_free(buffer);
309

310 311 312
	return length;
}

313 314 315 316 317
/**
 * 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
318
static int
319
faad_get_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
320
{
321
	int file_time = -1;
322 323
	float length;

324
	if ((length = faad_get_file_time_float(is)) >= 0)
325
		file_time = length + 0.5;
326

327
	return file_time;
328 329
}

330
static void
331
faad_stream_decode(Decoder &mpd_decoder, InputStream &is)
332
{
333 334 335 336
	DecoderBuffer *buffer =
		decoder_buffer_new(&mpd_decoder, is,
				   FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
	const float total_time = faad_song_duration(buffer, is);
337

338 339
	/* create the libfaad decoder */

340
	NeAACDecHandle decoder = NeAACDecOpen();
341

342 343
	NeAACDecConfigurationPtr config =
		NeAACDecGetCurrentConfiguration(decoder);
344 345 346
	config->outputFormat = FAAD_FMT_16BIT;
	config->downMatrix = 1;
	config->dontUpSampleImplicitSBR = 0;
347
	NeAACDecSetConfiguration(decoder, config);
348

349
	while (!decoder_buffer_is_full(buffer) && !is.LockIsEOF() &&
350
	       decoder_get_command(mpd_decoder) == DecoderCommand::NONE) {
351 352
		adts_find_frame(buffer);
		decoder_buffer_fill(buffer);
353 354
	}

355 356
	/* initialize it */

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

366 367
	/* initialize the MPD core */

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

370 371
	/* the decoder loop */

372
	DecoderCommand cmd;
373
	unsigned bit_rate = 0;
374
	do {
375
		size_t frame_size;
Max Kellermann's avatar
Max Kellermann committed
376
		const void *decoded;
377
		NeAACDecFrameInfo frame_info;
378 379 380 381

		/* find the next frame */

		frame_size = adts_find_frame(buffer);
382
		if (frame_size == 0)
383
			/* end of file */
384 385
			break;

386 387
		/* decode it */

388
		decoded = faad_decoder_decode(decoder, buffer, &frame_info);
389

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

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

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

412
		decoder_buffer_consume(buffer, frame_info.bytesconsumed);
413

414 415
		/* update bit rate and position */

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

422 423
		/* send PCM samples to MPD */

Max Kellermann's avatar
Max Kellermann committed
424
		cmd = decoder_data(mpd_decoder, is, decoded,
425
				   (size_t)frame_info.samples * 2,
426
				   bit_rate);
427
	} while (cmd != DecoderCommand::STOP);
428

429 430
	/* cleanup */

431
	NeAACDecClose(decoder);
432
	decoder_buffer_free(buffer);
433 434
}

435
static bool
436
faad_scan_stream(InputStream &is,
437
		 const struct tag_handler *handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
438
{
439
	int file_time = faad_get_file_time(is);
Warren Dukes's avatar
Warren Dukes committed
440

441
	if (file_time < 0)
442
		return false;
Warren Dukes's avatar
Warren Dukes committed
443

444 445
	tag_handler_invoke_duration(handler, handler_ctx, file_time);
	return true;
Warren Dukes's avatar
Warren Dukes committed
446 447
}

448
static const char *const faad_suffixes[] = { "aac", nullptr };
Max Kellermann's avatar
Max Kellermann committed
449
static const char *const faad_mime_types[] = {
450
	"audio/aac", "audio/aacp", nullptr
Max Kellermann's avatar
Max Kellermann committed
451
};
Warren Dukes's avatar
Warren Dukes committed
452

453
const DecoderPlugin faad_decoder_plugin = {
454 455 456 457 458 459 460 461 462 463
	"faad",
	nullptr,
	nullptr,
	faad_stream_decode,
	nullptr,
	nullptr,
	faad_scan_stream,
	nullptr,
	faad_suffixes,
	faad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
464
};