MadDecoderPlugin.cxx 24.7 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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 "pcm/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 66
static constexpr Domain mad_domain("mad");

67 68
gcc_const
static SongTime
69
ToSongTime(mad_timer_t t) noexcept
70 71 72 73
{
	return SongTime::FromMS(mad_timer_count(t, MAD_UNITS_MILLISECONDS));
}

74
static inline int32_t
75
mad_fixed_to_24_sample(mad_fixed_t sample) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
76
{
77
	static constexpr unsigned bits = 24;
78 79
	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
80

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

84
	/* quantize */
85
	return Clamp(sample, MIN, MAX)
86
		>> (MAD_F_FRACBITS + 1 - bits);
Warren Dukes's avatar
Warren Dukes committed
87
}
Avuton Olrich's avatar
Avuton Olrich committed
88

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

99
class MadDecoder {
100 101
	static constexpr size_t READ_BUFFER_SIZE = 40960;

Warren Dukes's avatar
Warren Dukes committed
102 103 104 105
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
Max Kellermann's avatar
Max Kellermann committed
106
	unsigned char input_buffer[READ_BUFFER_SIZE];
107
	int32_t output_buffer[sizeof(mad_pcm::samples) / sizeof(mad_fixed_t)];
108
	SignedSongTime total_time;
109 110
	SongTime elapsed_time;
	SongTime seek_time;
111
	MadDecoderMuteFrame mute_frame = MadDecoderMuteFrame::NONE;
112 113
	long *frame_offsets = nullptr;
	mad_timer_t *times = nullptr;
114 115 116
	size_t highest_frame = 0;
	size_t max_frames = 0;
	size_t current_frame = 0;
117 118
	unsigned int drop_start_frames;
	unsigned int drop_end_frames;
119 120 121 122 123
	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;
124 125 126 127 128 129 130 131

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

132
	DecoderClient *const client;
133
	InputStream &input_stream;
134
	enum mad_layer layer = mad_layer(0);
135

136
public:
137 138
	MadDecoder(DecoderClient *client, InputStream &input_stream) noexcept;
	~MadDecoder() noexcept;
139

140 141
	void RunDecoder() noexcept;
	bool RunScan(TagHandler &handler) noexcept;
142

143
private:
144 145 146
	bool Seek(long offset) noexcept;
	bool FillBuffer() noexcept;
	void ParseId3(size_t tagsize, Tag *tag) noexcept;
147
	MadDecoderAction DecodeNextFrame(bool skip, Tag *tag) noexcept;
148 149

	gcc_pure
150
	offset_type ThisFrameOffset() const noexcept;
151 152

