MadDecoderPlugin.cxx 26.2 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 The Music Player Daemon Project
3
 * http://www.musicpd.org
Warren Dukes's avatar
Warren Dukes committed
4 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.
Warren Dukes's avatar
Warren Dukes committed
18 19
 */

20
#include "config.h"
21
#include "MadDecoderPlugin.hxx"
22
#include "../DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
23
#include "input/InputStream.hxx"
24
#include "config/ConfigGlobal.hxx"
25 26
#include "tag/TagId3.hxx"
#include "tag/TagRva2.hxx"
27
#include "tag/TagHandler.hxx"
28
#include "tag/ReplayGain.hxx"
29
#include "tag/MixRamp.hxx"
30
#include "CheckAudioFormat.hxx"
31
#include "util/StringCompare.hxx"
32
#include "util/Error.hxx"
33 34
#include "util/Domain.hxx"
#include "Log.hxx"
Warren Dukes's avatar
Warren Dukes committed
35 36

#include <mad.h>
37

38
#ifdef ENABLE_ID3TAG
39 40
#include <id3tag.h>
#endif
41

42 43 44 45 46
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

47
static constexpr unsigned long FRAMES_CUSHION = 2000;
Warren Dukes's avatar
Warren Dukes committed
48

49 50 51 52 53 54
enum mp3_action {
	DECODE_SKIP = -3,
	DECODE_BREAK = -2,
	DECODE_CONT = -1,
	DECODE_OK = 0
};
Warren Dukes's avatar
Warren Dukes committed
55

56 57 58 59 60
enum muteframe {
	MUTEFRAME_NONE,
	MUTEFRAME_SKIP,
	MUTEFRAME_SEEK
};
61

62
/* the number of samples of silence the decoder inserts at start */
63
static constexpr unsigned DECODERDELAY = 529;
64

65
static constexpr bool DEFAULT_GAPLESS_MP3_PLAYBACK = true;
66

67 68
static constexpr Domain mad_domain("mad");

Max Kellermann's avatar
Max Kellermann committed
69
static bool gapless_playback;
70

71 72 73 74 75 76 77
gcc_const
static SongTime
ToSongTime(mad_timer_t t)
{
	return SongTime::FromMS(mad_timer_count(t, MAD_UNITS_MILLISECONDS));
}

78 79
static inline int32_t
mad_fixed_to_24_sample(mad_fixed_t sample)
Avuton Olrich's avatar
Avuton Olrich committed
80
{
81 82 83
	static constexpr unsigned bits = 24;
	static constexpr mad_fixed_t MIN = -MAD_F_ONE;
	static constexpr mad_fixed_t MAX = MAD_F_ONE - 1;
Warren Dukes's avatar
Warren Dukes committed
84

85 86
	/* round */
	sample = sample + (1L << (MAD_F_FRACBITS - bits));
Warren Dukes's avatar
Warren Dukes committed
87

88
	/* clip */
89
	if (gcc_unlikely(sample > MAX))
90
		sample = MAX;
91
	else if (gcc_unlikely(sample < MIN))
92
		sample = MIN;
Warren Dukes's avatar
Warren Dukes committed
93

94 95
	/* quantize */
	return sample >> (MAD_F_FRACBITS + 1 - bits);
Warren Dukes's avatar
Warren Dukes committed
96
}
Avuton Olrich's avatar
Avuton Olrich committed
97

98 99 100 101
static void
mad_fixed_to_24_buffer(int32_t *dest, const struct mad_synth *synth,
		       unsigned int start, unsigned int end,
		       unsigned int num_channels)
102
{
103 104
	for (unsigned i = start; i < end; ++i)
		for (unsigned c = 0; c < num_channels; ++c)
105
			*dest++ = mad_fixed_to_24_sample(synth->pcm.samples[c][i]);
106 107
}

108
static bool
109
mp3_plugin_init(gcc_unused const ConfigBlock &block)
110
{
111
	gapless_playback = config_get_bool(ConfigOption::GAPLESS_MP3_PLAYBACK,
112
					   DEFAULT_GAPLESS_MP3_PLAYBACK);
113
	return true;
114 115
}

116
struct MadDecoder {
117 118 119
	static constexpr size_t READ_BUFFER_SIZE = 40960;
	static constexpr size_t MP3_DATA_OUTPUT_BUFFER_SIZE = 2048;

Warren Dukes's avatar
Warren Dukes committed
120 121 122 123
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
Max Kellermann's avatar
Max Kellermann committed
124 125
	unsigned char input_buffer[READ_BUFFER_SIZE];
	int32_t output_buffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
126
	SignedSongTime total_time;
127 128
	SongTime elapsed_time;
	SongTime seek_time;
Max Kellermann's avatar
Max Kellermann committed
129 130
	enum muteframe mute_frame;
	long *frame_offsets;
Avuton Olrich's avatar
Avuton Olrich committed
131
	mad_timer_t *times;
Max Kellermann's avatar
Max Kellermann committed
132 133 134 135 136 137 138
	unsigned long highest_frame;
	unsigned long max_frames;
	unsigned long current_frame;
	unsigned int drop_start_frames;
	unsigned int drop_end_frames;
	unsigned int drop_start_samples;
	unsigned int drop_end_samples;
139
	bool found_replay_gain;
Max Kellermann's avatar
Max Kellermann committed
140 141
	bool found_first_frame;
	bool decoded_first_frame;
Max Kellermann's avatar
Max Kellermann committed
142
	unsigned long bit_rate;
143
	Decoder *const decoder;
144
	InputStream &input_stream;
145
	enum mad_layer layer;
146

147
	MadDecoder(Decoder *decoder, InputStream &input_stream);
148 149 150 151
	~MadDecoder();

