MadDecoderPlugin.cxx 25.7 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 "tag/Id3Scan.hxx"
25
#include "tag/Id3ReplayGain.hxx"
26
#include "tag/Handler.hxx"
27
#include "tag/ReplayGain.hxx"
28
#include "tag/MixRamp.hxx"
29
#include "CheckAudioFormat.hxx"
30
#include "util/Clamp.hxx"
31
#include "util/StringCompare.hxx"
32 33
#include "util/Domain.hxx"
#include "Log.hxx"
Warren Dukes's avatar
Warren Dukes committed
34 35

#include <mad.h>
36

37
#ifdef ENABLE_ID3TAG
38
#include "tag/Id3Unique.hxx"
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
enum class MadDecoderAction {
	SKIP,
	BREAK,
	CONT,
	OK
54
};
Warren Dukes's avatar
Warren Dukes committed
55

56 57 58 59
enum class MadDecoderMuteFrame {
	NONE,
	SKIP,
	SEEK
60
};
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
gcc_const
static SongTime
73
ToSongTime(mad_timer_t t) noexcept
74 75 76 77
{
	return SongTime::FromMS(mad_timer_count(t, MAD_UNITS_MILLISECONDS));
}

78
static inline int32_t
79
mad_fixed_to_24_sample(mad_fixed_t sample) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
80
{
81
	static constexpr unsigned bits = 24;
82 83
	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
	/* quantize */
89
	return Clamp(sample, MIN, MAX)
90
		>> (MAD_F_FRACBITS + 1 - bits);
Warren Dukes's avatar
Warren Dukes committed
91
}
Avuton Olrich's avatar
Avuton Olrich committed
92

93
static void
94
mad_fixed_to_24_buffer(int32_t *dest, const struct mad_pcm &src,
95
		       size_t start, size_t end,
96
		       unsigned int num_channels)
97
{
98
	for (size_t i = start; i < end; ++i)
99
		for (unsigned c = 0; c < num_channels; ++c)
100
			*dest++ = mad_fixed_to_24_sample(src.samples[c][i]);
101 102
}

103
static bool
104
mad_plugin_init(const ConfigBlock &block)
105
{
106 107
	gapless_playback = block.GetBlockValue("gapless",
					       DEFAULT_GAPLESS_MP3_PLAYBACK);
108
	return true;
109 110
}

111
class MadDecoder {
112 113
	static constexpr size_t READ_BUFFER_SIZE = 40960;

Warren Dukes's avatar
Warren Dukes committed
114 115 116 117
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
Max Kellermann's avatar
Max Kellermann committed
118
	unsigned char input_buffer[READ_BUFFER_SIZE];
119
	int32_t output_buffer[sizeof(mad_pcm::samples) / sizeof(mad_fixed_t)];
120
	SignedSongTime total_time;
121 122
	SongTime elapsed_time;
	SongTime seek_time;
123
	MadDecoderMuteFrame mute_frame = MadDecoderMuteFrame::NONE;
124 125
	long *frame_offsets = nullptr;
	mad_timer_t *times = nullptr;
126 127 128
	size_t highest_frame = 0;
	size_t max_frames = 0;
	size_t current_frame = 0;
129 130
	unsigned int drop_start_frames;
	unsigned int drop_end_frames;
131 132 133 134 135
	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;
136 137 138 139 140 141 142 143

	/**
	 * If this flag is true, then end-of-file was seen and a
	 * padding of 8 zero bytes were appended to #input_buffer, to
	 * allow libmad to decode the last frame.
	 */
	bool was_eof = false;

144
	DecoderClient *const client;
145
	InputStream &input_stream;
146
	enum mad_layer layer = mad_layer(0);
147

148
public:
149 150
	MadDecoder(DecoderClient *client, InputStream &input_stream) noexcept;
	~MadDecoder() noexcept;
151

152 153 154
	void RunDecoder() noexcept;
	bool RunScan(TagHandler &handler) noexcept;

155
private:
156 157 158 159 160
	bool Seek(long offset) noexcept;
	bool FillBuffer() noexcept;
	void ParseId3(size_t tagsize, Tag *tag) noexcept;
	MadDecoderAction DecodeNextFrameHeader(Tag *tag) noexcept;
	MadDecoderAction DecodeNextFrame() noexcept;
161 162

