MadDecoderPlugin.cxx 24.4 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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/Block.hxx"
25
#include "tag/Id3Scan.hxx"
26
#include "tag/Id3ReplayGain.hxx"
27 28
#include "tag/Rva2.hxx"
#include "tag/Handler.hxx"
29
#include "tag/ReplayGain.hxx"
30
#include "tag/MixRamp.hxx"
31
#include "CheckAudioFormat.hxx"
32
#include "util/StringCompare.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
#include "tag/Id3Unique.hxx"
40 41
#include <id3tag.h>
#endif
42

43 44
#include <stdexcept>

45 46 47 48 49
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

50
static constexpr unsigned long FRAMES_CUSHION = 2000;
Warren Dukes's avatar
Warren Dukes committed
51

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

59 60 61 62 63
enum muteframe {
	MUTEFRAME_NONE,
	MUTEFRAME_SKIP,
	MUTEFRAME_SEEK
};
64

65
/* the number of samples of silence the decoder inserts at start */
66
static constexpr unsigned DECODERDELAY = 529;
67

68
static constexpr bool DEFAULT_GAPLESS_MP3_PLAYBACK = true;
69

70 71
static constexpr Domain mad_domain("mad");

Max Kellermann's avatar
Max Kellermann committed
72
static bool gapless_playback;
73

74 75
gcc_const
static SongTime
76
ToSongTime(mad_timer_t t) noexcept
77 78 79 80
{
	return SongTime::FromMS(mad_timer_count(t, MAD_UNITS_MILLISECONDS));
}

81 82
static inline int32_t
mad_fixed_to_24_sample(mad_fixed_t sample)
Avuton Olrich's avatar
Avuton Olrich committed
83
{
84 85 86
	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
87

88 89
	/* round */
	sample = sample + (1L << (MAD_F_FRACBITS - bits));
Warren Dukes's avatar
Warren Dukes committed
90

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

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

101 102 103 104
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)
105
{
106 107
	for (unsigned i = start; i < end; ++i)
		for (unsigned c = 0; c < num_channels; ++c)
108
			*dest++ = mad_fixed_to_24_sample(synth->pcm.samples[c][i]);
109 110
}

111
static bool
112
mp3_plugin_init(const ConfigBlock &block)
113
{
114 115
	gapless_playback = block.GetBlockValue("gapless",
					       DEFAULT_GAPLESS_MP3_PLAYBACK);
116
	return true;
117 118
}

119
struct MadDecoder {
120 121 122
	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
123 124 125 126
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
Max Kellermann's avatar
Max Kellermann committed
127 128
	unsigned char input_buffer[READ_BUFFER_SIZE];
	int32_t output_buffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
129
	SignedSongTime total_time;
130 131
	SongTime elapsed_time;
	SongTime seek_time;
132 133 134 135 136 137 138 139 140 141 142 143 144
	enum muteframe mute_frame = MUTEFRAME_NONE;
	long *frame_offsets = nullptr;
	mad_timer_t *times = nullptr;
	unsigned long highest_frame = 0;
	unsigned long max_frames = 0;
	unsigned long current_frame = 0;
	unsigned int drop_start_frames = 0;
	unsigned int drop_end_frames = 0;
	unsigned int drop_start_samples = 0;
	unsigned int drop_end_samples = 0;
	bool found_replay_gain = false;
	bool found_first_frame = false;
	bool decoded_first_frame = false;
Max Kellermann's avatar
Max Kellermann committed
145
	unsigned long bit_rate;
146
	DecoderClient *const client;
147
	InputStream &input_stream;
148
	enum mad_layer layer = mad_layer(0);
149

150
	MadDecoder(DecoderClient *client, InputStream &input_stream);
151 152 153 154
	~MadDecoder();

	bool Seek(long offset);
	bool FillBuffer();
155 156
	void ParseId3(size_t tagsize, Tag *tag);
	enum mp3_action DecodeNextFrameHeader(Tag *tag);
157 158 159
	enum mp3_action DecodeNextFrame();

	gcc_pure
160
	offset_type ThisFrameOffset() const noexcept;
161 162

	gcc_pure
163
	offset_type RestIncludingThisFrame() const noexcept;
164 165 166 167 168 169

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

170
	bool DecodeFirstFrame(Tag *tag);
171

172 173 174 175 176 177 178 179 180
	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];
	}