	bool Seek(long offset);
	bool FillBuffer();
Max Kellermann's avatar
Max Kellermann committed
152 153
	void ParseId3(size_t tagsize, Tag **mpd_tag);
	enum mp3_action DecodeNextFrameHeader(Tag **tag);
154 155 156
	enum mp3_action DecodeNextFrame();

	gcc_pure
157
	offset_type ThisFrameOffset() const;
158 159

	gcc_pure
160
	offset_type RestIncludingThisFrame() const;
161 162 163 164 165 166

	/**
	 * Attempt to calulcate the length of the song from filesize
	 */
	void FileSizeToSongLength();

Max Kellermann's avatar
Max Kellermann committed
167
	bool DecodeFirstFrame(Tag **tag);
168

169 170 171 172 173 174 175 176 177
	void AllocateBuffers() {
		assert(max_frames > 0);
		assert(frame_offsets == nullptr);
		assert(times == nullptr);

		frame_offsets = new long[max_frames];
		times = new mad_timer_t[max_frames];
	}

178
	gcc_pure
179
	long TimeToFrame(SongTime t) const;
180 181 182 183 184 185

	void UpdateTimerNextFrame();

	/**
	 * Sends the synthesized current frame via decoder_data().
	 */
186
	DecoderCommand SendPCM(unsigned i, unsigned pcm_length);
187 188 189 190 191

	/**
	 * Synthesize the current frame and send it via
	 * decoder_data().
	 */
192
	DecoderCommand SyncAndSend();
193 194

	bool Read();
Max Kellermann's avatar
Max Kellermann committed
195
};
Warren Dukes's avatar
Warren Dukes committed
196

197
MadDecoder::MadDecoder(Decoder *_decoder,
198
		       InputStream &_input_stream)
199 200 201 202 203 204
	:mute_frame(MUTEFRAME_NONE),
	 frame_offsets(nullptr),
	 times(nullptr),
	 highest_frame(0), max_frames(0), current_frame(0),
	 drop_start_frames(0), drop_end_frames(0),
	 drop_start_samples(0), drop_end_samples(0),
205
	 found_replay_gain(false),
206 207 208
	 found_first_frame(false), decoded_first_frame(false),
	 decoder(_decoder), input_stream(_input_stream),
	 layer(mad_layer(0))
Avuton Olrich's avatar
Avuton Olrich committed
209
{
210 211 212 213 214
	mad_stream_init(&stream);
	mad_stream_options(&stream, MAD_OPTION_IGNORECRC);
	mad_frame_init(&frame);
	mad_synth_init(&synth);
	mad_timer_reset(&timer);
Warren Dukes's avatar
Warren Dukes committed
215 216
}

217 218
inline bool
MadDecoder::Seek(long offset)
Avuton Olrich's avatar
Avuton Olrich committed
219
{
220
	Error error;
221
	if (!input_stream.LockSeek(offset, error))
Max Kellermann's avatar
Max Kellermann committed
222
		return false;
223

224 225
	mad_stream_buffer(&stream, input_buffer, 0);
	stream.error = MAD_ERROR_NONE;
226

Max Kellermann's avatar
Max Kellermann committed
227
	return true;
228 229
}

230 231
inline bool
MadDecoder::FillBuffer()
Avuton Olrich's avatar
Avuton Olrich committed
232
{
Max Kellermann's avatar
Max Kellermann committed
233 234 235
	size_t remaining, length;
	unsigned char *dest;

236 237 238 239
	if (stream.next_frame != nullptr) {
		remaining = stream.bufend - stream.next_frame;
		memmove(input_buffer, stream.next_frame, remaining);
		dest = input_buffer + remaining;
Max Kellermann's avatar
Max Kellermann committed
240
		length = READ_BUFFER_SIZE - remaining;
Avuton Olrich's avatar
Avuton Olrich committed
241
	} else {
Max Kellermann's avatar
Max Kellermann committed
242 243
		remaining = 0;
		length = READ_BUFFER_SIZE;
244
		dest = input_buffer;
Warren Dukes's avatar
Warren Dukes committed
245 246
	}

247 248
	/* we've exhausted the read buffer, so give up!, these potential
	 * mp3 frames are way too big, and thus unlikely to be mp3 frames */
Max Kellermann's avatar
Max Kellermann committed
249
	if (length == 0)
Max Kellermann's avatar
Max Kellermann committed
250
		return false;
251

252
	length = decoder_read(decoder, input_stream, dest, length);
Max Kellermann's avatar
Max Kellermann committed
253
	if (length == 0)
Max Kellermann's avatar
Max Kellermann committed
254
		return false;
255

256 257
	mad_stream_buffer(&stream, input_buffer, length + remaining);
	stream.error = MAD_ERROR_NONE;
Warren Dukes's avatar
Warren Dukes committed
258

Max Kellermann's avatar
Max Kellermann committed
259
	return true;
Warren Dukes's avatar
Warren Dukes committed
260 261
}

262
#ifdef ENABLE_ID3TAG
263
static bool
264
parse_id3_replay_gain_info(ReplayGainInfo &rgi,
265
			   struct id3_tag *tag)