	gcc_pure
153
	offset_type RestIncludingThisFrame() const noexcept;
154 155 156 157

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

160
	bool DecodeFirstFrame(Tag *tag) noexcept;
161

162
	void AllocateBuffers() noexcept {
163 164 165 166 167 168 169 170
		assert(max_frames > 0);
		assert(frame_offsets == nullptr);
		assert(times == nullptr);

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

171
	gcc_pure
172
	size_t TimeToFrame(SongTime t) const noexcept;
173

174 175 176 177 178
	/**
	 * 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".
	 */
179
	void UpdateTimerNextFrame() noexcept;
180 181

	/**
182 183
	 * Sends the synthesized current frame via
	 * DecoderClient::SubmitData().
184
	 */
185
	DecoderCommand SubmitPCM(size_t start, size_t n) noexcept;
186 187 188

	/**
	 * Synthesize the current frame and send it via
189
	 * DecoderClient::SubmitData().
190
	 */
191
	DecoderCommand SynthAndSubmit() noexcept;
192

193 194 195 196
	/**
	 * @return false to stop decoding
	 */
	bool HandleCurrentFrame() noexcept;
197

198 199
	bool LoadNextFrame() noexcept;

200
	bool Read() noexcept;
Max Kellermann's avatar
Max Kellermann committed
201
};
Warren Dukes's avatar
Warren Dukes committed
202

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

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

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

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

229
inline bool
230
MadDecoder::FillBuffer() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
231
{
232 233 234 235
	/* amount of rest data still residing in the buffer */
	size_t rest_size = 0;

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

238
	if (stream.next_frame != nullptr) {
239 240 241 242
		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
243 244
	}

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

250 251 252
	size_t nbytes = decoder_read(client, input_stream,
				     dest, max_read_size);
	if (nbytes == 0) {
253 254 255 256 257 258
		if (was_eof || max_read_size < MAD_BUFFER_GUARD)
			return false;

		was_eof = true;
		nbytes = MAD_BUFFER_GUARD;
		memset(dest, 0, nbytes);
259
	}
260

261
	mad_stream_buffer(&stream, input_buffer, rest_size + nbytes);
262
	stream.error = MAD_ERROR_NONE;
Warren Dukes's avatar
Warren Dukes committed
263

Max Kellermann's avatar
Max Kellermann committed
264
	return true;
Warren Dukes's avatar
Warren Dukes committed
265 266
}

267
#ifdef ENABLE_ID3TAG
268 269
gcc_pure
static MixRampInfo
270
parse_id3_mixramp(struct id3_tag *tag) noexcept
271
{
272
	MixRampInfo result;
273

274 275
	struct id3_frame *frame;
	for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
276 277 278
		if (frame->nfields < 3)
			continue;

279
		char *const key = (char *)
280 281
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
282
		char *const value = (char *)
283 284 285
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

286
		ParseMixRampTag(result, key, value);
287 288 289 290 291

		free(key);
		free(value);
	}

292
	return result;
293 294 295
}
#endif

296
inline void
297
MadDecoder::ParseId3(size_t tagsize, Tag *mpd_tag) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
298
{
299
#ifdef ENABLE_ID3TAG
300
	std::unique_ptr<id3_byte_t[]> allocated;
301

302
	const id3_length_t count = stream.bufend - stream.this_frame;
303

304
	const id3_byte_t *id3_data;
Avuton Olrich's avatar
Avuton Olrich committed
305
	if (tagsize <= count) {
306 307
		id3_data = stream.this_frame;
		mad_stream_skip(&(stream), tagsize);
Avuton Olrich's avatar
Avuton Olrich committed
308
	} else {
309 310
		allocated.reset(new id3_byte_t[tagsize]);
		memcpy(allocated.get(), stream.this_frame, count);
311
		mad_stream_skip(&(stream), count);
312

313
		if (!decoder_read_full(client, input_stream,
314
				       allocated.get() + count, tagsize - count)) {
315
			LogDebug(mad_domain, "error parsing ID3 tag");
Max Kellermann's avatar
Max Kellermann committed
316
			return;
Warren Dukes's avatar
Warren Dukes committed
317
		}
318

319
		id3_data = allocated.get();
320 321
	}

322
	const UniqueId3Tag id3_tag(id3_tag_parse(id3_data, tagsize));
323
	if (id3_tag == nullptr)
Max Kellermann's avatar
Max Kellermann committed
324
		return;
325

326 327
	if (mpd_tag != nullptr)
		*mpd_tag = tag_id3_import(id3_tag.get());
328

329
	if (client != nullptr) {
330
		ReplayGainInfo rgi;
331

332
		if (Id3ToReplayGainInfo(rgi, id3_tag.get())) {
333
			client->SubmitReplayGain(&rgi);
334
			found_replay_gain = true;
335
		}
336

337
		client->SubmitMixRamp(parse_id3_mixramp(id3_tag.get()));
338 339
	}

340
#else /* !ENABLE_ID3TAG */
341 342 343 344 345
	(void)mpd_tag;

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

346
	size_t count = stream.bufend - stream.this_frame;
347 348

	if (tagsize <= count) {
349
		mad_stream_skip(&stream, tagsize);
350
	} else {
351
		mad_stream_skip(&stream, count);
352
		decoder_skip(client, input_stream, tagsize - count);
353
	}
354
#endif
355 356
}