181
	gcc_pure
182
	long TimeToFrame(SongTime t) const noexcept;
183 184 185 186

	void UpdateTimerNextFrame();

	/**
187 188
	 * Sends the synthesized current frame via
	 * DecoderClient::SubmitData().
189
	 */
190
	DecoderCommand SendPCM(unsigned i, unsigned pcm_length);
191 192 193

	/**
	 * Synthesize the current frame and send it via
194
	 * DecoderClient::SubmitData().
195
	 */
196
	DecoderCommand SyncAndSend();
197 198

	bool Read();
Max Kellermann's avatar
Max Kellermann committed
199
};
Warren Dukes's avatar
Warren Dukes committed
200

201
MadDecoder::MadDecoder(DecoderClient *_client,
202
		       InputStream &_input_stream)
203
	:client(_client), input_stream(_input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
204
{
205 206 207 208 209
	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
210 211
}

212 213
inline bool
MadDecoder::Seek(long offset)
Avuton Olrich's avatar
Avuton Olrich committed
214
{
215 216
	try {
		input_stream.LockSeek(offset);
217
	} catch (...) {
Max Kellermann's avatar
Max Kellermann committed
218
		return false;
219
	}
220

221 222
	mad_stream_buffer(&stream, input_buffer, 0);
	stream.error = MAD_ERROR_NONE;
223

Max Kellermann's avatar
Max Kellermann committed
224
	return true;
225 226
}

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

233 234 235 236
	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
237
		length = READ_BUFFER_SIZE - remaining;
Avuton Olrich's avatar
Avuton Olrich committed
238
	} else {
Max Kellermann's avatar
Max Kellermann committed
239 240
		remaining = 0;
		length = READ_BUFFER_SIZE;
241
		dest = input_buffer;
Warren Dukes's avatar
Warren Dukes committed
242 243
	}

244 245
	/* 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
246
	if (length == 0)
Max Kellermann's avatar
Max Kellermann committed
247
		return false;
248

249
	length = decoder_read(client, input_stream, dest, length);
Max Kellermann's avatar
Max Kellermann committed
250
	if (length == 0)
Max Kellermann's avatar
Max Kellermann committed
251
		return false;
252

253 254
	mad_stream_buffer(&stream, input_buffer, length + remaining);
	stream.error = MAD_ERROR_NONE;
Warren Dukes's avatar
Warren Dukes committed
255

Max Kellermann's avatar
Max Kellermann committed
256
	return true;
Warren Dukes's avatar
Warren Dukes committed
257 258
}

259
#ifdef ENABLE_ID3TAG
260 261
gcc_pure
static MixRampInfo
262
parse_id3_mixramp(struct id3_tag *tag) noexcept
263
{
264
	MixRampInfo result;
265

266 267
	struct id3_frame *frame;
	for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
268 269 270
		if (frame->nfields < 3)
			continue;

271
		char *const key = (char *)
272 273
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
274
		char *const value = (char *)
275 276 277
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

278
		ParseMixRampTag(result, key, value);
279 280 281 282 283

		free(key);
		free(value);
	}

284
	return result;
285 286 287
}
#endif

288
inline void
289
MadDecoder::ParseId3(size_t tagsize, Tag *mpd_tag)
Avuton Olrich's avatar
Avuton Olrich committed
290
{
291
#ifdef ENABLE_ID3TAG
292
	std::unique_ptr<id3_byte_t[]> allocated;
293

294
	const id3_length_t count = stream.bufend - stream.this_frame;
295

296
	const id3_byte_t *id3_data;
Avuton Olrich's avatar
Avuton Olrich committed
297
	if (tagsize <= count) {
298 299
		id3_data = stream.this_frame;
		mad_stream_skip(&(stream), tagsize);
Avuton Olrich's avatar
Avuton Olrich committed
300
	} else {
301 302
		allocated.reset(new id3_byte_t[tagsize]);
		memcpy(allocated.get(), stream.this_frame, count);
303
		mad_stream_skip(&(stream), count);
304

305
		if (!decoder_read_full(client, input_stream,
306
				       allocated.get() + count, tagsize - count)) {
307
			LogDebug(mad_domain, "error parsing ID3 tag");
Max Kellermann's avatar
Max Kellermann committed
308
			return;
Warren Dukes's avatar
Warren Dukes committed
309
		}
310

311
		id3_data = allocated.get();
312 313
	}

314
	const UniqueId3Tag id3_tag(id3_tag_parse(id3_data, tagsize));
315
	if (id3_tag == nullptr)
Max Kellermann's avatar
Max Kellermann committed
316
		return;
317

318 319
	if (mpd_tag != nullptr)
		*mpd_tag = tag_id3_import(id3_tag.get());
320

321
	if (client != nullptr) {
322
		ReplayGainInfo rgi;
323

324
		if (Id3ToReplayGainInfo(rgi, id3_tag.get())) {
325
			client->SubmitReplayGain(&rgi);
326
			found_replay_gain = true;
327
		}
328

329
		client->SubmitMixRamp(parse_id3_mixramp(id3_tag.get()));
330 331
	}

332
#else /* !ENABLE_ID3TAG */
333 334 335 336 337
	(void)mpd_tag;

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

