MadDecoderPlugin.cxx 26.1 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;
Warren Dukes's avatar
Warren Dukes committed
82

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

86
	/* quantize */
87
	return Clamp(sample, MAD_F_MIN, MAD_F_MAX)
88
		>> (MAD_F_FRACBITS + 1 - bits);
Warren Dukes's avatar
Warren Dukes committed
89
}
Avuton Olrich's avatar
Avuton Olrich committed
90

91 92 93 94
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)
95
{
96 97
	for (unsigned i = start; i < end; ++i)
		for (unsigned c = 0; c < num_channels; ++c)
98
			*dest++ = mad_fixed_to_24_sample(synth->pcm.samples[c][i]);
99 100
}

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

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

	/**
	 * 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;

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

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

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

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

	gcc_pure
162
	offset_type ThisFrameOffset() const noexcept;
163 164

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

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

172
	bool DecodeFirstFrame(Tag *tag) noexcept;
173

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

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

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

186 187 188 189 190
	/**
	 * 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".
	 */
191
	void UpdateTimerNextFrame() noexcept;
192 193

	/**
194 195
	 * Sends the synthesized current frame via
	 * DecoderClient::SubmitData().
196
	 */
197
	DecoderCommand SubmitPCM(unsigned i, unsigned pcm_length) noexcept;
198 199 200

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

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

210 211
	bool LoadNextFrame() noexcept;

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

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

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

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

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

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

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

250
	if (stream.next_frame != nullptr) {
251 252 253 254
		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
255 256
	}

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

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

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

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

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

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

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

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

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

		free(key);
		free(value);
	}

304
	return result;
305 306 307
}
#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

573
	*oldbitlen = bitlen;
574

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

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

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

590 591
	*bitlen -= 72;

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

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

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

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

617
	mad_bit_skip(ptr, 16);
618

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

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

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

652
	mad_bit_skip(ptr, 16);
653

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

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

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

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

	*bitlen -= 216;
665

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

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

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

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

685 686 687
	return offset;
}

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

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

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

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

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

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

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

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

741
	FileSizeToSongLength();
742

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

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

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

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

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

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

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

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

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

808
long
809
MadDecoder::TimeToFrame(SongTime t) const noexcept
810 811 812
{
	unsigned long i;

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

	return i;
}

822
void
823
MadDecoder::UpdateTimerNextFrame() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
824
{
825 826 827 828 829 830 831
	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;
832
		else
833
			highest_frame++;
834

835
		frame_offsets[current_frame] = ThisFrameOffset();
836

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

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

847
DecoderCommand
848
MadDecoder::SubmitPCM(unsigned i, unsigned pcm_length) noexcept
849
{
850
	unsigned max_samples = sizeof(output_buffer) /
851 852
		sizeof(output_buffer[0]) /
		MAD_NCHANNELS(&frame.header);
853 854 855 856 857 858 859 860

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

		i += num_samples;

861
		mad_fixed_to_24_buffer(output_buffer, &synth,
862
				       i - num_samples, i,
863 864
				       MAD_NCHANNELS(&frame.header));
		num_samples *= MAD_NCHANNELS(&frame.header);
865

866 867
		auto cmd = client->SubmitData(input_stream, output_buffer,
					      sizeof(output_buffer[0]) * num_samples,
868
					      frame.header.bitrate / 1000);
869
		if (cmd != DecoderCommand::NONE)
870 871 872
			return cmd;
	}

873
	return DecoderCommand::NONE;
874 875
}

876
inline DecoderCommand
877
MadDecoder::SynthAndSubmit() noexcept
878
{
879 880 881 882 883 884 885 886 887
	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;
888 889
	}

890 891
	if (drop_start_frames > 0) {
		drop_start_frames--;
892
		return DecoderCommand::NONE;
893
	} else if ((drop_end_frames > 0) &&
894
		   current_frame == max_frames - drop_end_frames) {
895 896
		/* stop decoding, effectively dropping all remaining
		   frames */
897
		return DecoderCommand::STOP;
898 899
	}

900 901 902 903 904
	unsigned i = 0;
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
905

906 907
	unsigned pcm_length = synth.pcm.length;
	if (drop_end_samples &&
908
	    current_frame == max_frames - drop_end_frames - 1) {
909
		if (drop_end_samples >= pcm_length)
910 911
			pcm_length = 0;
		else
912
			pcm_length -= drop_end_samples;
913 914
	}

915
	auto cmd = SubmitPCM(i, pcm_length);
916
	if (cmd != DecoderCommand::NONE)
917 918
		return cmd;

919
	if (drop_end_samples &&
920
	    current_frame == max_frames - drop_end_frames - 1)
921 922
		/* stop decoding, effectively dropping
		 * all remaining samples */
923
		return DecoderCommand::STOP;
924

925
	return DecoderCommand::NONE;
926 927
}