Avuton Olrich's avatar
Avuton Olrich committed
266
{
267
	bool found = false;
268

269
	rgi.Clear();
270

271 272
	struct id3_frame *frame;
	for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
Avuton Olrich's avatar
Avuton Olrich committed
273 274
		if (frame->nfields < 3)
			continue;
275

276
		char *const key = (char *)
Avuton Olrich's avatar
Avuton Olrich committed
277 278
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
279
		char *const value = (char *)
Avuton Olrich's avatar
Avuton Olrich committed
280 281
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));
282

283
		if (ParseReplayGainTag(rgi, key, value))
284
			found = true;
285 286 287 288 289

		free(key);
		free(value);
	}

290
	return found ||
291
		/* fall back on RVA2 if no replaygain tags found */
292
		tag_rva2_parse(tag, rgi);
293
}
294
#endif
295

296
#ifdef ENABLE_ID3TAG
297 298 299
gcc_pure
static MixRampInfo
parse_id3_mixramp(struct id3_tag *tag)
300
{
301
	MixRampInfo result;
302

303 304
	struct id3_frame *frame;
	for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
305 306 307
		if (frame->nfields < 3)
			continue;

308
		char *const key = (char *)
309 310
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
311
		char *const value = (char *)
312 313 314
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

315
		ParseMixRampTag(result, key, value);
316 317 318 319 320

		free(key);
		free(value);
	}

321
	return result;
322 323 324
}
#endif

325
inline void
Max Kellermann's avatar
Max Kellermann committed
326
MadDecoder::ParseId3(size_t tagsize, Tag **mpd_tag)
Avuton Olrich's avatar
Avuton Olrich committed
327
{
328
#ifdef ENABLE_ID3TAG
329
	id3_byte_t *allocated = nullptr;
330

331
	const id3_length_t count = stream.bufend - stream.this_frame;
332

333
	const id3_byte_t *id3_data;
Avuton Olrich's avatar
Avuton Olrich committed
334
	if (tagsize <= count) {
335 336
		id3_data = stream.this_frame;
		mad_stream_skip(&(stream), tagsize);
Avuton Olrich's avatar
Avuton Olrich committed
337
	} else {
338
		allocated = new id3_byte_t[tagsize];
339 340
		memcpy(allocated, stream.this_frame, count);
		mad_stream_skip(&(stream), count);
341

342 343
		if (!decoder_read_full(decoder, input_stream,
				       allocated + count, tagsize - count)) {
344
			LogDebug(mad_domain, "error parsing ID3 tag");
345
			delete[] allocated;
Max Kellermann's avatar
Max Kellermann committed
346
			return;
Warren Dukes's avatar
Warren Dukes committed
347
		}
348 349 350 351

		id3_data = allocated;
	}

352
	struct id3_tag *const id3_tag = id3_tag_parse(id3_data, tagsize);
353
	if (id3_tag == nullptr) {
354
		delete[] allocated;
Max Kellermann's avatar
Max Kellermann committed
355 356
		return;
	}
357

Max Kellermann's avatar
Max Kellermann committed
358
	if (mpd_tag) {
Max Kellermann's avatar
Max Kellermann committed
359
		Tag *tmp_tag = tag_id3_import(id3_tag);
360
		if (tmp_tag != nullptr) {
Max Kellermann's avatar
Max Kellermann committed
361
			delete *mpd_tag;
Max Kellermann's avatar
Max Kellermann committed
362
			*mpd_tag = tmp_tag;
363
		}
364
	}
365

366
	if (decoder != nullptr) {
367
		ReplayGainInfo rgi;
368

369
		if (parse_id3_replay_gain_info(rgi, id3_tag)) {
370
			decoder_replay_gain(*decoder, &rgi);
371
			found_replay_gain = true;
372
		}
373

374
		decoder_mixramp(*decoder, parse_id3_mixramp(id3_tag));
375 376
	}

Max Kellermann's avatar
Max Kellermann committed
377
	id3_tag_delete(id3_tag);
Max Kellermann's avatar
Max Kellermann committed
378

379
	delete[] allocated;
380
#else /* !ENABLE_ID3TAG */
381 382 383 384 385
	(void)mpd_tag;

	/* This code is enabled when libid3tag is disabled.  Instead
	   of parsing the ID3 frame, it just skips it. */

386
	size_t count = stream.bufend - stream.this_frame;
387 388

	if (tagsize <= count) {
389
		mad_stream_skip(&stream, tagsize);
390
	} else {
391
		mad_stream_skip(&stream, count);
392
		decoder_skip(decoder, input_stream, tagsize - count);
393
	}
394
#endif
395 396
}

397
#ifndef ENABLE_ID3TAG
398 399 400
/**
 * This function emulates libid3tag when it is disabled.  Instead of
 * doing a real analyzation of the frame, it just checks whether the
401 402
 * frame begins with the string "ID3".  If so, it returns the length
 * of the ID3 frame.
403 404 405 406
 */
static signed long
id3_tag_query(const void *p0, size_t length)
{
407
	const char *p = (const char *)p0;
408

409 410
	return length >= 10 && memcmp(p, "ID3", 3) == 0
		? (p[8] << 7) + p[9] + 10
411 412
		: 0;
}
413
#endif /* !ENABLE_ID3TAG */
414