357
#ifndef ENABLE_ID3TAG
358 359 360
/**
 * This function emulates libid3tag when it is disabled.  Instead of
 * doing a real analyzation of the frame, it just checks whether the
361 362
 * frame begins with the string "ID3".  If so, it returns the length
 * of the ID3 frame.
363 364
 */
static signed long
365
id3_tag_query(const void *p0, size_t length) noexcept
366
{
367
	const char *p = (const char *)p0;
368

369 370
	return length >= 10 && memcmp(p, "ID3", 3) == 0
		? (p[8] << 7) + p[9] + 10
371 372
		: 0;
}
373
#endif /* !ENABLE_ID3TAG */
374

375
static MadDecoderAction
376
RecoverFrameError(const struct mad_stream &stream) noexcept
377 378
{
	if (MAD_RECOVERABLE(stream.error))
379
		return MadDecoderAction::SKIP;
380 381 382 383

	FormatWarning(mad_domain,
		      "unrecoverable frame level error: %s",
		      mad_stream_errorstr(&stream));
384
	return MadDecoderAction::BREAK;
385 386
}

387
MadDecoderAction
388
MadDecoder::DecodeNextFrame(bool skip, Tag *tag) noexcept
Avuton Olrich's avatar
Avuton Olrich committed
389
{
390 391
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
392
		return MadDecoderAction::BREAK;
393

394
	if (mad_header_decode(&frame.header, &stream)) {
395 396 397
		if (stream.error == MAD_ERROR_BUFLEN)
			return MadDecoderAction::CONT;

398 399 400 401
		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
402 403

			if (tagsize > 0) {
404
				ParseId3((size_t)tagsize, tag);
405
				return MadDecoderAction::CONT;
406 407
			}
		}
408

409
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
410
	}
411

412 413 414
	enum mad_layer new_layer = frame.header.layer;
	if (layer == (mad_layer)0) {
		if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
415
			/* Only layer 2 and 3 have been tested to work */
416
			return MadDecoderAction::SKIP;
417
		}
418 419 420

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

425
	if (!skip && mad_frame_decode(&frame, &stream))
426
		return RecoverFrameError(stream);
Warren Dukes's avatar
Warren Dukes committed
427

428
	return MadDecoderAction::OK;
Warren Dukes's avatar
Warren Dukes committed
429 430
}

431
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
432 433 434 435
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');
436

Warren Dukes's avatar
Warren Dukes committed
437
struct xing {
438 439 440 441 442
	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
443 444
};

445 446 447 448
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
449

450
struct lame_version {
451 452
	unsigned major;
	unsigned minor;
453 454
};

455
struct lame {
456
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
457
	struct lame_version version; /* struct containing just the version */
458
	float peak;             /* replaygain peak */
Max Kellermann's avatar
Max Kellermann committed
459 460 461 462
	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 */
463
	int crc;                /* CRC of the first 190 bytes of this frame */
464 465
};

