faad_decoder_plugin.c 11.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2010 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 22
#include "decoder_api.h"
#include "decoder_buffer.h"
23
#include "audio_check.h"
24 25 26

#define AAC_MAX_CHANNELS	6

27
#include <assert.h>
28
#include <unistd.h>
29
#include <faad.h>
30 31 32
#include <glib.h>

#undef G_LOG_DOMAIN
33
#define G_LOG_DOMAIN "faad"
34

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

40 41 42 43 44 45 46 47 48
/**
 * The GLib quark used for errors reported by this plugin.
 */
static inline GQuark
faad_decoder_quark(void)
{
	return g_quark_from_static_string("faad");
}

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

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

Max Kellermann's avatar
Max Kellermann committed
65 66 67 68
/**
 * 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
69
static size_t
70
adts_find_frame(struct decoder_buffer *buffer)
Max Kellermann's avatar
Max Kellermann committed
71
{
72 73 74
	const unsigned char *data, *p;
	size_t length, frame_length;
	bool ret;
Max Kellermann's avatar
Max Kellermann committed
75

76 77 78 79 80 81 82 83
	while (true) {
		data = decoder_buffer_read(buffer, &length);
		if (data == NULL || length < 8) {
			/* not enough data yet */
			ret = decoder_buffer_fill(buffer);
			if (!ret)
				/* failed */
				return 0;
84

85 86
			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
87

88 89 90 91 92 93 94 95 96 97 98 99 100
		/* find the 0xff marker */
		p = memchr(data, 0xff, length);
		if (p == NULL) {
			/* no marker - discard the buffer */
			decoder_buffer_consume(buffer, length);
			continue;
		}

		if (p > data) {
			/* discard data before 0xff */
			decoder_buffer_consume(buffer, p - data);
			continue;
		}
Max Kellermann's avatar
Max Kellermann committed
101 102

		/* is it a frame? */
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
		frame_length = adts_check_frame(data);
		if (frame_length == 0) {
			/* it's just some random 0xff byte; discard it
			   and continue searching */
			decoder_buffer_consume(buffer, 1);
			continue;
		}

		if (length < frame_length) {
			/* available buffer size is smaller than the
			   frame will be - attempt to read more
			   data */
			ret = decoder_buffer_fill(buffer);
			if (!ret) {
				/* not enough data; discard this frame
				   to prevent a possible buffer
				   overflow */
				data = decoder_buffer_read(buffer, &length);
				if (data != NULL)
					decoder_buffer_consume(buffer, length);
			}

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

128 129 130
		/* found a full frame! */
		return frame_length;
	}
Max Kellermann's avatar
Max Kellermann committed
131 132
}

133
static float
134
adts_song_duration(struct decoder_buffer *buffer)
Avuton Olrich's avatar
Avuton Olrich committed
135
{
Max Kellermann's avatar
Max Kellermann committed
136
	unsigned int frames, frame_length;
137
	unsigned sample_rate = 0;
Max Kellermann's avatar
Max Kellermann committed
138
	float frames_per_second;
139 140

	/* Read all frames to ensure correct time and bitrate */
Avuton Olrich's avatar
Avuton Olrich committed
141
	for (frames = 0;; frames++) {
142 143 144
		frame_length = adts_find_frame(buffer);
		if (frame_length == 0)
			break;
145 146


147 148 149 150 151 152 153 154 155 156 157 158
		if (frames == 0) {
			const unsigned char *data;
			size_t buffer_length;

			data = decoder_buffer_read(buffer, &buffer_length);
			assert(data != NULL);
			assert(frame_length <= buffer_length);

			sample_rate = adts_sample_rates[(data[2] & 0x3c) >> 2];
		}

		decoder_buffer_consume(buffer, frame_length);
159 160
	}

Max Kellermann's avatar
Max Kellermann committed
161
	frames_per_second = (float)sample_rate / 1024.0;
162 163 164 165
	if (frames_per_second <= 0)
		return -1;

	return (float)frames / frames_per_second;
166 167
}

