FaadDecoderPlugin.cxx 11.2 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
	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
	buffer.Consume(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
	auto data = ConstBuffer<uint8_t>::FromVoid(buffer.Read());
292
	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
 * 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.
306
 */
307 308
static std::pair<bool, SignedSongTime>
faad_get_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
309
{
310 311
	DecoderBuffer buffer(nullptr, is,
			     FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
312
	auto duration = faad_song_duration(buffer, is);
313
	bool recognized = !duration.IsNegative();
314

315
	if (!recognized) {
316
		NeAACDecHandle decoder = faad_decoder_new();
317

318
		buffer.Fill();
319

320
		AudioFormat audio_format;
321
		if (faad_decoder_init(decoder, buffer, audio_format,
322
				      IgnoreError()))
323
			recognized = true;
324

325
		NeAACDecClose(decoder);
326
	}
327

328
	return std::make_pair(recognized, duration);
329 330
}

331
static void
332
faad_stream_decode(Decoder &mpd_decoder, InputStream &is,
333
		   DecoderBuffer &buffer, const NeAACDecHandle decoder)
334
{
335
	const auto total_time = faad_song_duration(buffer, is);
336

337 338
	if (adts_find_frame(buffer) == 0)
		return;
339

340 341
	/* initialize it */

342
	Error error;
343 344
	AudioFormat audio_format;
	if (!faad_decoder_init(decoder, buffer, audio_format, error)) {
345
		LogError(error);
346 347 348
		return;
	}

349 350
	/* initialize the MPD core */

351
	decoder_initialized(mpd_decoder, audio_format, false, total_time);
352

353 354
	/* the decoder loop */

355
	DecoderCommand cmd;
356
	unsigned bit_rate = 0;
357
	do {
358 359
		/* find the next frame */

360
		const size_t frame_size = adts_find_frame(buffer);
361
		if (frame_size == 0)
362
			/* end of file */
363 364
			break;

365 366
		/* decode it */

367 368 369
		NeAACDecFrameInfo frame_info;
		const void *const decoded =
			faad_decoder_decode(decoder, buffer, &frame_info);
370

Max Kellermann's avatar
Max Kellermann committed
371
		if (frame_info.error > 0) {
372 373 374
			FormatWarning(faad_decoder_domain,
				      "error decoding AAC stream: %s",
				      NeAACDecGetErrorMessage(frame_info.error));
375 376 377
			break;
		}

378
		if (frame_info.channels != audio_format.channels) {
379 380 381
			FormatDefault(faad_decoder_domain,
				      "channel count changed from %u to %u",
				      audio_format.channels, frame_info.channels);
382 383
			break;
		}
384

385
		if (frame_info.samplerate != audio_format.sample_rate) {
386 387 388 389
			FormatDefault(faad_decoder_domain,
				      "sample rate changed from %u to %lu",
				      audio_format.sample_rate,
				      (unsigned long)frame_info.samplerate);
390
			break;
391 392
		}

393
		buffer.Consume(frame_info.bytesconsumed);
394

395 396
		/* update bit rate and position */

Max Kellermann's avatar
Max Kellermann committed
397
		if (frame_info.samples > 0) {
Max Kellermann's avatar
Max Kellermann committed
398
			bit_rate = frame_info.bytesconsumed * 8.0 *
399
			    frame_info.channels * audio_format.sample_rate /
Max Kellermann's avatar
Max Kellermann committed
400
			    frame_info.samples / 1000 + 0.5;
401 402
		}

403 404
		/* send PCM samples to MPD */

Max Kellermann's avatar
Max Kellermann committed
405
		cmd = decoder_data(mpd_decoder, is, decoded,
406
				   (size_t)frame_info.samples * 2,
407
				   bit_rate);
408
	} while (cmd != DecoderCommand::STOP);
409 410 411 412 413
}

static void
faad_stream_decode(Decoder &mpd_decoder, InputStream &is)
{
414 415
	DecoderBuffer buffer(&mpd_decoder, is,
			     FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
416 417 418 419 420

	/* create the libfaad decoder */

	const NeAACDecHandle decoder = faad_decoder_new();

421
	faad_stream_decode(mpd_decoder, is, buffer, decoder);
422

423 424
	/* cleanup */

425
	NeAACDecClose(decoder);
426 427
}

428
static bool
429
faad_scan_stream(InputStream &is,
430
		 const struct tag_handler *handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
431
{
432 433
	auto result = faad_get_file_time(is);
	if (!result.first)
434
		return false;
Warren Dukes's avatar
Warren Dukes committed
435

436 437 438
	if (!result.second.IsNegative())
		tag_handler_invoke_duration(handler, handler_ctx,
					    SongTime(result.second));
439
	return true;
Warren Dukes's avatar
Warren Dukes committed
440 441
}

442
static const char *const faad_suffixes[] = { "aac", nullptr };
Max Kellermann's avatar
Max Kellermann committed
443
static const char *const faad_mime_types[] = {
444
	"audio/aac", "audio/aacp", nullptr
Max Kellermann's avatar
Max Kellermann committed
445
};
Warren Dukes's avatar
Warren Dukes committed
446

447
const DecoderPlugin faad_decoder_plugin = {
448 449 450 451 452 453 454 455 456 457
	"faad",
	nullptr,
	nullptr,
	faad_stream_decode,
	nullptr,
	nullptr,
	faad_scan_stream,
	nullptr,
	faad_suffixes,
	faad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
458
};