MadDecoderPlugin.cxx 25.9 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 27
#include "tag/Id3Scan.hxx"
#include "tag/Rva2.hxx"
#include "tag/Handler.hxx"
28
#include "tag/ReplayGain.hxx"
29
#include "tag/MixRamp.hxx"
30
#include "CheckAudioFormat.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 39
#include <id3tag.h>
#endif
40

41 42
#include <stdexcept>

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

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

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

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

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

66
static constexpr bool DEFAULT_GAPLESS_MP3_PLAYBACK = true;
67

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

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

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

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

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

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

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

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

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

117
struct MadDecoder {
118 119 120
	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
121 122 123 124
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
Max Kellermann's avatar
Max Kellermann committed
125 126
	unsigned char input_buffer[READ_BUFFER_SIZE];
	int32_t output_buffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
127
	SignedSongTime total_time;
128 129
	SongTime elapsed_time;
	SongTime seek_time;
130 131 132 133 134 135 136 137 138 139 140 141 142
	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
143
	unsigned long bit_rate;
144
	DecoderClient *const client;
145
	InputStream &input_stream;
146
	enum mad_layer layer = mad_layer(0);
147

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

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

	gcc_pure
158
	offset_type ThisFrameOffset() const noexcept;
159 160

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

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

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

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

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

	void UpdateTimerNextFrame();

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

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

	bool Read();
Max Kellermann's avatar
Max Kellermann committed
197
};
Warren Dukes's avatar
Warren Dukes committed
198

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

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

219 220
	mad_stream_buffer(&stream, input_buffer, 0);
	stream.error = MAD_ERROR_NONE;
221

Max Kellermann's avatar
Max Kellermann committed
222
	return true;
223 224
}

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

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

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

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

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

Max Kellermann's avatar
Max Kellermann committed
254
	return true;
Warren Dukes's avatar
Warren Dukes committed
255 256
}

257
#ifdef ENABLE_ID3TAG
258
static bool
259
parse_id3_replay_gain_info(ReplayGainInfo &rgi,
260
			   struct id3_tag *tag)
Avuton Olrich's avatar
Avuton Olrich committed
261
{
262
	bool found = false;
263

264
	rgi.Clear();
265

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

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

278
		if (ParseReplayGainTag(rgi, key, value))
279
			found = true;
280 281 282 283 284

		free(key);
		free(value);
	}

285
	return found ||
286
		/* fall back on RVA2 if no replaygain tags found */
287
		tag_rva2_parse(tag, rgi);
288
}
289
#endif
290

291
#ifdef ENABLE_ID3TAG
292 293
gcc_pure
static MixRampInfo
294
parse_id3_mixramp(struct id3_tag *tag) noexcept
295
{
296
	MixRampInfo result;
297

298 299
	struct id3_frame *frame;
	for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
300 301 302
		if (frame->nfields < 3)
			continue;

303
		char *const key = (char *)
304 305
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
306
		char *const value = (char *)
307 308 309
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

310
		ParseMixRampTag(result, key, value);
311 312 313 314 315

		free(key);
		free(value);
	}

316
	return result;
317 318 319
}
#endif