338
	size_t count = stream.bufend - stream.this_frame;
339 340

	if (tagsize <= count) {
341
		mad_stream_skip(&stream, tagsize);
342
	} else {
343
		mad_stream_skip(&stream, count);
344
		decoder_skip(client, input_stream, tagsize - count);
345
	}
346
#endif
347 348
}

349
#ifndef ENABLE_ID3TAG
350 351 352
/**
 * This function emulates libid3tag when it is disabled.  Instead of
 * doing a real analyzation of the frame, it just checks whether the
353 354
 * frame begins with the string "ID3".  If so, it returns the length
 * of the ID3 frame.
355 356 357 358
 */
static signed long
id3_tag_query(const void *p0, size_t length)
{
359
	const char *p = (const char *)p0;
360

361 362
	return length >= 10 && memcmp(p, "ID3", 3) == 0
		? (p[8] << 7) + p[9] + 10
363 364
		: 0;
}
365
#endif /* !ENABLE_ID3TAG */
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380
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;
}

381
enum mp3_action
382
MadDecoder::DecodeNextFrameHeader(Tag *tag)
Avuton Olrich's avatar
Avuton Olrich committed
383
{
384 385 386
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
		return DECODE_BREAK;
387

388 389 390 391 392
	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
393 394

			if (tagsize > 0) {
395
				ParseId3((size_t)tagsize, tag);
396 397 398
				return DECODE_CONT;
			}
		}
399

400
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
401
	}
402

403 404 405
	enum mad_layer new_layer = frame.header.layer;
	if (layer == (mad_layer)0) {
		if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
406
			/* Only layer 2 and 3 have been tested to work */
407
			return DECODE_SKIP;
408
		}
409 410 411

		layer = new_layer;
	} else if (new_layer != layer) {
412
		/* Don't decode frames with a different layer than the first */
413 414
		return DECODE_SKIP;
	}
Warren Dukes's avatar
Warren Dukes committed
415 416 417 418

	return DECODE_OK;
}

419 420
enum mp3_action
MadDecoder::DecodeNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
421
{
422 423 424 425 426 427 428 429 430
	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
431
			if (tagsize > 0) {
432
				mad_stream_skip(&stream, tagsize);
433 434 435
				return DECODE_CONT;
			}
		}
436

437
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
438 439 440 441 442
	}

	return DECODE_OK;
}

443
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
444 445 446 447
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');
448

Warren Dukes's avatar
Warren Dukes committed
449
struct xing {
450 451 452 453 454
	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 */
Warren Dukes's avatar
Warren Dukes committed
455 456
};

457 458 459 460
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
461

462
struct lame_version {
463 464
	unsigned major;
	unsigned minor;
465 466
};

467
struct lame {
468
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
469
	struct lame_version version; /* struct containing just the version */
470
	float peak;             /* replaygain peak */
Max Kellermann's avatar
Max Kellermann committed
471 472 473 474
	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 */
475
	int crc;                /* CRC of the first 190 bytes of this frame */
476 477
};