168
static float
169
faad_song_duration(struct decoder_buffer *buffer, struct input_stream *is)
170 171 172
{
	size_t fileread;
	size_t tagsize;
173 174
	const unsigned char *data;
	size_t length;
175
	bool success;
176

177
	fileread = is->size >= 0 ? is->size : 0;
178

179 180 181 182
	decoder_buffer_fill(buffer);
	data = decoder_buffer_read(buffer, &length);
	if (data == NULL)
		return -1;
183 184

	tagsize = 0;
185
	if (length >= 10 && !memcmp(data, "ID3", 3)) {
186 187
		/* skip the ID3 tag */

188 189
		tagsize = (data[6] << 21) | (data[7] << 14) |
		    (data[8] << 7) | (data[9] << 0);
190

Avuton Olrich's avatar
Avuton Olrich committed
191
		tagsize += 10;
192

193 194 195 196 197
		success = decoder_buffer_skip(buffer, tagsize) &&
			decoder_buffer_fill(buffer);
		if (!success)
			return -1;

198 199 200
		data = decoder_buffer_read(buffer, &length);
		if (data == NULL)
			return -1;
201 202
	}

203 204
	if (is->seekable && length >= 2 &&
	    data[0] == 0xFF && ((data[1] & 0xF6) == 0xF0)) {
205
		/* obtain the duration from the ADTS header */
206
		float song_length = adts_song_duration(buffer);
207

208
		input_stream_seek(is, tagsize, SEEK_SET, NULL);
209

210 211 212 213
		data = decoder_buffer_read(buffer, &length);
		if (data != NULL)
			decoder_buffer_consume(buffer, length);
		decoder_buffer_fill(buffer);
214

215 216
		return song_length;
	} else if (length >= 5 && memcmp(data, "ADIF", 4) == 0) {
217
		/* obtain the duration from the ADIF header */
Max Kellermann's avatar
Max Kellermann committed
218
		unsigned bit_rate;
219
		size_t skip_size = (data[4] & 0x80) ? 9 : 0;
220

221
		if (8 + skip_size > length)
222 223
			/* not enough data yet; skip parsing this
			   header */
224
			return -1;
225

226 227 228 229
		bit_rate = ((data[4 + skip_size] & 0x0F) << 19) |
			(data[5 + skip_size] << 11) |
			(data[6 + skip_size] << 3) |
			(data[7 + skip_size] & 0xE0);
Max Kellermann's avatar
Max Kellermann committed
230 231

		if (fileread != 0 && bit_rate != 0)
232
			return fileread * 8.0 / bit_rate;
233
		else
234 235 236
			return fileread;
	} else
		return -1;
237 238
}

239 240 241 242 243
/**
 * Wrapper for faacDecInit() which works around some API
 * inconsistencies in libfaad.
 */
static bool
244
faad_decoder_init(faacDecHandle decoder, struct decoder_buffer *buffer,
245
		  struct audio_format *audio_format, GError **error_r)
246
{
247 248 249 250 251 252
	union {
		/* deconst hack for libfaad */
		const void *in;
		void *out;
	} u;
	size_t length;
253
	int32_t nbytes;
254 255
	uint32_t sample_rate;
	uint8_t channels;
256 257 258 259
#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. */
260
	unsigned long *sample_rate_p = (unsigned long *)(void *)&sample_rate;
261
#else
262
	uint32_t *sample_rate_p = &sample_rate;
263 264
#endif

265
	u.in = decoder_buffer_read(buffer, &length);
266 267 268
	if (u.in == NULL) {
		g_set_error(error_r, faad_decoder_quark(), 0,
			    "Empty file");
269
		return false;
270
	}
271 272

	nbytes = faacDecInit(decoder, u.out,
273
#ifdef HAVE_FAAD_BUFLEN_FUNCS
274
			     length,
275
#endif
276 277 278 279
			     sample_rate_p, &channels);
	if (nbytes < 0) {
		g_set_error(error_r, faad_decoder_quark(), 0,
			    "Not an AAC stream");
280
		return false;
281
	}
282

283
	decoder_buffer_consume(buffer, nbytes);
284

285
	return audio_format_init_checked(audio_format, sample_rate,
286
					 SAMPLE_FORMAT_S16, channels, error_r);
287 288 289 290 291 292 293
}