	gcc_pure
163
	offset_type ThisFrameOffset() const noexcept;
164 165

	gcc_pure
166
	offset_type RestIncludingThisFrame() const noexcept;
167 168 169 170

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

173
	bool DecodeFirstFrame(Tag *tag) noexcept;
174

175
	void AllocateBuffers() noexcept {
176 177 178 179 180 181 182 183
		assert(max_frames > 0);
		assert(frame_offsets == nullptr);
		assert(times == nullptr);

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

184
	gcc_pure
185
	size_t TimeToFrame(SongTime t) const noexcept;
186

187 188 189 190 191
	/**
	 * Record the current frame's offset in the "frame_offsets"
	 * buffer and go forward to the next frame, updating the
	 * attributes "current_frame" and "timer".
	 */
192
	void UpdateTimerNextFrame() noexcept;
193 194

	/**
195 196
	 * Sends the synthesized current frame via
	 * DecoderClient::SubmitData().
197
	 */
198
	DecoderCommand SubmitPCM(size_t start, size_t n) noexcept;
199 200 201

	/**
	 * Synthesize the current frame and send it via
202
	 * DecoderClient::SubmitData().
203
	 */
204
	DecoderCommand SynthAndSubmit() noexcept;
205

206 207 208 209 210
	/**
	 * @return false to stop decoding
	 */
	bool HandleCurrentFrame() noexcept;

211 212
	bool LoadNextFrame() noexcept;

213
	bool Read() noexcept;
Max Kellermann's avatar
Max Kellermann committed
214
};
Warren Dukes's avatar
Warren Dukes committed
215

216
MadDecoder::MadDecoder(DecoderClient *_client,
217
		       InputStream &_input_stream) noexcept
218
	:client(_client), input_stream(_input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
219
{
220 221 222 223 224
	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
225 226
}

227
inline bool
228
MadDecoder::Seek(long offset) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
229
{
230 231
	try {
		input_stream.LockSeek(offset);
232
	} catch (...) {
Max Kellermann's avatar
Max Kellermann committed
233
		return false;
234
	}
235

236 237
	mad_stream_buffer(&stream, input_buffer, 0);
	stream.error = MAD_ERROR_NONE;
238

Max Kellermann's avatar
Max Kellermann committed
239
	return true;
240 241
}

242
inline bool
243
MadDecoder::FillBuffer() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
244
{
245 246 247 248
	/* amount of rest data still residing in the buffer */
	size_t rest_size = 0;

	size_t max_read_size = sizeof(input_buffer);
249
	unsigned char *dest = input_buffer;
Max Kellermann's avatar
Max Kellermann committed
250

251
	if (stream.next_frame != nullptr) {
252 253 254 255
		rest_size = stream.bufend - stream.next_frame;
		memmove(input_buffer, stream.next_frame, rest_size);
		dest += rest_size;
		max_read_size -= rest_size;
Warren Dukes's avatar
Warren Dukes committed
256 257
	}

258 259
	/* we've exhausted the read buffer, so give up!, these potential
	 * mp3 frames are way too big, and thus unlikely to be mp3 frames */
260
	if (max_read_size == 0)
Max Kellermann's avatar
Max Kellermann committed
261
		return false;
262

263 264 265
	size_t nbytes = decoder_read(client, input_stream,
				     dest, max_read_size);
	if (nbytes == 0) {
266 267 268 269 270 271
		if (was_eof || max_read_size < MAD_BUFFER_GUARD)
			return false;

		was_eof = true;
		nbytes = MAD_BUFFER_GUARD;
		memset(dest, 0, nbytes);
272
	}
273

274
	mad_stream_buffer(&stream, input_buffer, rest_size + nbytes);
275
	stream.error = MAD_ERROR_NONE;
Warren Dukes's avatar
Warren Dukes committed
276

Max Kellermann's avatar
Max Kellermann committed
277
	return true;
Warren Dukes's avatar
Warren Dukes committed
278 279
}

280
#ifdef ENABLE_ID3TAG
281 282
gcc_pure
static MixRampInfo
283
parse_id3_mixramp(struct id3_tag *tag) noexcept
284
{
285
	MixRampInfo result;
286

287 288
	struct id3_frame *frame;
	for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
289 290 291
		if (frame->nfields < 3)
			continue;

292
		char *const key = (char *)
293 294
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
295
		char *const value = (char *)
296 297 298
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

299
		ParseMixRampTag(result, key, value);
300 301 302 303 304

		free(key);
		free(value);
	}

305
	return result;
306 307 308
}
#endif

309
inline void
310
MadDecoder::ParseId3(size_t tagsize, Tag *mpd_tag) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
311
{
312
#ifdef ENABLE_ID3TAG
313
	std::unique_ptr<id3_byte_t[]> allocated;
314

315
	const id3_length_t count = stream.bufend - stream.this_frame;
316

317
	const id3_byte_t *id3_data;
Avuton Olrich's avatar
Avuton Olrich committed
318
	if (tagsize <= count) {
319 320
		id3_data = stream.this_frame;
		mad_stream_skip(&(stream), tagsize);
Avuton Olrich's avatar
Avuton Olrich committed
321
	} else {
322 323
		allocated.reset(new id3_byte_t[tagsize]);
		memcpy(allocated.get(), stream.this_frame, count);
324
		mad_stream_skip(&(stream), count);
325

326
		if (!decoder_read_full(client, input_stream,
327
				       allocated.get() + count, tagsize - count)) {
328
			LogDebug(mad_domain, "error parsing ID3 tag");
Max Kellermann's avatar
Max Kellermann committed
329
			return;
Warren Dukes's avatar
Warren Dukes committed
330
		}
331

332
		id3_data = allocated.get();
333 334
	}

335
	const UniqueId3Tag id3_tag(id3_tag_parse(id3_data, tagsize));
336
	if (id3_tag == nullptr)
Max Kellermann's avatar
Max Kellermann committed
337
		return;
338

339 340
	if (mpd_tag != nullptr)
		*mpd_tag = tag_id3_import(id3_tag.get());
341

342
	if (client != nullptr) {
343
		ReplayGainInfo rgi;
344

345
		if (Id3ToReplayGainInfo(rgi, id3_tag.get())) {
346
			client->SubmitReplayGain(&rgi);
347
			found_replay_gain = true;
348
		}
349

350
		client->SubmitMixRamp(parse_id3_mixramp(id3_tag.get()));
351 352
	}

353
#else /* !ENABLE_ID3TAG */
354 355 356 357 358
	(void)mpd_tag;

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

359
	size_t count = stream.bufend - stream.this_frame;
360 361

	if (tagsize <= count) {
362
		mad_stream_skip(&stream, tagsize);
363
	} else {
364
		mad_stream_skip(&stream, count);
365
		decoder_skip(client, input_stream, tagsize - count);
366
	}
367
#endif
368 369
}

370
#ifndef ENABLE_ID3TAG
371 372 373
/**
 * This function emulates libid3tag when it is disabled.  Instead of
 * doing a real analyzation of the frame, it just checks whether the
374 375
 * frame begins with the string "ID3".  If so, it returns the length
 * of the ID3 frame.
376 377
 */
static signed long
378
id3_tag_query(const void *p0, size_t length) noexcept
379
{
380
	const char *p = (const char *)p0;
381

382 383
	return length >= 10 && memcmp(p, "ID3", 3) == 0
		? (p[8] << 7) + p[9] + 10
384 385
		: 0;
}
386
#endif /* !ENABLE_ID3TAG */
387

388
static MadDecoderAction
389
RecoverFrameError(const struct mad_stream &stream) noexcept
390 391
{
	if (MAD_RECOVERABLE(stream.error))
392
		return MadDecoderAction::SKIP;
393
	else if (stream.error == MAD_ERROR_BUFLEN)
394
		return MadDecoderAction::CONT;
395 396 397 398

	FormatWarning(mad_domain,
		      "unrecoverable frame level error: %s",
		      mad_stream_errorstr(&stream));
399
	return MadDecoderAction::BREAK;
400 401
}

402
MadDecoderAction
403
MadDecoder::DecodeNextFrameHeader(Tag *tag) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
404
{
405 406
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
407
		return MadDecoderAction::BREAK;
408

409 410 411 412 413
	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
414 415

			if (tagsize > 0) {
416
				ParseId3((size_t)tagsize, tag);
417
				return MadDecoderAction::CONT;
418 419
			}
		}
420

421
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
422
	}