Max Kellermann's avatar
Max Kellermann committed
478 479
static bool
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
Warren Dukes's avatar
Warren Dukes committed
480
{
481
	int bitlen = *oldbitlen;
Warren Dukes's avatar
Warren Dukes committed
482

Max Kellermann's avatar
Max Kellermann committed
483 484 485
	if (bitlen < 16)
		return false;

486
	const unsigned long bits = mad_bit_read(ptr, 16);
487 488
	bitlen -= 16;

489
	if (bits == XI_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
490 491 492 493 494 495
		if (bitlen < 16)
			return false;

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

496
		bitlen -= 16;
497
	} else if (bits == IN_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
498 499 500 501 502 503
		if (bitlen < 16)
			return false;

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

504
		bitlen -= 16;
505
	}
506
	else if (bits != NG_MAGIC && bits != FO_MAGIC)
Max Kellermann's avatar
Max Kellermann committed
507
		return false;
508

Max Kellermann's avatar
Max Kellermann committed
509 510
	if (bitlen < 32)
		return false;
511
	xing->flags = mad_bit_read(ptr, 32);
512 513 514
	bitlen -= 32;

	if (xing->flags & XING_FRAMES) {
Max Kellermann's avatar
Max Kellermann committed
515 516
		if (bitlen < 32)
			return false;
517
		xing->frames = mad_bit_read(ptr, 32);
518 519 520 521
		bitlen -= 32;
	}

	if (xing->flags & XING_BYTES) {
Max Kellermann's avatar
Max Kellermann committed
522 523
		if (bitlen < 32)
			return false;
524
		xing->bytes = mad_bit_read(ptr, 32);
525 526
		bitlen -= 32;
	}
Warren Dukes's avatar
Warren Dukes committed
527

528
	if (xing->flags & XING_TOC) {
Max Kellermann's avatar
Max Kellermann committed
529 530
		if (bitlen < 800)
			return false;
531 532
		for (unsigned i = 0; i < 100; ++i)
			xing->toc[i] = mad_bit_read(ptr, 8);
533 534 535 536
		bitlen -= 800;
	}

	if (xing->flags & XING_SCALE) {
Max Kellermann's avatar
Max Kellermann committed
537 538
		if (bitlen < 32)
			return false;
539
		xing->scale = mad_bit_read(ptr, 32);
540 541 542
		bitlen -= 32;
	}

543 544
	/* 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 */
545
	const int bitsleft = 960 - (*oldbitlen - bitlen);
Max Kellermann's avatar
Max Kellermann committed
546 547
	if (bitsleft < 0)
		return false;
548
	else if (bitsleft > 0) {
549
		mad_bit_skip(ptr, bitsleft);
550 551 552
		bitlen -= bitsleft;
	}

553
	*oldbitlen = bitlen;
554

Max Kellermann's avatar
Max Kellermann committed
555
	return true;
Warren Dukes's avatar
Warren Dukes committed
556 557
}