/**
 * Wrapper for faacDecDecode() which works around some API
 * inconsistencies in libfaad.
 */
static const void *
294
faad_decoder_decode(faacDecHandle decoder, struct decoder_buffer *buffer,
295
		    faacDecFrameInfo *frame_info)
296
{
297 298 299 300 301 302
	union {
		/* deconst hack for libfaad */
		const void *in;
		void *out;
	} u;
	size_t length;
303 304
	void *result;

305 306
	u.in = decoder_buffer_read(buffer, &length);
	if (u.in == NULL)
307
		return NULL;
308

309
	result = faacDecDecode(decoder, frame_info,
310
			       u.out
311
#ifdef HAVE_FAAD_BUFLEN_FUNCS
312
			       , length
313 314 315 316 317 318
#endif
			       );

	return result;
}

319 320 321 322 323
/**
 * 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
324
static float
325
faad_get_file_time_float(struct input_stream *is)
Avuton Olrich's avatar
Avuton Olrich committed
326
{
327
	struct decoder_buffer *buffer;
328
	float length;
329 330
	faacDecHandle decoder;
	faacDecConfigurationPtr config;
331

332
	buffer = decoder_buffer_new(NULL, is,
333
				    FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
334
	length = faad_song_duration(buffer, is);
335

Avuton Olrich's avatar
Avuton Olrich committed
336
	if (length < 0) {
337
		bool ret;
338
		struct audio_format audio_format;
339

340 341 342 343
		decoder = faacDecOpen();

		config = faacDecGetCurrentConfiguration(decoder);
		config->outputFormat = FAAD_FMT_16BIT;
Avuton Olrich's avatar
Avuton Olrich committed
344
		faacDecSetConfiguration(decoder, config);
345

346
		decoder_buffer_fill(buffer);
347

348 349
		ret = faad_decoder_init(decoder, buffer, &audio_format, NULL);
		if (ret)
Avuton Olrich's avatar
Avuton Olrich committed
350
			length = 0;
351 352 353

		faacDecClose(decoder);
	}
354

355
	decoder_buffer_free(buffer);
356

357 358 359
	return length;
}

360 361 362 363 364
/**
 * 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
365
static int
366
faad_get_file_time(struct input_stream *is)
Avuton Olrich's avatar
Avuton Olrich committed
367
{
368
	int file_time = -1;
369 370
	float length;

371
	if ((length = faad_get_file_time_float(is)) >= 0)
372
		file_time = length + 0.5;
373

374
	return file_time;
375 376
}

377
static void
378
faad_stream_decode(struct decoder *mpd_decoder, struct input_stream *is)
379
{
380
	GError *error = NULL;
Max Kellermann's avatar
Max Kellermann committed
381
	float total_time = 0;
382
	faacDecHandle decoder;
383
	struct audio_format audio_format;
384
	faacDecConfigurationPtr config;
385
	bool ret;
Max Kellermann's avatar
Max Kellermann committed
386
	uint16_t bit_rate = 0;
387
	struct decoder_buffer *buffer;
388
	enum decoder_command cmd;
389

390 391 392
	buffer = decoder_buffer_new(mpd_decoder, is,
				    FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
	total_time = faad_song_duration(buffer, is);
393

394 395
	/* create the libfaad decoder */

396 397 398 399 400 401 402 403 404 405 406 407
	decoder = faacDecOpen();

	config = faacDecGetCurrentConfiguration(decoder);
	config->outputFormat = FAAD_FMT_16BIT;
#ifdef HAVE_FAACDECCONFIGURATION_DOWNMATRIX
	config->downMatrix = 1;
#endif
#ifdef HAVE_FAACDECCONFIGURATION_DONTUPSAMPLEIMPLICITSBR
	config->dontUpSampleImplicitSBR = 0;
#endif
	faacDecSetConfiguration(decoder, config);

408 409
	while (!decoder_buffer_is_full(buffer) &&
	       !input_stream_eof(is) &&
410
	       decoder_get_command(mpd_decoder) == DECODE_COMMAND_NONE) {
411 412
		adts_find_frame(buffer);
		decoder_buffer_fill(buffer);
413 414
	}