423

424 425 426
	enum mad_layer new_layer = frame.header.layer;
	if (layer == (mad_layer)0) {
		if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
427
			/* Only layer 2 and 3 have been tested to work */
428
			return MadDecoderAction::SKIP;
429
		}
430 431 432

		layer = new_layer;
	} else if (new_layer != layer) {
433
		/* Don't decode frames with a different layer than the first */
434
		return MadDecoderAction::SKIP;
435
	}
Warren Dukes's avatar
Warren Dukes committed
436

437
	return MadDecoderAction::OK;
Warren Dukes's avatar
Warren Dukes committed
438 439
}

440
MadDecoderAction
441
MadDecoder::DecodeNextFrame() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
442
{
443 444
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
445
		return MadDecoderAction::BREAK;
446 447 448 449 450 451

	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
452
			if (tagsize > 0) {
453
				mad_stream_skip(&stream, tagsize);
454
				return MadDecoderAction::CONT;
455 456
			}
		}
457

458
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
459 460
	}

461
	return MadDecoderAction::OK;
Warren Dukes's avatar
Warren Dukes committed
462 463
}

464
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
465 466 467 468
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');
469

Warren Dukes's avatar
Warren Dukes committed
470
struct xing {
471 472 473 474 475
	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
476 477
};

478 479 480 481
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
482