Max Kellermann's avatar
Max Kellermann committed
466
static bool
467
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen) noexcept
Warren Dukes's avatar
Warren Dukes committed
468
{
469
	int bitlen = *oldbitlen;
Warren Dukes's avatar
Warren Dukes committed
470

Max Kellermann's avatar
Max Kellermann committed
471 472 473
	if (bitlen < 16)
		return false;

474
	const unsigned long bits = mad_bit_read(ptr, 16);
475 476
	bitlen -= 16;

477
	if (bits == XI_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
478 479 480 481 482 483
		if (bitlen < 16)
			return false;

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

484
		bitlen -= 16;
485
	} else if (bits == IN_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
486 487 488 489 490 491
		if (bitlen < 16)
			return false;

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

492
		bitlen -= 16;
493
	}
494
	else if (bits != NG_MAGIC && bits != FO_MAGIC)
Max Kellermann's avatar
Max Kellermann committed
495
		return false;
496

Max Kellermann's avatar
Max Kellermann committed
497 498
	if (bitlen < 32)
		return false;
499
	xing->flags = mad_bit_read(ptr, 32);
500 501 502
	bitlen -= 32;

	if (xing->flags & XING_FRAMES) {
Max Kellermann's avatar
Max Kellermann committed
503 504
		if (bitlen < 32)
			return false;
505
		xing->frames = mad_bit_read(ptr, 32);
506 507 508 509
		bitlen -= 32;
	}

	if (xing->flags & XING_BYTES) {
Max Kellermann's avatar
Max Kellermann committed
510 511
		if (bitlen < 32)
			return false;
512
		xing->bytes = mad_bit_read(ptr, 32);
513 514
		bitlen -= 32;
	}
Warren Dukes's avatar
Warren Dukes committed
515

516
	if (xing->flags & XING_TOC) {
Max Kellermann's avatar
Max Kellermann committed
517 518
		if (bitlen < 800)
			return false;
519 520
		for (unsigned char & i : xing->toc)
			i = mad_bit_read(ptr, 8);
521 522 523 524
		bitlen -= 800;
	}

	if (xing->flags & XING_SCALE) {
Max Kellermann's avatar
Max Kellermann committed
525 526
		if (bitlen < 32)
			return false;
527
		xing->scale = mad_bit_read(ptr, 32);
528 529 530
		bitlen -= 32;
	}

531 532
	/* 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 */
533
	const int bitsleft = 960 - (*oldbitlen - bitlen);
Max Kellermann's avatar
Max Kellermann committed
534 535
	if (bitsleft < 0)
		return false;
536
	else if (bitsleft > 0) {
537
		mad_bit_skip(ptr, bitsleft);
538 539 540
		bitlen -= bitsleft;
	}

541
	*oldbitlen = bitlen;
542

Max Kellermann's avatar
Max Kellermann committed
543
	return true;
Warren Dukes's avatar
Warren Dukes committed
544 545
}