415 416 417 418 419 420 421 422 423 424 425 426 427 428
static enum mp3_action
RecoverFrameError(struct mad_stream &stream)
{
	if (MAD_RECOVERABLE(stream.error))
		return DECODE_SKIP;
	else if (stream.error == MAD_ERROR_BUFLEN)
		return DECODE_CONT;

	FormatWarning(mad_domain,
		      "unrecoverable frame level error: %s",
		      mad_stream_errorstr(&stream));
	return DECODE_BREAK;
}

429
enum mp3_action
Max Kellermann's avatar
Max Kellermann committed
430
MadDecoder::DecodeNextFrameHeader(Tag **tag)
Avuton Olrich's avatar
Avuton Olrich committed
431
{
432 433 434
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
		return DECODE_BREAK;
435

436 437 438 439 440
	if (mad_header_decode(&frame.header, &stream)) {
		if (stream.error == MAD_ERROR_LOSTSYNC && stream.this_frame) {
			signed long tagsize = id3_tag_query(stream.this_frame,
							    stream.bufend -
							    stream.this_frame);
Avuton Olrich's avatar
Avuton Olrich committed
441 442 443

			if (tagsize > 0) {
				if (tag && !(*tag)) {
444
					ParseId3((size_t)tagsize, tag);
Avuton Olrich's avatar
Avuton Olrich committed
445
				} else {
446
					mad_stream_skip(&stream, tagsize);
447
				}
448 449 450
				return DECODE_CONT;
			}
		}
451

452
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
453
	}
454

455 456 457
	enum mad_layer new_layer = frame.header.layer;
	if (layer == (mad_layer)0) {
		if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
458
			/* Only layer 2 and 3 have been tested to work */
459
			return DECODE_SKIP;
460
		}
461 462 463

		layer = new_layer;
	} else if (new_layer != layer) {
464
		/* Don't decode frames with a different layer than the first */
465 466
		return DECODE_SKIP;
	}
Warren Dukes's avatar
Warren Dukes committed
467 468 469 470

	return DECODE_OK;
}

471 472
enum mp3_action
MadDecoder::DecodeNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
473
{
474 475 476 477 478 479 480 481 482
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
		return DECODE_BREAK;

	if (mad_frame_decode(&frame, &stream)) {
		if (stream.error == MAD_ERROR_LOSTSYNC) {
			signed long tagsize = id3_tag_query(stream.this_frame,
							    stream.bufend -
							    stream.this_frame);
Avuton Olrich's avatar
Avuton Olrich committed
483
			if (tagsize > 0) {
484
				mad_stream_skip(&stream, tagsize);
485 486 487
				return DECODE_CONT;
			}
		}
488

489
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
490 491 492 493 494
	}

	return DECODE_OK;
}

495
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
496 497 498 499
static constexpr unsigned XI_MAGIC = (('X' << 8) | 'i');
static constexpr unsigned NG_MAGIC = (('n' << 8) | 'g');
static constexpr unsigned IN_MAGIC = (('I' << 8) | 'n');
static constexpr unsigned FO_MAGIC = (('f' << 8) | 'o');
500 501

enum xing_magic {
502
	XING_MAGIC_XING, /* VBR */
503
	XING_MAGIC_INFO  /* CBR */
504
};
Warren Dukes's avatar
Warren Dukes committed
505 506

struct xing {
507 508 509 510 511 512
	long flags;             /* valid fields (see below) */
	unsigned long frames;   /* total number of frames */
	unsigned long bytes;    /* total number of bytes */
	unsigned char toc[100]; /* 100-point seek table */
	long scale;             /* VBR quality */
	enum xing_magic magic;  /* header magic */
Warren Dukes's avatar
Warren Dukes committed
513 514
};

515 516 517 518
static constexpr unsigned XING_FRAMES = 1;
static constexpr unsigned XING_BYTES = 2;
static constexpr unsigned XING_TOC = 4;
static constexpr unsigned XING_SCALE = 8;
Warren Dukes's avatar
Warren Dukes committed
519

520
struct lame_version {
521 522
	unsigned major;
	unsigned minor;
523 524
};

525
struct lame {
526
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
527
	struct lame_version version; /* struct containing just the version */
528
	float peak;             /* replaygain peak */
Max Kellermann's avatar
Max Kellermann committed
529 530 531 532
	float track_gain;       /* replaygain track gain */
	float album_gain;       /* replaygain album gain */
	int encoder_delay;      /* # of added samples at start of mp3 */
	int encoder_padding;    /* # of added samples at end of mp3 */
533
	int crc;                /* CRC of the first 190 bytes of this frame */
534 535
};