483
struct lame_version {
484 485
	unsigned major;
	unsigned minor;
486 487
};

488
struct lame {
489
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
490
	struct lame_version version; /* struct containing just the version */
491
	float peak;             /* replaygain peak */
Max Kellermann's avatar
Max Kellermann committed
492 493 494 495
	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 */
496
	int crc;                /* CRC of the first 190 bytes of this frame */
497 498
};

Max Kellermann's avatar
Max Kellermann committed
499
static bool
500
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen) noexcept
Warren Dukes's avatar
Warren Dukes committed
501
{
502
	int bitlen = *oldbitlen;
Warren Dukes's avatar
Warren Dukes committed
503

Max Kellermann's avatar
Max Kellermann committed
504 505 506
	if (bitlen < 16)
		return false;

507
	const unsigned long bits = mad_bit_read(ptr, 16);
508 509
	bitlen -= 16;

510
	if (bits == XI_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
511 512 513 514 515 516
		if (bitlen < 16)
			return false;

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

517
		bitlen -= 16;
518
	} else if (bits == IN_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
519 520 521 522 523 524
		if (bitlen < 16)
			return false;

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

525
		bitlen -= 16;
526
	}
527
	else if (bits != NG_MAGIC && bits != FO_MAGIC)
Max Kellermann's avatar
Max Kellermann committed
528
		return false;
529

Max Kellermann's avatar
Max Kellermann committed
530 531
	if (bitlen < 32)
		return false;
532
	xing->flags = mad_bit_read(ptr, 32);
533 534 535
	bitlen -= 32;

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

	if (xing->flags & XING_BYTES) {
Max Kellermann's avatar
Max Kellermann committed
543 544
		if (bitlen < 32)
			return false;
545
		xing->bytes = mad_bit_read(ptr, 32);
546 547
		bitlen -= 32;
	}
Warren Dukes's avatar
Warren Dukes committed
548

549
	if (xing->flags & XING_TOC) {
Max Kellermann's avatar
Max Kellermann committed
550 551
		if (bitlen < 800)
			return false;
552 553
		for (unsigned i = 0; i < 100; ++i)
			xing->toc[i] = mad_bit_read(ptr, 8);
554 555 556 557
		bitlen -= 800;
	}

	if (xing->flags & XING_SCALE) {
Max Kellermann's avatar
Max Kellermann committed
558 559
		if (bitlen < 32)
			return false;
560
		xing->scale = mad_bit_read(ptr, 32);
561 562 563
		bitlen -= 32;
	}

564 565
	/* 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 */
566
	const int bitsleft = 960 - (*oldbitlen - bitlen);
Max Kellermann's avatar
Max Kellermann committed
567 568
	if (bitsleft < 0)
		return false;
569
	else if (bitsleft > 0) {
570
		mad_bit_skip(ptr, bitsleft);
571 572 573
		bitlen -= bitsleft;
	}

574
	*oldbitlen = bitlen;
575

Max Kellermann's avatar
Max Kellermann committed
576
	return true;
Warren Dukes's avatar
Warren Dukes committed
577 578
}