415 416
	/* initialize it */

417
	ret = faad_decoder_init(decoder, buffer, &audio_format, &error);
418
	if (!ret) {
419 420
		g_warning("%s", error->message);
		g_error_free(error);
421 422 423 424
		faacDecClose(decoder);
		return;
	}

425 426
	/* initialize the MPD core */

427 428
	decoder_initialized(mpd_decoder, &audio_format, false, total_time);

429 430
	/* the decoder loop */

431
	do {
432
		size_t frame_size;
Max Kellermann's avatar
Max Kellermann committed
433 434
		const void *decoded;
		faacDecFrameInfo frame_info;
435 436 437 438

		/* find the next frame */

		frame_size = adts_find_frame(buffer);
439
		if (frame_size == 0)
440
			/* end of file */
441 442
			break;

443 444
		/* decode it */

445
		decoded = faad_decoder_decode(decoder, buffer, &frame_info);
446

Max Kellermann's avatar
Max Kellermann committed
447
		if (frame_info.error > 0) {
448
			g_warning("error decoding AAC stream: %s\n",
Max Kellermann's avatar
Max Kellermann committed
449
				  faacDecGetErrorMessage(frame_info.error));
450 451 452
			break;
		}

453
		if (frame_info.channels != audio_format.channels) {
454
			g_warning("channel count changed from %u to %u",
455
				  audio_format.channels, frame_info.channels);
456 457
			break;
		}
458

459
#ifdef HAVE_FAACDECFRAMEINFO_SAMPLERATE
460
		if (frame_info.samplerate != audio_format.sample_rate) {
461
			g_warning("sample rate changed from %u to %lu",
462
				  audio_format.sample_rate,
463 464
				  (unsigned long)frame_info.samplerate);
			break;
465
		}
466
#endif
467

468
		decoder_buffer_consume(buffer, frame_info.bytesconsumed);
469

470 471
		/* update bit rate and position */

Max Kellermann's avatar
Max Kellermann committed
472
		if (frame_info.samples > 0) {
Max Kellermann's avatar
Max Kellermann committed
473
			bit_rate = frame_info.bytesconsumed * 8.0 *
474
			    frame_info.channels * audio_format.sample_rate /
Max Kellermann's avatar
Max Kellermann committed
475
			    frame_info.samples / 1000 + 0.5;
476 477
		}

478 479
		/* send PCM samples to MPD */

Max Kellermann's avatar
Max Kellermann committed
480
		cmd = decoder_data(mpd_decoder, is, decoded,
481
				   (size_t)frame_info.samples * 2,
482
				   bit_rate);
483
	} while (cmd != DECODE_COMMAND_STOP);
484

485 486
	/* cleanup */

487 488 489
	faacDecClose(decoder);
}

Max Kellermann's avatar
Max Kellermann committed
490
static struct tag *
491
faad_stream_tag(struct input_stream *is)
Avuton Olrich's avatar
Avuton Olrich committed
492
{
493
	int file_time = faad_get_file_time(is);
494
	struct tag *tag;
Warren Dukes's avatar
Warren Dukes committed
495

496
	if (file_time < 0)
497
		return NULL;
Warren Dukes's avatar
Warren Dukes committed
498

499 500 501
	tag = tag_new();
	tag->time = file_time;
	return tag;
Warren Dukes's avatar
Warren Dukes committed
502 503
}

Max Kellermann's avatar
Max Kellermann committed
504 505 506 507
static const char *const faad_suffixes[] = { "aac", NULL };
static const char *const faad_mime_types[] = {
	"audio/aac", "audio/aacp", NULL
};
Warren Dukes's avatar
Warren Dukes committed
508

509 510
const struct decoder_plugin faad_decoder_plugin = {
	.name = "faad",
511
	.stream_decode = faad_stream_decode,
512
	.stream_tag = faad_stream_tag,
Max Kellermann's avatar
Max Kellermann committed
513 514
	.suffixes = faad_suffixes,
	.mime_types = faad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
515
};