Max Kellermann's avatar
Max Kellermann committed
558 559
static bool
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
560 561 562
{
	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
	 * not all 36 bytes (288 bits) are there. */
563
	if (*bitlen < 288)
Max Kellermann's avatar
Max Kellermann committed
564
		return false;
565

566
	for (unsigned i = 0; i < 9; i++)
567
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
568 569
	lame->encoder[9] = '\0';

570 571
	*bitlen -= 72;

572 573 574
	/* 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. */
575
	if (!StringStartsWith(lame->encoder, "LAME"))
Max Kellermann's avatar
Max Kellermann committed
576
		return false;
577 578 579

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

582 583
	FormatDebug(mad_domain, "detected LAME version %i.%i (\"%s\")",
		    lame->version.major, lame->version.minor, lame->encoder);
584 585 586 587 588 589 590 591

	/* 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 */
592
	int adj = 0;
593 594 595
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;
596

597
	mad_bit_skip(ptr, 16);
598

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

Max Kellermann's avatar
Max Kellermann committed
602
	lame->track_gain = 0;
603 604 605
	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 */
606
	int gain = mad_bit_read(ptr, 9); /* gain*10 */
607
	if (gain && name == 1 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
608
		lame->track_gain = ((sign ? -gain : gain) / 10.0) + adj;
609 610
		FormatDebug(mad_domain, "LAME track gain found: %f",
			    lame->track_gain);
611
	}
612

613 614 615 616
	/* 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
617
	lame->album_gain = 0;
618 619 620 621 622 623
#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
624
		lame->album_gain = ((sign ? -gain : gain) / 10.0) + adj;
625 626
		FormatDebug(mad_domain, "LAME album gain found: %f",
			    lame->track_gain);
627
	}
628
#else
629
	mad_bit_skip(ptr, 16);
630 631
#endif

632
	mad_bit_skip(ptr, 16);
633

Max Kellermann's avatar
Max Kellermann committed
634 635
	lame->encoder_delay = mad_bit_read(ptr, 12);
	lame->encoder_padding = mad_bit_read(ptr, 12);
636

637 638
	FormatDebug(mad_domain, "encoder delay is %i, encoder padding is %i",
		    lame->encoder_delay, lame->encoder_padding);
639

640
	mad_bit_skip(ptr, 80);
641 642 643 644

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

	*bitlen -= 216;
645

Max Kellermann's avatar
Max Kellermann committed
646
	return true;
647 648
}

649
static inline SongTime
650 651
mp3_frame_duration(const struct mad_frame *frame)
{
652
	return ToSongTime(frame->header.duration);
653 654
}

655
inline offset_type
656
MadDecoder::ThisFrameOffset() const noexcept
657
{
658
	auto offset = input_stream.GetOffset();
659

660 661
	if (stream.this_frame != nullptr)
		offset -= stream.bufend - stream.this_frame;
662
	else
663
		offset -= stream.bufend - stream.buffer;
664

665 666 667
	return offset;
}

668
inline offset_type
669
MadDecoder::RestIncludingThisFrame() const noexcept
670
{
671
	return input_stream.GetSize() - ThisFrameOffset();
672 673
}

674 675
inline void
MadDecoder::FileSizeToSongLength()
676
{
677
	if (input_stream.KnownSize()) {
678
		offset_type rest = RestIncludingThisFrame();
679

680 681 682 683 684
		const SongTime frame_duration = mp3_frame_duration(&frame);
		const SongTime duration =
			SongTime::FromScale<uint64_t>(rest,
						      frame.header.bitrate / 8);
		total_time = duration;
685

686 687 688 689
		max_frames = (frame_duration.IsPositive()
			      ? duration.count() / frame_duration.count()
			      : 0)
			+ FRAMES_CUSHION;
690
	} else {
691
		max_frames = FRAMES_CUSHION;
692
		total_time = SignedSongTime::Negative();
693 694 695
	}
}

696
inline bool
697
MadDecoder::DecodeFirstFrame(Tag *tag)
698
{
699
	struct xing xing;
700

Max Kellermann's avatar
Max Kellermann committed
701
	while (true) {
702
		enum mp3_action ret;
703
		do {
704
			ret = DecodeNextFrameHeader(tag);
705 706
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
707
			return false;
708
		if (ret == DECODE_SKIP) continue;
709

710
		do {
711
			ret = DecodeNextFrame();
712 713
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
714
			return false;
715
		if (ret == DECODE_OK) break;
Avuton Olrich's avatar
Avuton Olrich committed
716 717
	}

718 719
	struct mad_bitptr ptr = stream.anc_ptr;
	int bitlen = stream.anc_bitlen;
720

721
	FileSizeToSongLength();
722

723 724 725
	/*
	 * if an xing tag exists, use that!
	 */
726
	if (parse_xing(&xing, &ptr, &bitlen)) {
727
		mute_frame = MUTEFRAME_SKIP;
728

729
		if ((xing.flags & XING_FRAMES) && xing.frames) {
730
			mad_timer_t duration = frame.header.duration;
Avuton Olrich's avatar
Avuton Olrich committed
731
			mad_timer_multiply(&duration, xing.frames);
732
			total_time = ToSongTime(duration);
733
			max_frames = xing.frames;
Warren Dukes's avatar
Warren Dukes committed
734
		}
735

736
		struct lame lame;
737
		if (parse_lame(&lame, &ptr, &bitlen)) {
738
			if (gapless_playback && input_stream.IsSeekable()) {
739
				drop_start_samples = lame.encoder_delay +
740
				                           DECODERDELAY;
741
				drop_end_samples = lame.encoder_padding;
742 743 744 745
			}

			/* Album gain isn't currently used.  See comment in
			 * parse_lame() for details. -- jat */
746
			if (client != nullptr && !found_replay_gain &&
Max Kellermann's avatar
Max Kellermann committed
747
			    lame.track_gain) {
748
				ReplayGainInfo rgi;
749
				rgi.Clear();
750 751
				rgi.track.gain = lame.track_gain;
				rgi.track.peak = lame.peak;
752
				client->SubmitReplayGain(&rgi);
753 754
			}
		}
755
	}
Warren Dukes's avatar
Warren Dukes committed
756

757
	if (!max_frames)
Max Kellermann's avatar
Max Kellermann committed
758
		return false;
759

760
	if (max_frames > 8 * 1024 * 1024) {
761 762 763
		FormatWarning(mad_domain,
			      "mp3 file header indicates too many frames: %lu",
			      max_frames);
Max Kellermann's avatar
Max Kellermann committed
764
		return false;
765 766
	}

Max Kellermann's avatar
Max Kellermann committed
767
	return true;
Warren Dukes's avatar
Warren Dukes committed
768 769
}