Max Kellermann's avatar
Max Kellermann committed
579
static bool
580
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen) noexcept
581 582 583
{
	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
	 * not all 36 bytes (288 bits) are there. */
584
	if (*bitlen < 288)
Max Kellermann's avatar
Max Kellermann committed
585
		return false;
586

587
	for (unsigned i = 0; i < 9; i++)
588
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
589 590
	lame->encoder[9] = '\0';

591 592
	*bitlen -= 72;

593 594 595
	/* 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. */
596
	if (!StringStartsWith(lame->encoder, "LAME"))
Max Kellermann's avatar
Max Kellermann committed
597
		return false;
598 599 600

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

603 604
	FormatDebug(mad_domain, "detected LAME version %i.%i (\"%s\")",
		    lame->version.major, lame->version.minor, lame->encoder);
605 606 607 608 609 610 611 612

	/* 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 */
613
	int adj = 0;
614 615 616
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;
617

618
	mad_bit_skip(ptr, 16);
619

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

Max Kellermann's avatar
Max Kellermann committed
623
	lame->track_gain = 0;
624 625 626
	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 */
627
	int gain = mad_bit_read(ptr, 9); /* gain*10 */
628
	if (gain && name == 1 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
629
		lame->track_gain = ((sign ? -gain : gain) / 10.0) + adj;
630 631
		FormatDebug(mad_domain, "LAME track gain found: %f",
			    lame->track_gain);
632
	}
633

634 635 636 637
	/* 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
638
	lame->album_gain = 0;
639 640 641 642 643 644
#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
645
		lame->album_gain = ((sign ? -gain : gain) / 10.0) + adj;
646 647
		FormatDebug(mad_domain, "LAME album gain found: %f",
			    lame->track_gain);
648
	}
649
#else
650
	mad_bit_skip(ptr, 16);
651 652
#endif

653
	mad_bit_skip(ptr, 16);
654

Max Kellermann's avatar
Max Kellermann committed
655 656
	lame->encoder_delay = mad_bit_read(ptr, 12);
	lame->encoder_padding = mad_bit_read(ptr, 12);
657

658 659
	FormatDebug(mad_domain, "encoder delay is %i, encoder padding is %i",
		    lame->encoder_delay, lame->encoder_padding);
660

661
	mad_bit_skip(ptr, 80);
662 663 664 665

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

	*bitlen -= 216;
666

Max Kellermann's avatar
Max Kellermann committed
667
	return true;
668 669
}

670
static inline SongTime
671
mad_frame_duration(const struct mad_frame *frame) noexcept
672
{
673
	return ToSongTime(frame->header.duration);
674 675
}

676
inline offset_type
677
MadDecoder::ThisFrameOffset() const noexcept
678
{
679
	auto offset = input_stream.GetOffset();
680

681 682
	if (stream.this_frame != nullptr)
		offset -= stream.bufend - stream.this_frame;
683
	else
684
		offset -= stream.bufend - stream.buffer;
685

686 687 688
	return offset;
}

689
inline offset_type
690
MadDecoder::RestIncludingThisFrame() const noexcept
691
{
692
	return input_stream.GetSize() - ThisFrameOffset();
693 694
}

695
inline void
696
MadDecoder::FileSizeToSongLength() noexcept
697
{
698
	if (input_stream.KnownSize()) {
699
		offset_type rest = RestIncludingThisFrame();
700

701
		const SongTime frame_duration = mad_frame_duration(&frame);
702 703 704 705
		const SongTime duration =
			SongTime::FromScale<uint64_t>(rest,
						      frame.header.bitrate / 8);
		total_time = duration;
706

707 708 709 710
		max_frames = (frame_duration.IsPositive()
			      ? duration.count() / frame_duration.count()
			      : 0)
			+ FRAMES_CUSHION;
711
	} else {
712
		max_frames = FRAMES_CUSHION;
713
		total_time = SignedSongTime::Negative();
714 715 716
	}
}

717
inline bool
718
MadDecoder::DecodeFirstFrame(Tag *tag) noexcept
719
{
720
	struct xing xing;
721

Max Kellermann's avatar
Max Kellermann committed
722
	while (true) {
723
		MadDecoderAction ret;
724
		do {
725
			ret = DecodeNextFrameHeader(tag);
726 727
		} while (ret == MadDecoderAction::CONT);
		if (ret == MadDecoderAction::BREAK)
Max Kellermann's avatar
Max Kellermann committed
728
			return false;
729
		if (ret == MadDecoderAction::SKIP) continue;
730

731
		do {
732
			ret = DecodeNextFrame();
733 734
		} while (ret == MadDecoderAction::CONT);
		if (ret == MadDecoderAction::BREAK)
Max Kellermann's avatar
Max Kellermann committed
735
			return false;
736
		if (ret == MadDecoderAction::OK) break;
Avuton Olrich's avatar
Avuton Olrich committed
737 738
	}

739 740
	struct mad_bitptr ptr = stream.anc_ptr;
	int bitlen = stream.anc_bitlen;
741

742
	FileSizeToSongLength();
743

744 745 746
	/*
	 * if an xing tag exists, use that!
	 */
747
	if (parse_xing(&xing, &ptr, &bitlen)) {
748
		mute_frame = MadDecoderMuteFrame::SKIP;
749

750
		if ((xing.flags & XING_FRAMES) && xing.frames) {
751
			mad_timer_t duration = frame.header.duration;
Avuton Olrich's avatar
Avuton Olrich committed
752
			mad_timer_multiply(&duration, xing.frames);
753
			total_time = ToSongTime(duration);
754
			max_frames = xing.frames;
Warren Dukes's avatar
Warren Dukes committed
755
		}
756

757
		struct lame lame;
758
		if (parse_lame(&lame, &ptr, &bitlen)) {
759
			if (gapless_playback && input_stream.IsSeekable()) {
760 761 762 763
				/* libmad inserts 529 samples of
				   silence at the beginning and
				   removes those 529 samples at the
				   end */
764
				drop_start_samples = lame.encoder_delay +
765
				                           DECODERDELAY;
766
				drop_end_samples = lame.encoder_padding;
767 768 769 770
				if (drop_end_samples > DECODERDELAY)
					drop_end_samples -= DECODERDELAY;
				else
					drop_end_samples = 0;
771 772 773 774
			}

			/* Album gain isn't currently used.  See comment in
			 * parse_lame() for details. -- jat */
775
			if (client != nullptr && !found_replay_gain &&
Max Kellermann's avatar
Max Kellermann committed
776
			    lame.track_gain) {
777
				ReplayGainInfo rgi;
778
				rgi.Clear();
779 780
				rgi.track.gain = lame.track_gain;
				rgi.track.peak = lame.peak;
781
				client->SubmitReplayGain(&rgi);
782 783
			}
		}
784
	}
Warren Dukes's avatar
Warren Dukes committed
785

786
	if (!max_frames)
Max Kellermann's avatar
Max Kellermann committed
787
		return false;
788

789
	if (max_frames > 8 * 1024 * 1024) {
790 791 792
		FormatWarning(mad_domain,
			      "mp3 file header indicates too many frames: %lu",
			      max_frames);
Max Kellermann's avatar
Max Kellermann committed
793
		return false;
794 795
	}

Max Kellermann's avatar
Max Kellermann committed
796
	return true;
Warren Dukes's avatar
Warren Dukes committed
797 798
}