Max Kellermann's avatar
Max Kellermann committed
536 537
static bool
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
Warren Dukes's avatar
Warren Dukes committed
538
{
539
	int bitlen = *oldbitlen;
Warren Dukes's avatar
Warren Dukes committed
540

Max Kellermann's avatar
Max Kellermann committed
541 542 543
	if (bitlen < 16)
		return false;

544
	const unsigned long bits = mad_bit_read(ptr, 16);
545 546
	bitlen -= 16;

547
	if (bits == XI_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
548 549 550 551 552 553
		if (bitlen < 16)
			return false;

		if (mad_bit_read(ptr, 16) != NG_MAGIC)
			return false;

554
		bitlen -= 16;
555 556
		xing->magic = XING_MAGIC_XING;
	} else if (bits == IN_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
557 558 559 560 561 562
		if (bitlen < 16)
			return false;

		if (mad_bit_read(ptr, 16) != FO_MAGIC)
			return false;

563 564
		bitlen -= 16;
		xing->magic = XING_MAGIC_INFO;
565 566 567
	}
	else if (bits == NG_MAGIC) xing->magic = XING_MAGIC_XING;
	else if (bits == FO_MAGIC) xing->magic = XING_MAGIC_INFO;
Max Kellermann's avatar
Max Kellermann committed
568 569
	else
		return false;
570

Max Kellermann's avatar
Max Kellermann committed
571 572
	if (bitlen < 32)
		return false;
573
	xing->flags = mad_bit_read(ptr, 32);
574 575 576
	bitlen -= 32;

	if (xing->flags & XING_FRAMES) {
Max Kellermann's avatar
Max Kellermann committed
577 578
		if (bitlen < 32)
			return false;
579
		xing->frames = mad_bit_read(ptr, 32);
580 581 582 583
		bitlen -= 32;
	}

	if (xing->flags & XING_BYTES) {
Max Kellermann's avatar
Max Kellermann committed
584 585
		if (bitlen < 32)
			return false;
586
		xing->bytes = mad_bit_read(ptr, 32);
587 588
		bitlen -= 32;
	}
Warren Dukes's avatar
Warren Dukes committed
589

590
	if (xing->flags & XING_TOC) {
Max Kellermann's avatar
Max Kellermann committed
591 592
		if (bitlen < 800)
			return false;
593 594
		for (unsigned i = 0; i < 100; ++i)
			xing->toc[i] = mad_bit_read(ptr, 8);
595 596 597 598
		bitlen -= 800;
	}

	if (xing->flags & XING_SCALE) {
Max Kellermann's avatar
Max Kellermann committed
599 600
		if (bitlen < 32)
			return false;
601
		xing->scale = mad_bit_read(ptr, 32);
602 603 604
		bitlen -= 32;
	}

605 606
	/* Make sure we consume no less than 120 bytes (960 bits) in hopes that
	 * the LAME tag is found there, and not right after the Xing header */
607
	const int bitsleft = 960 - (*oldbitlen - bitlen);
Max Kellermann's avatar
Max Kellermann committed
608 609
	if (bitsleft < 0)
		return false;
610 611 612 613 614
	else if (bitsleft > 0) {
		mad_bit_read(ptr, bitsleft);
		bitlen -= bitsleft;
	}

615
	*oldbitlen = bitlen;
616

Max Kellermann's avatar
Max Kellermann committed
617
	return true;
Warren Dukes's avatar
Warren Dukes committed
618 619
}

Max Kellermann's avatar
Max Kellermann committed
620 621
static bool
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
622 623 624
{
	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
	 * not all 36 bytes (288 bits) are there. */
625
	if (*bitlen < 288)
Max Kellermann's avatar
Max Kellermann committed
626
		return false;
627

628
	for (unsigned i = 0; i < 9; i++)
629
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
630 631
	lame->encoder[9] = '\0';

632 633
	*bitlen -= 72;

634 635 636
	/* This is technically incorrect, since the encoder might not be lame.
	 * But there's no other way to determine if this is a lame tag, and we
	 * wouldn't want to go reading a tag that's not there. */
637
	if (!StringStartsWith(lame->encoder, "LAME"))
Max Kellermann's avatar
Max Kellermann committed
638
		return false;
639 640 641

	if (sscanf(lame->encoder+4, "%u.%u",
	           &lame->version.major, &lame->version.minor) != 2)
Max Kellermann's avatar
Max Kellermann committed
642
		return false;
643

644 645
	FormatDebug(mad_domain, "detected LAME version %i.%i (\"%s\")",
		    lame->version.major, lame->version.minor, lame->encoder);
646 647 648 649 650 651 652 653

	/* The reference volume was changed from the 83dB used in the
	 * ReplayGain spec to 89dB in lame 3.95.1.  Bump the gain for older
	 * versions, since everyone else uses 89dB instead of 83dB.
	 * Unfortunately, lame didn't differentiate between 3.95 and 3.95.1, so
	 * it's impossible to make the proper adjustment for 3.95.
	 * Fortunately, 3.95 was only out for about a day before 3.95.1 was
	 * released. -- tmz */
654
	int adj = 0;
655 656 657
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;
658 659 660

	mad_bit_read(ptr, 16);

661
	lame->peak = mad_f_todouble(mad_bit_read(ptr, 32) << 5); /* peak */
662
	FormatDebug(mad_domain, "LAME peak found: %f", lame->peak);
663

Max Kellermann's avatar
Max Kellermann committed
664
	lame->track_gain = 0;
665 666 667
	unsigned name = mad_bit_read(ptr, 3); /* gain name */
	unsigned orig = mad_bit_read(ptr, 3); /* gain originator */
	unsigned sign = mad_bit_read(ptr, 1); /* sign bit */
668
	int gain = mad_bit_read(ptr, 9); /* gain*10 */
669
	if (gain && name == 1 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
670
		lame->track_gain = ((sign ? -gain : gain) / 10.0) + adj;
671 672
		FormatDebug(mad_domain, "LAME track gain found: %f",
			    lame->track_gain);
673
	}
674

675 676 677 678
	/* tmz reports that this isn't currently written by any version of lame
	 * (as of 3.97).  Since we have no way of testing it, don't use it.
	 * Wouldn't want to go blowing someone's ears just because we read it
	 * wrong. :P -- jat */
Max Kellermann's avatar
Max Kellermann committed
679
	lame->album_gain = 0;
680 681 682 683 684 685
#if 0
	name = mad_bit_read(ptr, 3); /* gain name */
	orig = mad_bit_read(ptr, 3); /* gain originator */
	sign = mad_bit_read(ptr, 1); /* sign bit */
	gain = mad_bit_read(ptr, 9); /* gain*10 */
	if (gain && name == 2 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
686
		lame->album_gain = ((sign ? -gain : gain) / 10.0) + adj;
687 688
		FormatDebug(mad_domain, "LAME album gain found: %f",
			    lame->track_gain);
689
	}
690
#else
691
	mad_bit_read(ptr, 16);
692 693
#endif

694 695
	mad_bit_read(ptr, 16);

Max Kellermann's avatar
Max Kellermann committed
696 697
	lame->encoder_delay = mad_bit_read(ptr, 12);
	lame->encoder_padding = mad_bit_read(ptr, 12);
698

699 700
	FormatDebug(mad_domain, "encoder delay is %i, encoder padding is %i",
		    lame->encoder_delay, lame->encoder_padding);
701

702 703 704 705 706
	mad_bit_read(ptr, 80);

	lame->crc = mad_bit_read(ptr, 16);

	*bitlen -= 216;
707

Max Kellermann's avatar
Max Kellermann committed
708
	return true;
709 710
}