770
MadDecoder::~MadDecoder()
Avuton Olrich's avatar
Avuton Olrich committed
771
{
772 773 774
	mad_synth_finish(&synth);
	mad_frame_finish(&frame);
	mad_stream_finish(&stream);
Warren Dukes's avatar
Warren Dukes committed
775

776 777
	delete[] frame_offsets;
	delete[] times;
Warren Dukes's avatar
Warren Dukes committed
778 779
}

780
long
781
MadDecoder::TimeToFrame(SongTime t) const noexcept
782 783 784
{
	unsigned long i;

785
	for (i = 0; i < highest_frame; ++i) {
786
		auto frame_time = ToSongTime(times[i]);
787 788 789 790 791 792 793
		if (frame_time >= t)
			break;
	}

	return i;
}

794 795
void
MadDecoder::UpdateTimerNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
796
{
797 798 799 800 801 802 803 804
	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;
805
		else
806
			highest_frame++;
807

808
		frame_offsets[current_frame] = ThisFrameOffset();
809

810 811
		mad_timer_add(&timer, frame.header.duration);
		times[current_frame] = timer;
812
	} else
813 814
		/* get the new timer value from "times" */
		timer = times[current_frame];
815

816
	current_frame++;
817
	elapsed_time = ToSongTime(timer);
818 819
}

820
DecoderCommand
821
MadDecoder::SendPCM(unsigned i, unsigned pcm_length)
822
{
823
	unsigned max_samples = sizeof(output_buffer) /
824 825
		sizeof(output_buffer[0]) /
		MAD_NCHANNELS(&frame.header);
826 827 828 829 830 831 832 833

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

		i += num_samples;

834
		mad_fixed_to_24_buffer(output_buffer, &synth,
835
				       i - num_samples, i,
836 837
				       MAD_NCHANNELS(&frame.header));
		num_samples *= MAD_NCHANNELS(&frame.header);
838

839 840 841
		auto cmd = client->SubmitData(input_stream, output_buffer,
					      sizeof(output_buffer[0]) * num_samples,
					      bit_rate / 1000);
842
		if (cmd != DecoderCommand::NONE)
843 844 845
			return cmd;
	}

846
	return DecoderCommand::NONE;
847 848
}

849
inline DecoderCommand
850
MadDecoder::SyncAndSend()
851
{
852 853 854 855 856 857 858 859 860
	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;
861 862
	}

863 864
	if (drop_start_frames > 0) {
		drop_start_frames--;
865
		return DecoderCommand::NONE;
866 867
	} else if ((drop_end_frames > 0) &&
		   (current_frame == (max_frames + 1 - drop_end_frames))) {
868 869
		/* stop decoding, effectively dropping all remaining
		   frames */
870
		return DecoderCommand::STOP;
871 872
	}

873 874 875 876 877
	unsigned i = 0;
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
878

879 880 881 882
	unsigned pcm_length = synth.pcm.length;
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames)) {
		if (drop_end_samples >= pcm_length)
883 884
			pcm_length = 0;
		else
885
			pcm_length -= drop_end_samples;
886 887
	}

888 889
	auto cmd = SendPCM(i, pcm_length);
	if (cmd != DecoderCommand::NONE)
890 891
		return cmd;

892 893
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames))
894 895
		/* stop decoding, effectively dropping
		 * all remaining samples */
896
		return DecoderCommand::STOP;
897

898
	return DecoderCommand::NONE;
899 900
}