799
MadDecoder::~MadDecoder() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
800
{
801 802 803
	mad_synth_finish(&synth);
	mad_frame_finish(&frame);
	mad_stream_finish(&stream);
Warren Dukes's avatar
Warren Dukes committed
804

805 806
	delete[] frame_offsets;
	delete[] times;
Warren Dukes's avatar
Warren Dukes committed
807 808
}

809
size_t
810
MadDecoder::TimeToFrame(SongTime t) const noexcept
811
{
812
	size_t i;
813

814
	for (i = 0; i < highest_frame; ++i) {
815
		auto frame_time = ToSongTime(times[i]);
816 817 818 819 820 821 822
		if (frame_time >= t)
			break;
	}

	return i;
}

823
void
824
MadDecoder::UpdateTimerNextFrame() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
825
{
826 827 828 829 830 831 832
	if (current_frame >= highest_frame) {
		/* record this frame's properties in frame_offsets
		   (for seeking) and times */

		if (current_frame >= max_frames)
			/* cap current_frame */
			current_frame = max_frames - 1;
833
		else
834
			highest_frame++;
835

836
		frame_offsets[current_frame] = ThisFrameOffset();
837

838 839
		mad_timer_add(&timer, frame.header.duration);
		times[current_frame] = timer;
840
	} else
841 842
		/* get the new timer value from "times" */
		timer = times[current_frame];
843

844
	current_frame++;
845
	elapsed_time = ToSongTime(timer);
846 847
}