320
inline void
Max Kellermann's avatar
Max Kellermann committed
321
MadDecoder::ParseId3(size_t tagsize, Tag **mpd_tag)
Avuton Olrich's avatar
Avuton Olrich committed
322
{
323
#ifdef ENABLE_ID3TAG
324
	id3_byte_t *allocated = nullptr;
325

326
	const id3_length_t count = stream.bufend - stream.this_frame;
327

328
	const id3_byte_t *id3_data;
Avuton Olrich's avatar
Avuton Olrich committed
329
	if (tagsize <= count) {
330 331
		id3_data = stream.this_frame;
		mad_stream_skip(&(stream), tagsize);
Avuton Olrich's avatar
Avuton Olrich committed
332
	} else {
333
		allocated = new id3_byte_t[tagsize];
334 335
		memcpy(allocated, stream.this_frame, count);
		mad_stream_skip(&(stream), count);
336

337
		if (!decoder_read_full(client, input_stream,
338
				       allocated + count, tagsize - count)) {
339
			LogDebug(mad_domain, "error parsing ID3 tag");
340
			delete[] allocated;
Max Kellermann's avatar
Max Kellermann committed
341
			return;
Warren Dukes's avatar
Warren Dukes committed
342
		}
343 344 345 346

		id3_data = allocated;
	}

347
	struct id3_tag *const id3_tag = id3_tag_parse(id3_data, tagsize);
348
	if (id3_tag == nullptr) {
349
		delete[] allocated;
Max Kellermann's avatar
Max Kellermann committed
350 351
		return;
	}
352

Max Kellermann's avatar
Max Kellermann committed
353
	if (mpd_tag) {
Max Kellermann's avatar
Max Kellermann committed
354
		Tag *tmp_tag = tag_id3_import(id3_tag);
355
		if (tmp_tag != nullptr) {
Max Kellermann's avatar
Max Kellermann committed
356
			delete *mpd_tag;
Max Kellermann's avatar
Max Kellermann committed
357
			*mpd_tag = tmp_tag;
358
		}
359
	}
360

361
	if (client != nullptr) {
362
		ReplayGainInfo rgi;
363

364
		if (parse_id3_replay_gain_info(rgi, id3_tag)) {
365
			client->SubmitReplayGain(&rgi);
366
			found_replay_gain = true;
367
		}
368

369
		client->SubmitMixRamp(parse_id3_mixramp(id3_tag));
370 371
	}

Max Kellermann's avatar
Max Kellermann committed
372
	id3_tag_delete(id3_tag);
Max Kellermann's avatar
Max Kellermann committed
373

374
	delete[] allocated;
375
#else /* !ENABLE_ID3TAG */
376 377 378 379 380
	(void)mpd_tag;

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

381
	size_t count = stream.bufend - stream.this_frame;
382 383

	if (tagsize <= count) {
384
		mad_stream_skip(&stream, tagsize);
385
	} else {
386
		mad_stream_skip(&stream, count);
387
		decoder_skip(client, input_stream, tagsize - count);
388
	}
389
#endif
390 391
}

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

404 405
	return length >= 10 && memcmp(p, "ID3", 3) == 0
		? (p[8] << 7) + p[9] + 10
406 407
		: 0;
}
408
#endif /* !ENABLE_ID3TAG */
409

410 411 412 413 414 415 416 417 418 419 420 421 422 423
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;
}

424
enum mp3_action
Max Kellermann's avatar
Max Kellermann committed
425
MadDecoder::DecodeNextFrameHeader(Tag **tag)
Avuton Olrich's avatar
Avuton Olrich committed
426
{
427 428 429
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
		return DECODE_BREAK;
430

431 432 433 434 435
	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
436 437 438

			if (tagsize > 0) {
				if (tag && !(*tag)) {
439
					ParseId3((size_t)tagsize, tag);
Avuton Olrich's avatar
Avuton Olrich committed
440
				} else {
441
					mad_stream_skip(&stream, tagsize);
442
				}
443 444 445
				return DECODE_CONT;
			}
		}
446

447
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
448
	}
449

450 451 452
	enum mad_layer new_layer = frame.header.layer;
	if (layer == (mad_layer)0) {
		if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
453
			/* Only layer 2 and 3 have been tested to work */
454
			return DECODE_SKIP;
455
		}
456 457 458

		layer = new_layer;
	} else if (new_layer != layer) {
459
		/* Don't decode frames with a different layer than the first */
460 461
		return DECODE_SKIP;
	}
Warren Dukes's avatar
Warren Dukes committed
462 463 464 465

	return DECODE_OK;
}

466 467
enum mp3_action
MadDecoder::DecodeNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
468
{
469 470 471 472 473 474 475 476 477
	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
478
			if (tagsize > 0) {
479
				mad_stream_skip(&stream, tagsize);
480 481 482
				return DECODE_CONT;
			}
		}
483

484
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
485 486 487 488 489
	}

	return DECODE_OK;
}

490
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
491 492 493 494
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');
495 496

enum xing_magic {
497
	XING_MAGIC_XING, /* VBR */
498
	XING_MAGIC_INFO  /* CBR */
499
};
Warren Dukes's avatar
Warren Dukes committed
500 501

struct xing {
502 503 504 505 506 507
	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
508 509
};

510 511 512 513
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
514

515
struct lame_version {
516 517
	unsigned major;
	unsigned minor;
518 519
};