711
static inline SongTime
712 713
mp3_frame_duration(const struct mad_frame *frame)
{
714
	return ToSongTime(frame->header.duration);
715 716
}

717
inline offset_type
718
MadDecoder::ThisFrameOffset() const
719
{
720
	auto offset = input_stream.GetOffset();
721

722 723
	if (stream.this_frame != nullptr)
		offset -= stream.bufend - stream.this_frame;
724
	else
725
		offset -= stream.bufend - stream.buffer;
726

727 728 729
	return offset;
}

730
inline offset_type
731
MadDecoder::RestIncludingThisFrame() const
732
{
733
	return input_stream.GetSize() - ThisFrameOffset();
734 735
}

736 737
inline void
MadDecoder::FileSizeToSongLength()
738
{
739
	if (input_stream.KnownSize()) {
740
		offset_type rest = RestIncludingThisFrame();
741

742 743 744 745 746
		const SongTime frame_duration = mp3_frame_duration(&frame);
		const SongTime duration =
			SongTime::FromScale<uint64_t>(rest,
						      frame.header.bitrate / 8);
		total_time = duration;
747

748 749 750 751
		max_frames = (frame_duration.IsPositive()
			      ? duration.count() / frame_duration.count()
			      : 0)
			+ FRAMES_CUSHION;
752
	} else {
753
		max_frames = FRAMES_CUSHION;
754
		total_time = SignedSongTime::Negative();
755 756 757
	}
}