848
DecoderCommand
849
MadDecoder::SubmitPCM(size_t i, size_t pcm_length) noexcept
850
{
851
	size_t num_samples = pcm_length - i;
852

853
	mad_fixed_to_24_buffer(output_buffer, synth.pcm,
854 855 856
			       i, i + num_samples,
			       MAD_NCHANNELS(&frame.header));
	num_samples *= MAD_NCHANNELS(&frame.header);
857

858 859 860
	return client->SubmitData(input_stream, output_buffer,
				  sizeof(output_buffer[0]) * num_samples,
				  frame.header.bitrate / 1000);
861 862
}

863
inline DecoderCommand
864
MadDecoder::SynthAndSubmit() noexcept
865
{
866 867 868 869 870 871 872 873 874
	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;
875 876
	}

877 878
	if (drop_start_frames > 0) {
		drop_start_frames--;
879
		return DecoderCommand::NONE;
880
	} else if ((drop_end_frames > 0) &&
881
		   current_frame == max_frames - drop_end_frames) {
882 883
		/* stop decoding, effectively dropping all remaining
		   frames */
884
		return DecoderCommand::STOP;
885 886
	}

887
	size_t i = 0;
888 889 890 891
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
892

893
	size_t pcm_length = synth.pcm.length;
894
	if (drop_end_samples &&
895
	    current_frame == max_frames - drop_end_frames - 1) {
896
		if (drop_end_samples >= pcm_length)
897 898 899
			return DecoderCommand::STOP;

		pcm_length -= drop_end_samples;
900 901
	}

902
	auto cmd = SubmitPCM(i, pcm_length);
903
	if (cmd != DecoderCommand::NONE)
904 905
		return cmd;

906
	if (drop_end_samples &&
907
	    current_frame == max_frames - drop_end_frames - 1)
908 909
		/* stop decoding, effectively dropping
		 * all remaining samples */
910
		return DecoderCommand::STOP;
911

912
	return DecoderCommand::NONE;
913 914
}

915
inline bool
916
MadDecoder::HandleCurrentFrame() noexcept
917
{
918
	switch (mute_frame) {
919 920
		DecoderCommand cmd;

921 922
	case MadDecoderMuteFrame::SKIP:
		mute_frame = MadDecoderMuteFrame::NONE;
Avuton Olrich's avatar
Avuton Olrich committed
923
		break;
924
	case MadDecoderMuteFrame::SEEK:
925
		if (elapsed_time >= seek_time)
926
			mute_frame = MadDecoderMuteFrame::NONE;
927
		UpdateTimerNextFrame();
Avuton Olrich's avatar
Avuton Olrich committed
928
		break;
929
	case MadDecoderMuteFrame::NONE:
930
		cmd = SynthAndSubmit();
931
		UpdateTimerNextFrame();
932
		if (cmd == DecoderCommand::SEEK) {
933
			assert(input_stream.IsSeekable());
934

935
			const auto t = client->GetSeekTime();
936
			size_t j = TimeToFrame(t);
937 938 939
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
940
					was_eof = false;
941
					client->CommandFinished();
Avuton Olrich's avatar
Avuton Olrich committed
942
				} else
943
					client->SeekError();
Max Kellermann's avatar
Max Kellermann committed
944
			} else {
945
				seek_time = t;
946
				mute_frame = MadDecoderMuteFrame::SEEK;
947
				client->CommandFinished();
Max Kellermann's avatar
Max Kellermann committed
948
			}
949
		} else if (cmd != DecoderCommand::NONE)