520
struct lame {
521
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
522
	struct lame_version version; /* struct containing just the version */
523
	float peak;             /* replaygain peak */
Max Kellermann's avatar
Max Kellermann committed
524 525 526 527
	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 */
528
	int crc;                /* CRC of the first 190 bytes of this frame */
529 530
};

Max Kellermann's avatar
Max Kellermann committed
531 532
static bool
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
Warren Dukes's avatar
Warren Dukes committed
533
{
534
	int bitlen = *oldbitlen;
Warren Dukes's avatar
Warren Dukes committed
535

Max Kellermann's avatar
Max Kellermann committed
536 537 538
	if (bitlen < 16)
		return false;

539
	const unsigned long bits = mad_bit_read(ptr, 16);
540 541
	bitlen -= 16;

542
	if (bits == XI_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
543 544 545 546 547 548
		if (bitlen < 16)
			return false;

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

549
		bitlen -= 16;
550 551
		xing->magic = XING_MAGIC_XING;
	} else if (bits == IN_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
552 553 554 555 556 557
		if (bitlen < 16)
			return false;

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

558 559
		bitlen -= 16;
		xing->magic = XING_MAGIC_INFO;
560 561 562
	}
	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
563 564
	else
		return false;
565

Max Kellermann's avatar
Max Kellermann committed
566 567
	if (bitlen < 32)
		return false;
568
	xing->flags = mad_bit_read(ptr, 32);
569 570 571
	bitlen -= 32;

	if (xing->flags & XING_FRAMES) {
Max Kellermann's avatar
Max Kellermann committed
572 573
		if (bitlen < 32)
			return false;
574
		xing->frames = mad_bit_read(ptr, 32);
575 576 577 578
		bitlen -= 32;
	}

	if (xing->flags & XING_BYTES) {
Max Kellermann's avatar
Max Kellermann committed
579 580
		if (bitlen < 32)
			return false;
581
		xing->bytes = mad_bit_read(ptr, 32);
582 583
		bitlen -= 32;
	}
Warren Dukes's avatar
Warren Dukes committed
584

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

	if (xing->flags & XING_SCALE) {
Max Kellermann's avatar
Max Kellermann committed
594 595
		if (bitlen < 32)
			return false;
596
		xing->scale = mad_bit_read(ptr, 32);
597 598 599
		bitlen -= 32;
	}

600 601
	/* 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 */
602
	const int bitsleft = 960 - (*oldbitlen - bitlen);
Max Kellermann's avatar
Max Kellermann committed
603 604
	if (bitsleft < 0)
		return false;
605 606 607 608 609
	else if (bitsleft > 0) {
		mad_bit_read(ptr, bitsleft);
		bitlen -= bitsleft;
	}

610
	*oldbitlen = bitlen;
611

Max Kellermann's avatar
Max Kellermann committed
612
	return true;
Warren Dukes's avatar
Warren Dukes committed
613 614
}

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

623
	for (unsigned i = 0; i < 9; i++)
624
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
625 626
	lame->encoder[9] = '\0';

627 628
	*bitlen -= 72;

629 630 631
	/* 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. */
632
	if (!StringStartsWith(lame->encoder, "LAME"))
Max Kellermann's avatar
Max Kellermann committed
633
		return false;
634 635 636

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

639 640
	FormatDebug(mad_domain, "detected LAME version %i.%i (\"%s\")",
		    lame->version.major, lame->version.minor, lame->encoder);
641 642 643 644 645 646 647 648

	/* 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 */
649
	int adj = 0;
650 651 652
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;
653 654 655

	mad_bit_read(ptr, 16);

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

Max Kellermann's avatar
Max Kellermann committed
659
	lame->track_gain = 0;
660 661 662
	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 */
663
	int gain = mad_bit_read(ptr, 9); /* gain*10 */
664
	if (gain && name == 1 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
665
		lame->track_gain = ((sign ? -gain : gain) / 10.0) + adj;
666 667
		FormatDebug(mad_domain, "LAME track gain found: %f",
			    lame->track_gain);
668
	}
669