758
inline bool
Max Kellermann's avatar
Max Kellermann committed
759
MadDecoder::DecodeFirstFrame(Tag **tag)
760
{
761
	struct xing xing;
762
	xing.frames = 0;
763

Max Kellermann's avatar
Max Kellermann committed
764
	while (true) {
765
		enum mp3_action ret;
766
		do {
767
			ret = DecodeNextFrameHeader(tag);
768 769
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
770
			return false;
771
		if (ret == DECODE_SKIP) continue;
772

773
		do {
774
			ret = DecodeNextFrame();
775 776
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
777
			return false;
778
		if (ret == DECODE_OK) break;
Avuton Olrich's avatar
Avuton Olrich committed
779 780
	}

781 782
	struct mad_bitptr ptr = stream.anc_ptr;
	int bitlen = stream.anc_bitlen;
783

784
	FileSizeToSongLength();
785

786 787 788
	/*
	 * if an xing tag exists, use that!
	 */
789
	if (parse_xing(&xing, &ptr, &bitlen)) {
790
		mute_frame = MUTEFRAME_SKIP;
791

792
		if ((xing.flags & XING_FRAMES) && xing.frames) {
793
			mad_timer_t duration = frame.header.duration;
Avuton Olrich's avatar
Avuton Olrich committed
794
			mad_timer_multiply(&duration, xing.frames);
795
			total_time = ToSongTime(duration);
796
			max_frames = xing.frames;
Warren Dukes's avatar
Warren Dukes committed
797
		}
798

799
		struct lame lame;
800
		if (parse_lame(&lame, &ptr, &bitlen)) {
801
			if (gapless_playback && input_stream.IsSeekable()) {
802
				drop_start_samples = lame.encoder_delay +
803
				                           DECODERDELAY;
804
				drop_end_samples = lame.encoder_padding;
805 806 807 808
			}

			/* Album gain isn't currently used.  See comment in
			 * parse_lame() for details. -- jat */
809
			if (decoder != nullptr && !found_replay_gain &&
Max Kellermann's avatar
Max Kellermann committed
810
			    lame.track_gain) {
811
				ReplayGainInfo rgi;
812
				rgi.Clear();
813 814
				rgi.tuples[REPLAY_GAIN_TRACK].gain = lame.track_gain;
				rgi.tuples[REPLAY_GAIN_TRACK].peak = lame.peak;
815
				decoder_replay_gain(*decoder, &rgi);
816 817
			}
		}
818
	}
Warren Dukes's avatar
Warren Dukes committed
819

820
	if (!max_frames)
Max Kellermann's avatar
Max Kellermann committed
821
		return false;
822

823
	if (max_frames > 8 * 1024 * 1024) {
824 825 826
		FormatWarning(mad_domain,
			      "mp3 file header indicates too many frames: %lu",
			      max_frames);
Max Kellermann's avatar
Max Kellermann committed
827
		return false;
828 829
	}

Max Kellermann's avatar
Max Kellermann committed
830
	return true;
Warren Dukes's avatar
Warren Dukes committed
831 832
}

833
MadDecoder::~MadDecoder()
Avuton Olrich's avatar
Avuton Olrich committed
834
{
835 836 837
	mad_synth_finish(&synth);
	mad_frame_finish(&frame);
	mad_stream_finish(&stream);
Warren Dukes's avatar
Warren Dukes committed
838

839 840
	delete[] frame_offsets;
	delete[] times;
Warren Dukes's avatar
Warren Dukes committed
841 842 843
}

/* this is primarily used for getting total time for tags */
844
static std::pair<bool, SignedSongTime>
845
mad_decoder_total_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
846
{
847 848
	MadDecoder data(nullptr, is);
	return data.DecodeFirstFrame(nullptr)
849 850
		? std::make_pair(true, data.total_time)
		: std::make_pair(false, SignedSongTime::Negative());
Warren Dukes's avatar
Warren Dukes committed
851 852
}

853
long
854
MadDecoder::TimeToFrame(SongTime t) const
855 856 857
{
	unsigned long i;

858
	for (i = 0; i < highest_frame; ++i) {
859
		auto frame_time = ToSongTime(times[i]);
860 861 862 863 864 865 866
		if (frame_time >= t)
			break;
	}

	return i;
}

867 868
void
MadDecoder::UpdateTimerNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
869
{
870 871 872 873 874 875 876 877
	if (current_frame >= highest_frame) {
		/* record this frame's properties in frame_offsets
		   (for seeking) and times */
		bit_rate = frame.header.bitrate;

		if (current_frame >= max_frames)
			/* cap current_frame */
			current_frame = max_frames - 1;
878
		else
879
			highest_frame++;
880

881
		frame_offsets[current_frame] = ThisFrameOffset();
882

883 884
		mad_timer_add(&timer, frame.header.duration);
		times[current_frame] = timer;
885
	} else
886 887
		/* get the new timer value from "times" */
		timer = times[current_frame];
888

889
	current_frame++;
890
	elapsed_time = ToSongTime(timer);
891 892
}

893
DecoderCommand
894
MadDecoder::SendPCM(unsigned i, unsigned pcm_length)
895
{
896
	unsigned max_samples = sizeof(output_buffer) /
897 898
		sizeof(output_buffer[0]) /
		MAD_NCHANNELS(&frame.header);
899 900 901 902 903 904 905 906

	while (i < pcm_length) {
		unsigned int num_samples = pcm_length - i;
		if (num_samples > max_samples)
			num_samples = max_samples;

		i += num_samples;

907
		mad_fixed_to_24_buffer(output_buffer, &synth,
908
				       i - num_samples, i,
909 910
				       MAD_NCHANNELS(&frame.header));
		num_samples *= MAD_NCHANNELS(&frame.header);
911

912
		auto cmd = decoder_data(*decoder, input_stream, output_buffer,
913 914 915
					sizeof(output_buffer[0]) * num_samples,
					bit_rate / 1000);
		if (cmd != DecoderCommand::NONE)
916 917 918
			return cmd;
	}

919
	return DecoderCommand::NONE;
920 921
}

922
inline DecoderCommand
923
MadDecoder::SyncAndSend()
924
{
925 926 927 928 929 930 931 932 933
	mad_synth_frame(&synth, &frame);

	if (!found_first_frame) {
		unsigned int samples_per_frame = synth.pcm.length;
		drop_start_frames = drop_start_samples / samples_per_frame;
		drop_end_frames = drop_end_samples / samples_per_frame;
		drop_start_samples = drop_start_samples % samples_per_frame;
		drop_end_samples = drop_end_samples % samples_per_frame;
		found_first_frame = true;
934 935
	}

936 937
	if (drop_start_frames > 0) {
		drop_start_frames--;
938
		return DecoderCommand::NONE;
939 940
	} else if ((drop_end_frames > 0) &&
		   (current_frame == (max_frames + 1 - drop_end_frames))) {
941 942
		/* stop decoding, effectively dropping all remaining
		   frames */
943
		return DecoderCommand::STOP;
944 945
	}

946 947 948 949 950
	unsigned i = 0;
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
951

952 953 954 955
	unsigned pcm_length = synth.pcm.length;
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames)) {
		if (drop_end_samples >= pcm_length)
956 957
			pcm_length = 0;
		else
958
			pcm_length -= drop_end_samples;
959 960
	}

961 962
	auto cmd = SendPCM(i, pcm_length);
	if (cmd != DecoderCommand::NONE)
963 964
		return cmd;

965 966
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames))
967 968
		/* stop decoding, effectively dropping
		 * all remaining samples */
969
		return DecoderCommand::STOP;
970

971
	return DecoderCommand::NONE;
972 973
}