950
			return false;
Warren Dukes's avatar
Warren Dukes committed
951 952
	}

953 954 955 956
	return true;
}

inline bool
957
MadDecoder::LoadNextFrame() noexcept
958
{
Max Kellermann's avatar
Max Kellermann committed
959
	while (true) {
960
		MadDecoderAction ret;
961
		do {
962
			Tag tag;
963

964
			ret = DecodeNextFrameHeader(&tag);
965

966
			if (!tag.IsEmpty())
967
				client->SubmitTag(input_stream,
968
						  std::move(tag));
969 970
		} while (ret == MadDecoderAction::CONT);
		if (ret == MadDecoderAction::BREAK)
971
			return false;
972

973
		const bool skip = ret == MadDecoderAction::SKIP;
974

975
		if (mute_frame == MadDecoderMuteFrame::NONE) {
976
			do {
977
				ret = DecodeNextFrame();
978 979
			} while (ret == MadDecoderAction::CONT);
			if (ret == MadDecoderAction::BREAK)
980
				return false;
Warren Dukes's avatar
Warren Dukes committed
981
		}
982

983
		if (!skip && ret == MadDecoderAction::OK)
984
			return true;
Warren Dukes's avatar
Warren Dukes committed
985 986 987
	}
}

988 989 990 991 992 993 994
inline bool
MadDecoder::Read() noexcept
{
	return HandleCurrentFrame() &&
		LoadNextFrame();
}

995 996
inline void
MadDecoder::RunDecoder() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
997
{
998
	assert(client != nullptr);
999

1000
	Tag tag;
1001 1002
	if (!DecodeFirstFrame(&tag)) {
		if (client->GetCommand() == DecoderCommand::NONE)
1003
			LogError(mad_domain,
1004
				 "input does not appear to be a mp3 bit stream");
1005
		return;
Warren Dukes's avatar
Warren Dukes committed
1006 1007
	}

1008
	AllocateBuffers();
1009

1010 1011 1012 1013 1014
	client->Ready(CheckAudioFormat(frame.header.samplerate,
				       SampleFormat::S24_P32,
				       MAD_NCHANNELS(&frame.header)),
		      input_stream.IsSeekable(),
		      total_time);
Warren Dukes's avatar
Warren Dukes committed
1015

1016
	if (!tag.IsEmpty())
1017
		client->SubmitTag(input_stream, std::move(tag));
1018

1019
	while (Read()) {}
Warren Dukes's avatar
Warren Dukes committed
1020 1021
}

1022 1023
static void
mad_decode(DecoderClient &client, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
1024
{
1025 1026 1027 1028 1029 1030 1031 1032
	MadDecoder data(&client, input_stream);
	data.RunDecoder();
}

inline bool
MadDecoder::RunScan(TagHandler &handler) noexcept
{
	if (!DecodeFirstFrame(nullptr))
1033
		return false;
Warren Dukes's avatar
Warren Dukes committed
1034

1035 1036
	if (!total_time.IsNegative())
		handler.OnDuration(SongTime(total_time));
1037 1038

	try {
1039
		handler.OnAudioFormat(CheckAudioFormat(frame.header.samplerate,
1040
						       SampleFormat::S24_P32,
1041
						       MAD_NCHANNELS(&frame.header)));
1042 1043 1044
	} catch (...) {
	}

1045
	return true;
Warren Dukes's avatar
Warren Dukes committed
1046 1047
}

1048 1049 1050 1051 1052 1053 1054
static bool
mad_decoder_scan_stream(InputStream &is, TagHandler &handler) noexcept
{
	MadDecoder data(nullptr, is);
	return data.RunScan(handler);
}

1055 1056
static const char *const mad_suffixes[] = { "mp3", "mp2", nullptr };
static const char *const mad_mime_types[] = { "audio/mpeg", nullptr };
Warren Dukes's avatar
Warren Dukes committed
1057

1058
const struct DecoderPlugin mad_decoder_plugin = {
1059
	"mad",
1060
	mad_plugin_init,
1061
	nullptr,
1062
	mad_decode,
1063 1064 1065 1066
	nullptr,
	nullptr,
	mad_decoder_scan_stream,
	nullptr,
1067 1068
	mad_suffixes,
	mad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
1069
};