670 671 672 673
	/* 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
674
	lame->album_gain = 0;
675 676 677 678 679 680
#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
681
		lame->album_gain = ((sign ? -gain : gain) / 10.0) + adj;
682 683
		FormatDebug(mad_domain, "LAME album gain found: %f",
			    lame->track_gain);
684
	}
685
#else
686
	mad_bit_read(ptr, 16);
687 688
#endif

689 690
	mad_bit_read(ptr, 16);

Max Kellermann's avatar
Max Kellermann committed
691 692
	lame->encoder_delay = mad_bit_read(ptr, 12);
	lame->encoder_padding = mad_bit_read(ptr, 12);
693

694 695
	FormatDebug(mad_domain, "encoder delay is %i, encoder padding is %i",
		    lame->encoder_delay, lame->encoder_padding);
696

697 698 699 700 701
	mad_bit_read(ptr, 80);

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

	*bitlen -= 216;
702

Max Kellermann's avatar
Max Kellermann committed
703
	return true;
704 705
}

706
static inline SongTime
707 708
mp3_frame_duration(const struct mad_frame *frame)
{
709
	return ToSongTime(frame->header.duration);
710 711
}

712
inline offset_type
713
MadDecoder::ThisFrameOffset() const noexcept
714
{
715
	auto offset = input_stream.GetOffset();
716

717 718
	if (stream.this_frame != nullptr)
		offset -= stream.bufend - stream.this_frame;
719
	else
720
		offset -= stream.bufend - stream.buffer;
721

722 723 724
	return offset;
}

725
inline offset_type
726
MadDecoder::RestIncludingThisFrame() const noexcept
727
{
728
	return input_stream.GetSize() - ThisFrameOffset();
729 730
}

731 732
inline void
MadDecoder::FileSizeToSongLength()
733
{
734
	if (input_stream.KnownSize()) {
735
		offset_type rest = RestIncludingThisFrame();
736

737 738 739 740 741
		const SongTime frame_duration = mp3_frame_duration(&frame);
		const SongTime duration =
			SongTime::FromScale<uint64_t>(rest,
						      frame.header.bitrate / 8);
		total_time = duration;
742

743 744 745 746
		max_frames = (frame_duration.IsPositive()
			      ? duration.count() / frame_duration.count()
			      : 0)
			+ FRAMES_CUSHION;
747
	} else {
748
		max_frames = FRAMES_CUSHION;
749
		total_time = SignedSongTime::Negative();
750 751 752
	}
}

753
inline bool
Max Kellermann's avatar
Max Kellermann committed
754
MadDecoder::DecodeFirstFrame(Tag **tag)
755
{
756
	struct xing xing;
757
	xing.frames = 0;
758

Max Kellermann's avatar
Max Kellermann committed
759
	while (true) {
760
		enum mp3_action ret;
761
		do {
762
			ret = DecodeNextFrameHeader(tag);
763 764
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
765
			return false;
766
		if (ret == DECODE_SKIP) continue;
767

768
		do {
769
			ret = DecodeNextFrame();
770 771
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
772
			return false;
773
		if (ret == DECODE_OK) break;
Avuton Olrich's avatar
Avuton Olrich committed
774 775
	}

776 777
	struct mad_bitptr ptr = stream.anc_ptr;
	int bitlen = stream.anc_bitlen;
778

779
	FileSizeToSongLength();
780

781 782 783
	/*
	 * if an xing tag exists, use that!
	 */
784
	if (parse_xing(&xing, &ptr, &bitlen)) {
785
		mute_frame = MUTEFRAME_SKIP;
786

787
		if ((xing.flags & XING_FRAMES) && xing.frames) {
788
			mad_timer_t duration = frame.header.duration;
Avuton Olrich's avatar
Avuton Olrich committed
789
			mad_timer_multiply(&duration, xing.frames);
790
			total_time = ToSongTime(duration);
791
			max_frames = xing.frames;
Warren Dukes's avatar
Warren Dukes committed
792
		}
793

794
		struct lame lame;
795
		if (parse_lame(&lame, &ptr, &bitlen)) {
796
			if (gapless_playback && input_stream.IsSeekable()) {
797
				drop_start_samples = lame.encoder_delay +
798
				                           DECODERDELAY;
799
				drop_end_samples = lame.encoder_padding;
800 801 802 803
			}

			/* Album gain isn't currently used.  See comment in
			 * parse_lame() for details. -- jat */
804
			if (client != nullptr && !found_replay_gain &&
Max Kellermann's avatar
Max Kellermann committed
805
			    lame.track_gain) {
806
				ReplayGainInfo rgi;
807
				rgi.Clear();
808 809
				rgi.track.gain = lame.track_gain;
				rgi.track.peak = lame.peak;
810
				client->SubmitReplayGain(&rgi);
811 812
			}
		}
813
	}