901 902
inline bool
MadDecoder::Read()
903
{
904
	UpdateTimerNextFrame();
Warren Dukes's avatar
Warren Dukes committed
905

906
	switch (mute_frame) {
907 908
		DecoderCommand cmd;

Avuton Olrich's avatar
Avuton Olrich committed
909
	case MUTEFRAME_SKIP:
910
		mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
911 912
		break;
	case MUTEFRAME_SEEK:
913
		if (elapsed_time >= seek_time)
914
			mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
915
		break;
916
	case MUTEFRAME_NONE:
917
		cmd = SyncAndSend();
918
		if (cmd == DecoderCommand::SEEK) {
919
			assert(input_stream.IsSeekable());
920

921 922
			const auto t = client->GetSeekTime();
			unsigned long j = TimeToFrame(t);
923 924 925
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
926
					client->CommandFinished();
Avuton Olrich's avatar
Avuton Olrich committed
927
				} else
928
					client->SeekError();
Max Kellermann's avatar
Max Kellermann committed
929
			} else {
930
				seek_time = t;
931
				mute_frame = MUTEFRAME_SEEK;
932
				client->CommandFinished();
Max Kellermann's avatar
Max Kellermann committed
933
			}
934
		} else if (cmd != DecoderCommand::NONE)
935
			return false;
Warren Dukes's avatar
Warren Dukes committed
936 937
	}

Max Kellermann's avatar
Max Kellermann committed
938
	while (true) {
939
		enum mp3_action ret;
940
		do {
941
			Tag tag;
942

943
			ret = DecodeNextFrameHeader(&tag);
944

945
			if (!tag.IsEmpty())
946
				client->SubmitTag(input_stream,
947
						  std::move(tag));
948 949
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
950
			return false;
951 952

		const bool skip = ret == DECODE_SKIP;
953

954
		if (mute_frame == MUTEFRAME_NONE) {
955
			do {
956
				ret = DecodeNextFrame();
957 958
			} while (ret == DECODE_CONT);
			if (ret == DECODE_BREAK)
959
				return false;
Warren Dukes's avatar
Warren Dukes committed
960
		}
961

Avuton Olrich's avatar
Avuton Olrich committed
962
		if (!skip && ret == DECODE_OK)
963
			return true;
Warren Dukes's avatar
Warren Dukes committed
964 965 966
	}
}

967
static void
968
mp3_decode(DecoderClient &client, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
969
{
970
	MadDecoder data(&client, input_stream);
971

972
	Tag tag;
973
	if (!data.DecodeFirstFrame(&tag)) {
974
		if (client.GetCommand() == DecoderCommand::NONE)
975
			LogError(mad_domain,
Max Kellermann's avatar
Max Kellermann committed
976
				 "input/Input does not appear to be a mp3 bit stream");
977
		return;
Warren Dukes's avatar
Warren Dukes committed
978 979
	}

980 981
	data.AllocateBuffers();

982 983 984 985 986
	client.Ready(CheckAudioFormat(data.frame.header.samplerate,
				      SampleFormat::S24_P32,
				      MAD_NCHANNELS(&data.frame.header)),
		     input_stream.IsSeekable(),
		     data.total_time);
Warren Dukes's avatar
Warren Dukes committed
987

988 989
	if (!tag.IsEmpty())
		client.SubmitTag(input_stream, std::move(tag));
990

991
	while (data.Read()) {}
Warren Dukes's avatar
Warren Dukes committed
992 993
}

994
static bool
995
mad_decoder_scan_stream(InputStream &is, TagHandler &handler) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
996
{
997 998
	MadDecoder data(nullptr, is);
	if (!data.DecodeFirstFrame(nullptr))
999
		return false;
Warren Dukes's avatar
Warren Dukes committed
1000

1001 1002
	if (!data.total_time.IsNegative())
		handler.OnDuration(SongTime(data.total_time));
1003 1004 1005 1006 1007 1008 1009 1010

	try {
		handler.OnAudioFormat(CheckAudioFormat(data.frame.header.samplerate,
						       SampleFormat::S24_P32,
						       MAD_NCHANNELS(&data.frame.header)));
	} catch (...) {
	}

1011
	return true;
Warren Dukes's avatar
Warren Dukes committed
1012 1013
}

1014 1015
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
1016

1017
const struct DecoderPlugin mad_decoder_plugin = {
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
	"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
1028
};