974 975
inline bool
MadDecoder::Read()
976
{
977
	UpdateTimerNextFrame();
Warren Dukes's avatar
Warren Dukes committed
978

979
	switch (mute_frame) {
980 981
		DecoderCommand cmd;

Avuton Olrich's avatar
Avuton Olrich committed
982
	case MUTEFRAME_SKIP:
983
		mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
984 985
		break;
	case MUTEFRAME_SEEK:
986
		if (elapsed_time >= seek_time)
987
			mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
988
		break;
989
	case MUTEFRAME_NONE:
990
		cmd = SyncAndSend();
991
		if (cmd == DecoderCommand::SEEK) {
992
			assert(input_stream.IsSeekable());
993

994
			unsigned long j =
995
				TimeToFrame(decoder_seek_time(*decoder));
996 997 998
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
999
					decoder_command_finished(*decoder);
Avuton Olrich's avatar
Avuton Olrich committed
1000
				} else
1001
					decoder_seek_error(*decoder);
Max Kellermann's avatar
Max Kellermann committed
1002
			} else {
1003
				seek_time = decoder_seek_time(*decoder);
1004
				mute_frame = MUTEFRAME_SEEK;
1005
				decoder_command_finished(*decoder);
Max Kellermann's avatar
Max Kellermann committed
1006
			}
1007
		} else if (cmd != DecoderCommand::NONE)
1008
			return false;
Warren Dukes's avatar
Warren Dukes committed
1009 1010
	}

Max Kellermann's avatar
Max Kellermann committed
1011
	while (true) {
1012
		enum mp3_action ret;
1013
		do {
Max Kellermann's avatar
Max Kellermann committed
1014
			Tag *tag = nullptr;
1015

1016
			ret = DecodeNextFrameHeader(&tag);
1017

1018
			if (tag != nullptr) {
1019
				decoder_tag(*decoder, input_stream,
1020
					    std::move(*tag));
Max Kellermann's avatar
Max Kellermann committed
1021
				delete tag;
1022
			}
1023 1024
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
1025
			return false;
1026 1027

		const bool skip = ret == DECODE_SKIP;
1028

1029
		if (mute_frame == MUTEFRAME_NONE) {
1030
			do {
1031
				ret = DecodeNextFrame();
1032 1033
			} while (ret == DECODE_CONT);
			if (ret == DECODE_BREAK)
1034
				return false;
Warren Dukes's avatar
Warren Dukes committed
1035
		}
1036

Avuton Olrich's avatar
Avuton Olrich committed
1037
		if (!skip && ret == DECODE_OK)
1038
			return true;
Warren Dukes's avatar
Warren Dukes committed
1039 1040 1041
	}
}

1042
static void
1043
mp3_decode(Decoder &decoder, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
1044
{
1045
	MadDecoder data(&decoder, input_stream);
1046

Max Kellermann's avatar
Max Kellermann committed
1047
	Tag *tag = nullptr;
1048
	if (!data.DecodeFirstFrame(&tag)) {
Max Kellermann's avatar
Max Kellermann committed
1049
		delete tag;
1050

1051
		if (decoder_get_command(decoder) == DecoderCommand::NONE)
1052
			LogError(mad_domain,
Max Kellermann's avatar
Max Kellermann committed
1053
				 "input/Input does not appear to be a mp3 bit stream");
1054
		return;
Warren Dukes's avatar
Warren Dukes committed
1055 1056
	}

1057 1058
	data.AllocateBuffers();

1059
	Error error;
1060 1061
	AudioFormat audio_format;
	if (!audio_format_init_checked(audio_format,
1062
				       data.frame.header.samplerate,
1063
				       SampleFormat::S24_P32,
1064
				       MAD_NCHANNELS(&data.frame.header),
1065
				       error)) {
1066
		LogError(error);
Max Kellermann's avatar
Max Kellermann committed
1067
		delete tag;
1068 1069
		return;
	}
Avuton Olrich's avatar
Avuton Olrich committed
1070

1071
	decoder_initialized(decoder, audio_format,
1072
			    input_stream.IsSeekable(),
1073
			    data.total_time);
Warren Dukes's avatar
Warren Dukes committed
1074

1075
	if (tag != nullptr) {
1076
		decoder_tag(decoder, input_stream, std::move(*tag));
Max Kellermann's avatar
Max Kellermann committed
1077
		delete tag;
1078 1079
	}

1080
	while (data.Read()) {}
Warren Dukes's avatar
Warren Dukes committed
1081 1082
}

1083
static bool
1084
mad_decoder_scan_stream(InputStream &is,
1085
			const TagHandler &handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
1086
{
1087 1088
	const auto result = mad_decoder_total_file_time(is);
	if (!result.first)
1089
		return false;
Warren Dukes's avatar
Warren Dukes committed
1090

1091 1092 1093
	if (!result.second.IsNegative())
		tag_handler_invoke_duration(handler, handler_ctx,
					    SongTime(result.second));
1094
	return true;
Warren Dukes's avatar
Warren Dukes committed
1095 1096
}

1097 1098
static const char *const mp3_suffixes[] = { "mp3", "mp2", nullptr };
static const char *const mp3_mime_types[] = { "audio/mpeg", nullptr };
Warren Dukes's avatar
Warren Dukes committed
1099

1100
const struct DecoderPlugin mad_decoder_plugin = {
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
	"mad",
	mp3_plugin_init,
	nullptr,
	mp3_decode,
	nullptr,
	nullptr,
	mad_decoder_scan_stream,
	nullptr,
	mp3_suffixes,
	mp3_mime_types,
Warren Dukes's avatar
Warren Dukes committed
1111
};