Warren Dukes's avatar
Warren Dukes committed
814

815
	if (!max_frames)
Max Kellermann's avatar
Max Kellermann committed
816
		return false;
817

818
	if (max_frames > 8 * 1024 * 1024) {
819 820 821
		FormatWarning(mad_domain,
			      "mp3 file header indicates too many frames: %lu",
			      max_frames);
Max Kellermann's avatar
Max Kellermann committed
822
		return false;
823 824
	}

Max Kellermann's avatar
Max Kellermann committed
825
	return true;
Warren Dukes's avatar
Warren Dukes committed
826 827
}

828
MadDecoder::~MadDecoder()
Avuton Olrich's avatar
Avuton Olrich committed
829
{
830 831 832
	mad_synth_finish(&synth);
	mad_frame_finish(&frame);
	mad_stream_finish(&stream);
Warren Dukes's avatar
Warren Dukes committed
833

834 835
	delete[] frame_offsets;
	delete[] times;
Warren Dukes's avatar
Warren Dukes committed
836 837 838
}

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

848
long
849
MadDecoder::TimeToFrame(SongTime t) const noexcept
850 851 852
{
	unsigned long i;

853
	for (i = 0; i < highest_frame; ++i) {
854
		auto frame_time = ToSongTime(times[i]);
855 856 857 858 859 860 861
		if (frame_time >= t)
			break;
	}

	return i;
}

862 863
void
MadDecoder::UpdateTimerNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
864
{
865 866 867 868 869 870 871 872
	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;
873
		else
874
			highest_frame++;
875

876
		frame_offsets[current_frame] = ThisFrameOffset();
877

878 879
		mad_timer_add(&timer, frame.header.duration);
		times[current_frame] = timer;
880
	} else
881 882
		/* get the new timer value from "times" */
		timer = times[current_frame];
883

884
	current_frame++;
885
	elapsed_time = ToSongTime(timer);
886 887
}

888
DecoderCommand
889
MadDecoder::SendPCM(unsigned i, unsigned pcm_length)
890
{
891
	unsigned max_samples = sizeof(output_buffer) /
892 893
		sizeof(output_buffer[0]) /
		MAD_NCHANNELS(&frame.header);
894 895 896 897 898 899 900 901

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

		i += num_samples;

902
		mad_fixed_to_24_buffer(output_buffer, &synth,
903
				       i - num_samples, i,
904 905
				       MAD_NCHANNELS(&frame.header));
		num_samples *= MAD_NCHANNELS(&frame.header);
906

907 908 909
		auto cmd = client->SubmitData(input_stream, output_buffer,
					      sizeof(output_buffer[0]) * num_samples,
					      bit_rate / 1000);
910
		if (cmd != DecoderCommand::NONE)
911 912 913
			return cmd;
	}

914
	return DecoderCommand::NONE;
915 916
}

917
inline DecoderCommand
918
MadDecoder::SyncAndSend()
919
{
920 921 922 923 924 925 926 927 928
	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;
929 930
	}

931 932
	if (drop_start_frames > 0) {
		drop_start_frames--;
933
		return DecoderCommand::NONE;
934 935
	} else if ((drop_end_frames > 0) &&
		   (current_frame == (max_frames + 1 - drop_end_frames))) {
936 937
		/* stop decoding, effectively dropping all remaining
		   frames */
938
		return DecoderCommand::STOP;
939 940
	}

941 942 943 944 945
	unsigned i = 0;
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
946

947 948 949 950
	unsigned pcm_length = synth.pcm.length;
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames)) {
		if (drop_end_samples >= pcm_length)
951 952
			pcm_length = 0;
		else
953
			pcm_length -= drop_end_samples;
954 955
	}

956 957
	auto cmd = SendPCM(i, pcm_length);
	if (cmd != DecoderCommand::NONE)
958 959
		return cmd;

960 961
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames))
962 963
		/* stop decoding, effectively dropping
		 * all remaining samples */
964
		return DecoderCommand::STOP;
965

966
	return DecoderCommand::NONE;
967 968
}