928
inline bool
929
MadDecoder::HandleCurrentFrame() noexcept
930
{
931
	switch (mute_frame) {
932 933
		DecoderCommand cmd;

934 935
	case MadDecoderMuteFrame::SKIP:
		mute_frame = MadDecoderMuteFrame::NONE;
Avuton Olrich's avatar
Avuton Olrich committed
936
		break;
937
	case MadDecoderMuteFrame::SEEK:
938
		if (elapsed_time >= seek_time)
939
			mute_frame = MadDecoderMuteFrame::NONE;
940
		UpdateTimerNextFrame();
Avuton Olrich's avatar
Avuton Olrich committed
941
		break;
942
	case MadDecoderMuteFrame::NONE:
943
		cmd = SynthAndSubmit();
944
		UpdateTimerNextFrame();
945
		if (cmd == DecoderCommand::SEEK) {
946
			assert(input_stream.IsSeekable());
947

948 949
			const auto t = client->GetSeekTime();
			unsigned long j = TimeToFrame(t);
950 951 952
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
953
					was_eof = false;
954
					client->CommandFinished();
Avuton Olrich's avatar
Avuton Olrich committed
955
				} else
956
					client->SeekError();
Max Kellermann's avatar
Max Kellermann committed
957
			} else {
958
				seek_time = t;
959
				mute_frame = MadDecoderMuteFrame::SEEK;
960
				client->CommandFinished();
Max Kellermann's avatar
Max Kellermann committed
961
			}
962
		} else if (cmd != DecoderCommand::NONE)
963
			return false;
Warren Dukes's avatar
Warren Dukes committed
964 965
	}

966 967 968 969
	return true;
}

inline bool
970
MadDecoder::LoadNextFrame() noexcept
971
{
Max Kellermann's avatar
Max Kellermann committed
972
	while (true) {
973
		MadDecoderAction ret;
974
		do {
975
			Tag tag;
976

977
			ret = DecodeNextFrameHeader(&tag);
978

979
			if (!tag.IsEmpty())
980
				client->SubmitTag(input_stream,
981
						  std::move(tag));
982 983
		} while (ret == MadDecoderAction::CONT);
		if (ret == MadDecoderAction::BREAK)
984
			return false;
985

986
		const bool skip = ret == MadDecoderAction::SKIP;
987

988
		if (mute_frame == MadDecoderMuteFrame::NONE) {
989
			do {
990
				ret = DecodeNextFrame();
991 992
			} while (ret == MadDecoderAction::CONT);
			if (ret == MadDecoderAction::BREAK)
993
				return false;
Warren Dukes's avatar
Warren Dukes committed
994
		}
995

996
		if (!skip && ret == MadDecoderAction::OK)
997
			return true;
Warren Dukes's avatar
Warren Dukes committed
998 999 1000
	}
}

1001 1002 1003 1004 1005 1006 1007
inline bool
MadDecoder::Read() noexcept
{
	return HandleCurrentFrame() &&
		LoadNextFrame();
}

1008 1009
inline void
MadDecoder::RunDecoder() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
1010
{
1011
	assert(client != nullptr);
1012

1013
	Tag tag;
1014 1015
	if (!DecodeFirstFrame(&tag)) {
		if (client->GetCommand() == DecoderCommand::NONE)
1016
			LogError(mad_domain,
1017
				 "input does not appear to be a mp3 bit stream");
1018
		return;
Warren Dukes's avatar
Warren Dukes committed
1019 1020
	}

1021
	AllocateBuffers();
1022

1023 1024 1025 1026 1027
	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
1028

1029
	if (!tag.IsEmpty())
1030
		client->SubmitTag(input_stream, std::move(tag));
1031

1032
	while (Read()) {}
Warren Dukes's avatar
Warren Dukes committed
1033 1034
}

1035 1036
static void
mad_decode(DecoderClient &client, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
1037
{
1038 1039 1040 1041 1042 1043 1044 1045
	MadDecoder data(&client, input_stream);
	data.RunDecoder();
}

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

1048 1049
	if (!total_time.IsNegative())
		handler.OnDuration(SongTime(total_time));
1050 1051

	try {
1052
		handler.OnAudioFormat(CheckAudioFormat(frame.header.samplerate,
1053
						       SampleFormat::S24_P32,
1054
						       MAD_NCHANNELS(&frame.header)));
1055 1056 1057
	} catch (...) {
	}

1058
	return true;
Warren Dukes's avatar
Warren Dukes committed
1059 1060
}

1061 1062 1063 1064 1065 1066 1067
static bool
mad_decoder_scan_stream(InputStream &is, TagHandler &handler) noexcept
{
	MadDecoder data(nullptr, is);
	return data.RunScan(handler);
}

1068 1069
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
1070

1071
const struct DecoderPlugin mad_decoder_plugin = {
1072
	"mad",
1073
	mad_plugin_init,
1074
	nullptr,
1075
	mad_decode,
1076 1077 1078 1079
	nullptr,
	nullptr,
	mad_decoder_scan_stream,
	nullptr,
1080 1081
	mad_suffixes,
	mad_mime_types,
Warren Dukes's avatar
Warren Dukes committed
1082
};