Max Kellermann's avatar
Max Kellermann committed
546
static bool
547
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen) noexcept
548 549 550
{
	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
	 * not all 36 bytes (288 bits) are there. */
551
	if (*bitlen < 288)
Max Kellermann's avatar
Max Kellermann committed
552
		return false;
553

554
	for (unsigned i = 0; i < 9; i++)
555
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
556 557
	lame->encoder[9] = '\0';

558 559
	*bitlen -= 72;

560 561 562
	/* 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. */
563
	if (!StringStartsWith(lame->encoder, "LAME"))
Max Kellermann's avatar
Max Kellermann committed
564
		return false;
565 566 567

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

570 571
	FormatDebug(mad_domain, "detected LAME version %i.%i (\"%s\")",
		    lame->version.major, lame->version.minor, lame->encoder);
572 573 574 575 576 577 578 579

	/* 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 */
580
	int adj = 0;
581 582 583
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;
584

585
	mad_bit_skip(ptr, 16);
586

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

Max Kellermann's avatar
Max Kellermann committed
590
	lame->track_gain = 0;
591 592 593
	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 */
594
	int gain = mad_bit_read(ptr, 9); /* gain*10 */
595
	if (gain && name == 1 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
596
		lame->track_gain = ((sign ? -gain : gain) / 10.0) + adj;
597 598
		FormatDebug(mad_domain, "LAME track gain found: %f",
			    lame->track_gain);
599
	}
600

601 602 603 604
	/* 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
605
	lame->album_gain = 0;
606 607 608 609 610 611
#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
612
		lame->album_gain = ((sign ? -gain : gain) / 10.0) + adj;
613 614
		FormatDebug(mad_domain, "LAME album gain found: %f",
			    lame->track_gain);
615
	}
616
#else
617
	mad_bit_skip(ptr, 16);
618 619
#endif

620
	mad_bit_skip(ptr, 16);
621

Max Kellermann's avatar
Max Kellermann committed
622 623
	lame->encoder_delay = mad_bit_read(ptr, 12);
	lame->encoder_padding = mad_bit_read(ptr, 12);
624

625 626
	FormatDebug(mad_domain, "encoder delay is %i, encoder padding is %i",
		    lame->encoder_delay, lame->encoder_padding);
627

628
	mad_bit_skip(ptr, 80);
629 630 631 632

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

	*bitlen -= 216;
633

Max Kellermann's avatar
Max Kellermann committed
634
	return true;
635 636
}

637
static inline SongTime
638
mad_frame_duration(const struct mad_frame *frame) noexcept
639
{
640
	return ToSongTime(frame->header.duration);
641 642
}

643
inline offset_type
644
MadDecoder::ThisFrameOffset() const noexcept
645
{
646
	auto offset = input_stream.GetOffset();
647

648 649
	if (stream.this_frame != nullptr)
		offset -= stream.bufend - stream.this_frame;
650
	else
651
		offset -= stream.bufend - stream.buffer;
652

653 654 655
	return offset;
}

656
inline offset_type
657
MadDecoder::RestIncludingThisFrame() const noexcept
658
{
659
	return input_stream.GetSize() - ThisFrameOffset();
660 661
}

662
inline void
663
MadDecoder::FileSizeToSongLength() noexcept
664
{
665
	if (input_stream.KnownSize()) {
666
		offset_type rest = RestIncludingThisFrame();
667

668
		const SongTime frame_duration = mad_frame_duration(&frame);
669 670 671 672
		const SongTime duration =
			SongTime::FromScale<uint64_t>(rest,
						      frame.header.bitrate / 8);
		total_time = duration;
673

674 675 676 677
		max_frames = (frame_duration.IsPositive()
			      ? duration.count() / frame_duration.count()
			      : 0)
			+ FRAMES_CUSHION;
678
	} else {
679
		max_frames = FRAMES_CUSHION;
680
		total_time = SignedSongTime::Negative();
681 682 683
	}
}

684
inline bool
685
MadDecoder::DecodeFirstFrame(Tag *tag) noexcept
686
{
687
	struct xing xing;
688

689 690 691 692 693
#if GCC_CHECK_VERSION(10,0)
	/* work around bogus -Wuninitialized in GCC 10 */
	xing.frames = 0;
#endif

Max Kellermann's avatar
Max Kellermann committed
694
	while (true) {
695 696 697 698 699
		const auto action = DecodeNextFrame(false, tag);
		switch (action) {
		case MadDecoderAction::SKIP:
		case MadDecoderAction::CONT:
			continue;
700

701
		case MadDecoderAction::BREAK:
Max Kellermann's avatar
Max Kellermann committed
702
			return false;
703 704 705 706 707 708

		case MadDecoderAction::OK:
			break;
		}

		break;
Avuton Olrich's avatar
Avuton Olrich committed
709 710
	}

711 712
	struct mad_bitptr ptr = stream.anc_ptr;
	int bitlen = stream.anc_bitlen;
713

714
	FileSizeToSongLength();
715

716 717 718
	/*
	 * if an xing tag exists, use that!
	 */
719
	if (parse_xing(&xing, &ptr, &bitlen)) {
720
		mute_frame = MadDecoderMuteFrame::SKIP;
721

722
		if ((xing.flags & XING_FRAMES) && xing.frames) {
723
			mad_timer_t duration = frame.header.duration;
Avuton Olrich's avatar
Avuton Olrich committed
724
			mad_timer_multiply(&duration, xing.frames);
725
			total_time = ToSongTime(duration);
726
			max_frames = xing.frames;
Warren Dukes's avatar
Warren Dukes committed
727
		}
728

729
		struct lame lame;
730
		if (parse_lame(&lame, &ptr, &bitlen)) {
731
			if (input_stream.IsSeekable()) {
732 733 734 735
				/* libmad inserts 529 samples of
				   silence at the beginning and
				   removes those 529 samples at the
				   end */
736
				drop_start_samples = lame.encoder_delay +
737
				                           DECODERDELAY;
738
				drop_end_samples = lame.encoder_padding;
739 740 741 742
				if (drop_end_samples > DECODERDELAY)
					drop_end_samples -= DECODERDELAY;
				else
					drop_end_samples = 0;
743 744 745 746
			}

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

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

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

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

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

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

781
size_t
782
MadDecoder::TimeToFrame(SongTime t) const noexcept
783
{
784
	size_t i;
785

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

	return i;
}

795
void
796
MadDecoder::UpdateTimerNextFrame() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
797
{
798 799 800 801 802 803 804
	if (current_frame >= highest_frame) {
		/* record this frame's properties in frame_offsets
		   (for seeking) and times */

		if (current_frame >= max_frames)
			/* cap current_frame */
			current_frame = max_frames - 1;
805
		else
806
			highest_frame++;
807

808
		frame_offsets[current_frame] = ThisFrameOffset();
809

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

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

820
DecoderCommand
821
MadDecoder::SubmitPCM(size_t i, size_t pcm_length) noexcept
822
{
823
	size_t num_samples = pcm_length - i;
824

825
	mad_fixed_to_24_buffer(output_buffer, synth.pcm,
826 827 828
			       i, i + num_samples,
			       MAD_NCHANNELS(&frame.header));
	num_samples *= MAD_NCHANNELS(&frame.header);
829

830 831 832
	return client->SubmitData(input_stream, output_buffer,
				  sizeof(output_buffer[0]) * num_samples,
				  frame.header.bitrate / 1000);
833 834
}

835
inline DecoderCommand
836
MadDecoder::SynthAndSubmit() noexcept
837
{
838 839 840 841 842 843 844 845 846
	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;
847 848
	}

849 850
	if (drop_start_frames > 0) {
		drop_start_frames--;
851
		return DecoderCommand::NONE;
852
	} else if ((drop_end_frames > 0) &&
853
		   current_frame == max_frames - drop_end_frames) {
854 855
		/* stop decoding, effectively dropping all remaining
		   frames */
856
		return DecoderCommand::STOP;
857 858
	}

859
	size_t i = 0;
860 861 862 863
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
864

865
	size_t pcm_length = synth.pcm.length;
866
	if (drop_end_samples &&
867
	    current_frame == max_frames - drop_end_frames - 1) {
868
		if (drop_end_samples >= pcm_length)
869 870 871
			return DecoderCommand::STOP;

		pcm_length -= drop_end_samples;
872 873
	}

874
	auto cmd = SubmitPCM(i, pcm_length);
875
	if (cmd != DecoderCommand::NONE)
876 877
		return cmd;

878
	if (drop_end_samples &&
879
	    current_frame == max_frames - drop_end_frames - 1)
880 881
		/* stop decoding, effectively dropping
		 * all remaining samples */
882
		return DecoderCommand::STOP;
883

884
	return DecoderCommand::NONE;
885 886
}

887
inline bool
888
MadDecoder::HandleCurrentFrame() noexcept
889
{
890
	switch (mute_frame) {
891 892
		DecoderCommand cmd;

893 894
	case MadDecoderMuteFrame::SKIP:
		mute_frame = MadDecoderMuteFrame::NONE;
Avuton Olrich's avatar
Avuton Olrich committed
895
		break;
896
	case MadDecoderMuteFrame::SEEK:
897
		if (elapsed_time >= seek_time)
898
			mute_frame = MadDecoderMuteFrame::NONE;
899
		UpdateTimerNextFrame();
Avuton Olrich's avatar
Avuton Olrich committed
900
		break;
901
	case MadDecoderMuteFrame::NONE:
902
		cmd = SynthAndSubmit();
903
		UpdateTimerNextFrame();
904
		if (cmd == DecoderCommand::SEEK) {
905
			assert(input_stream.IsSeekable());
906

907
			const auto t = client->GetSeekTime();
908
			size_t j = TimeToFrame(t);
909 910 911
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
912
					was_eof = false;
913
					client->CommandFinished();
Avuton Olrich's avatar
Avuton Olrich committed
914
				} else
915
					client->SeekError();
Max Kellermann's avatar
Max Kellermann committed
916
			} else {
917
				seek_time = t;
918
				mute_frame = MadDecoderMuteFrame::SEEK;
919
				client->CommandFinished();
Max Kellermann's avatar
Max Kellermann committed
920
			}
921
		} else if (cmd != DecoderCommand::NONE)
922
			return false;
Warren Dukes's avatar
Warren Dukes committed
923 924
	}

925 926 927 928
	return true;
}

inline bool
929
MadDecoder::LoadNextFrame() noexcept
930
{
Max Kellermann's avatar
Max Kellermann committed
931
	while (true) {
932
		Tag tag;
933

934 935 936 937 938
		const auto action =
			DecodeNextFrame(mute_frame != MadDecoderMuteFrame::NONE,
					&tag);
		if (!tag.IsEmpty())
			client->SubmitTag(input_stream, std::move(tag));
939

940 941 942 943
		switch (action) {
		case MadDecoderAction::SKIP:
		case MadDecoderAction::CONT:
			continue;
944

945 946
		case MadDecoderAction::BREAK:
			return false;
947

948
		case MadDecoderAction::OK:
949
			return true;
950
		}
Warren Dukes's avatar
Warren Dukes committed
951 952 953
	}
}

954 955
inline bool
MadDecoder::Read() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
956
{
957 958 959 960
	return HandleCurrentFrame() &&
		LoadNextFrame();
}

961 962
inline void
MadDecoder::RunDecoder() noexcept
Avuton Olrich's avatar
Avuton Olrich committed
963
{
964
	assert(client != nullptr);
965

966
	Tag tag;
967 968
	if (!DecodeFirstFrame(&tag)) {
		if (client->GetCommand() == DecoderCommand::NONE)
969
			LogError(mad_domain,
970
				 "input does not appear to be a mp3 bit stream");
971
		return;
Warren Dukes's avatar
Warren Dukes committed
972 973
	}

974
	AllocateBuffers();
975

976 977 978 979 980
	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
981

982
	if (!tag.IsEmpty())
983
		client->SubmitTag(input_stream, std::move(tag));
984

985
	while (Read()) {}
Warren Dukes's avatar
Warren Dukes committed
986 987
}

988 989
static void
mad_decode(DecoderClient &client, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
990
{
991 992 993 994 995 996 997 998
	MadDecoder data(&client, input_stream);
	data.RunDecoder();
}

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

1001 1002
	if (!total_time.IsNegative())
		handler.OnDuration(SongTime(total_time));
1003 1004

	try {
1005
		handler.OnAudioFormat(CheckAudioFormat(frame.header.samplerate,
1006
						       SampleFormat::S24_P32,
1007
						       MAD_NCHANNELS(&frame.header)));
1008 1009 1010
	} catch (...) {
	}

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

1014 1015 1016 1017 1018 1019 1020
static bool
mad_decoder_scan_stream(InputStream &is, TagHandler &handler) noexcept
{
	MadDecoder data(nullptr, is);
	return data.RunScan(handler);
}

1021 1022
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
1023

1024
constexpr DecoderPlugin mad_decoder_plugin =
1025 1026 1027
	DecoderPlugin("mad", mad_decode, mad_decoder_scan_stream)
	.WithSuffixes(mad_suffixes)
	.WithMimeTypes(mad_mime_types);