969 970
inline bool
MadDecoder::Read()
971
{
972
	UpdateTimerNextFrame();
Warren Dukes's avatar
Warren Dukes committed
973

974
	switch (mute_frame) {
975 976
		DecoderCommand cmd;

Avuton Olrich's avatar
Avuton Olrich committed
977
	case MUTEFRAME_SKIP:
978
		mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
979 980
		break;
	case MUTEFRAME_SEEK:
981
		if (elapsed_time >= seek_time)
982
			mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
983
		break;
984
	case MUTEFRAME_NONE:
985
		cmd = SyncAndSend();
986
		if (cmd == DecoderCommand::SEEK) {
987
			assert(input_stream.IsSeekable());
988

989 990
			const auto t = client->GetSeekTime();
			unsigned long j = TimeToFrame(t);
991 992 993
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
994
					client->CommandFinished();
Avuton Olrich's avatar
Avuton Olrich committed
995
				} else
996
					client->SeekError();
Max Kellermann's avatar
Max Kellermann committed
997
			} else {
998
				seek_time = t;
999
				mute_frame = MUTEFRAME_SEEK;
1000
				client->CommandFinished();
Max Kellermann's avatar
Max Kellermann committed
1001
			}
1002
		} else if (cmd != DecoderCommand::NONE)
1003
			return false;
Warren Dukes's avatar
Warren Dukes committed
1004 1005
	}

Max Kellermann's avatar
Max Kellermann committed
1006
	while (true) {
1007
		enum mp3_action ret;
1008
		do {
Max Kellermann's avatar
Max Kellermann committed
1009
			Tag *tag = nullptr;
1010

1011
			ret = DecodeNextFrameHeader(&tag);
1012

1013
			if (tag != nullptr) {
1014 1015
				client->SubmitTag(input_stream,
						  std::move(*tag));
Max Kellermann's avatar
Max Kellermann committed
1016
				delete tag;
1017
			}
1018 1019
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
1020
			return false;
1021 1022

		const bool skip = ret == DECODE_SKIP;
1023

1024
		if (mute_frame == MUTEFRAME_NONE) {
1025
			do {
1026
				ret = DecodeNextFrame();
1027 1028
			} while (ret == DECODE_CONT);
			if (ret == DECODE_BREAK)
1029
				return false;
Warren Dukes's avatar
Warren Dukes committed
1030
		}
1031

Avuton Olrich's avatar
Avuton Olrich committed
1032
		if (!skip && ret == DECODE_OK)
1033
			return true;
Warren Dukes's avatar
Warren Dukes committed
1034 1035 1036
	}
}

1037
static void
1038
mp3_decode(DecoderClient &client, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
1039
{
1040
	MadDecoder data(&client, input_stream);
1041

Max Kellermann's avatar
Max Kellermann committed
1042
	Tag *tag = nullptr;
1043
	if (!data.DecodeFirstFrame(&tag)) {
Max Kellermann's avatar
Max Kellermann committed
1044
		delete tag;
1045

1046
		if (client.GetCommand() == DecoderCommand::NONE)
1047
			LogError(mad_domain,
Max Kellermann's avatar
Max Kellermann committed
1048
				 "input/Input does not appear to be a mp3 bit stream");
1049
		return;
Warren Dukes's avatar
Warren Dukes committed
1050 1051
	}

1052 1053
	data.AllocateBuffers();

1054 1055 1056 1057 1058
	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
1059

1060
	if (tag != nullptr) {
1061
		client.SubmitTag(input_stream, std::move(*tag));
Max Kellermann's avatar
Max Kellermann committed
1062
		delete tag;
1063 1064
	}

1065
	while (data.Read()) {}
Warren Dukes's avatar
Warren Dukes committed
1066 1067
}

1068
static bool
1069
mad_decoder_scan_stream(InputStream &is,
1070
			const TagHandler &handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
1071
{
1072 1073
	const auto result = mad_decoder_total_file_time(is);
	if (!result.first)
1074
		return false;
Warren Dukes's avatar
Warren Dukes committed
1075

1076 1077 1078
	if (!result.second.IsNegative())
		tag_handler_invoke_duration(handler, handler_ctx,
					    SongTime(result.second));
1079
	return true;
Warren Dukes's avatar
Warren Dukes committed
1080 1081
}

1082 1083
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
1084

1085
const struct DecoderPlugin mad_decoder_plugin = {
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
	"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
1096
};