MadDecoderPlugin.cxx 26.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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
#include "tag/TagId3.hxx"
#include "tag/TagRva2.hxx"
27
#include "tag/TagHandler.hxx"
28
#include "CheckAudioFormat.hxx"
29
#include "util/StringUtil.hxx"
30
#include "util/ASCII.hxx"
31
#include "util/Error.hxx"
32 33
#include "util/Domain.hxx"
#include "Log.hxx"
Warren Dukes's avatar
Warren Dukes committed
34 35

#include <mad.h>
36

37 38 39
#ifdef HAVE_ID3TAG
#include <id3tag.h>
#endif
40

41 42 43 44 45
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

46
#define FRAMES_CUSHION    2000
Warren Dukes's avatar
Warren Dukes committed
47

48
#define READ_BUFFER_SIZE  40960
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 64 65
/* the number of samples of silence the decoder inserts at start */
#define DECODERDELAY 529

Max Kellermann's avatar
Max Kellermann committed
66
#define 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
static inline int32_t
mad_fixed_to_24_sample(mad_fixed_t sample)
Avuton Olrich's avatar
Avuton Olrich committed
74
{
Warren Dukes's avatar
Warren Dukes committed
75
	enum {
76
		bits = 24,
Warren Dukes's avatar
Warren Dukes committed
77
		MIN = -MAD_F_ONE,
Avuton Olrich's avatar
Avuton Olrich committed
78
		MAX = MAD_F_ONE - 1
Warren Dukes's avatar
Warren Dukes committed
79 80
	};

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

84
	/* clip */
85
	if (gcc_unlikely(sample > MAX))
86
		sample = MAX;
87
	else if (gcc_unlikely(sample < MIN))
88
		sample = MIN;
Warren Dukes's avatar
Warren Dukes committed
89

90 91
	/* quantize */
	return sample >> (MAD_F_FRACBITS + 1 - bits);
Warren Dukes's avatar
Warren Dukes committed
92
}
Avuton Olrich's avatar
Avuton Olrich committed
93

94 95 96 97
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)
98
{
99
	unsigned int i, c;
100 101

	for (i = start; i < end; ++i) {
102
		for (c = 0; c < num_channels; ++c)
103
			*dest++ = mad_fixed_to_24_sample(synth->pcm.samples[c][i]);
104 105 106
	}
}

107
static bool
108
mp3_plugin_init(gcc_unused const config_param &param)
109
{
110 111
	gapless_playback = config_get_bool(CONF_GAPLESS_MP3_PLAYBACK,
					   DEFAULT_GAPLESS_MP3_PLAYBACK);
112
	return true;
113 114
}

115
#define MP3_DATA_OUTPUT_BUFFER_SIZE 2048
116

117
struct MadDecoder {
Warren Dukes's avatar
Warren Dukes committed
118 119 120 121
	struct mad_stream stream;
	struct mad_frame frame;
	struct mad_synth synth;
	mad_timer_t timer;
Max Kellermann's avatar
Max Kellermann committed
122 123 124 125
	unsigned char input_buffer[READ_BUFFER_SIZE];
	int32_t output_buffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
	float total_time;
	float elapsed_time;
Max Kellermann's avatar
Max Kellermann committed
126
	float seek_where;
Max Kellermann's avatar
Max Kellermann committed
127 128
	enum muteframe mute_frame;
	long *frame_offsets;
Avuton Olrich's avatar
Avuton Olrich committed
129
	mad_timer_t *times;
Max Kellermann's avatar
Max Kellermann committed
130 131 132 133 134 135 136
	unsigned long highest_frame;
	unsigned long max_frames;
	unsigned long current_frame;
	unsigned int drop_start_frames;
	unsigned int drop_end_frames;
	unsigned int drop_start_samples;
	unsigned int drop_end_samples;
137
	bool found_replay_gain;
Max Kellermann's avatar
Max Kellermann committed
138 139 140
	bool found_xing;
	bool found_first_frame;
	bool decoded_first_frame;
Max Kellermann's avatar
Max Kellermann committed
141
	unsigned long bit_rate;
142
	Decoder *const decoder;
143
	InputStream &input_stream;
144
	enum mad_layer layer;
145

146
	MadDecoder(Decoder *decoder, InputStream &input_stream);
147 148 149 150
	~MadDecoder();

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

	gcc_pure
156
	offset_type ThisFrameOffset() const;
157 158

	gcc_pure
159
	offset_type RestIncludingThisFrame() const;
160 161 162 163 164 165

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

Max Kellermann's avatar
Max Kellermann committed
166
	bool DecodeFirstFrame(Tag **tag);
167 168 169 170 171 172 173 174 175

	gcc_pure
	long TimeToFrame(double t) const;

	void UpdateTimerNextFrame();

	/**
	 * Sends the synthesized current frame via decoder_data().
	 */
176
	DecoderCommand SendPCM(unsigned i, unsigned pcm_length);
177 178 179 180 181

	/**
	 * Synthesize the current frame and send it via
	 * decoder_data().
	 */
182
	DecoderCommand SyncAndSend();
183 184

	bool Read();
Max Kellermann's avatar
Max Kellermann committed
185
};
Warren Dukes's avatar
Warren Dukes committed
186

187
MadDecoder::MadDecoder(Decoder *_decoder,
188
		       InputStream &_input_stream)
189 190 191 192 193 194 195 196 197 198
	:mute_frame(MUTEFRAME_NONE),
	 frame_offsets(nullptr),
	 times(nullptr),
	 highest_frame(0), max_frames(0), current_frame(0),
	 drop_start_frames(0), drop_end_frames(0),
	 drop_start_samples(0), drop_end_samples(0),
	 found_replay_gain(false), found_xing(false),
	 found_first_frame(false), decoded_first_frame(false),
	 decoder(_decoder), input_stream(_input_stream),
	 layer(mad_layer(0))
Avuton Olrich's avatar
Avuton Olrich committed
199
{
200 201 202 203 204
	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
205 206
}

207 208
inline bool
MadDecoder::Seek(long offset)
Avuton Olrich's avatar
Avuton Olrich committed
209
{
210
	Error error;
211
	if (!input_stream.LockSeek(offset, error))
Max Kellermann's avatar
Max Kellermann committed
212
		return false;
213

214 215
	mad_stream_buffer(&stream, input_buffer, 0);
	stream.error = MAD_ERROR_NONE;
216

Max Kellermann's avatar
Max Kellermann committed
217
	return true;
218 219
}

220 221
inline bool
MadDecoder::FillBuffer()
Avuton Olrich's avatar
Avuton Olrich committed
222
{
Max Kellermann's avatar
Max Kellermann committed
223 224 225
	size_t remaining, length;
	unsigned char *dest;

226 227 228 229
	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
230
		length = READ_BUFFER_SIZE - remaining;
Avuton Olrich's avatar
Avuton Olrich committed
231
	} else {
Max Kellermann's avatar
Max Kellermann committed
232 233
		remaining = 0;
		length = READ_BUFFER_SIZE;
234
		dest = input_buffer;
Warren Dukes's avatar
Warren Dukes committed
235 236
	}

237 238
	/* 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
239
	if (length == 0)
Max Kellermann's avatar
Max Kellermann committed
240
		return false;
241

242
	length = decoder_read(decoder, input_stream, dest, length);
Max Kellermann's avatar
Max Kellermann committed
243
	if (length == 0)
Max Kellermann's avatar
Max Kellermann committed
244
		return false;
245

246 247
	mad_stream_buffer(&stream, input_buffer, length + remaining);
	stream.error = MAD_ERROR_NONE;
Warren Dukes's avatar
Warren Dukes committed
248

Max Kellermann's avatar
Max Kellermann committed
249
	return true;
Warren Dukes's avatar
Warren Dukes committed
250 251
}

252
#ifdef HAVE_ID3TAG
253
static bool
254
parse_id3_replay_gain_info(ReplayGainInfo &rgi,
255
			   struct id3_tag *tag)
Avuton Olrich's avatar
Avuton Olrich committed
256
{
257
	int i;
Avuton Olrich's avatar
Avuton Olrich committed
258 259 260
	char *key;
	char *value;
	struct id3_frame *frame;
261
	bool found = false;
262

263
	rgi.Clear();
264

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

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

276
		if (StringEqualsCaseASCII(key, "replaygain_track_gain")) {
277
			rgi.tuples[REPLAY_GAIN_TRACK].gain = atof(value);
278
			found = true;
279
		} else if (StringEqualsCaseASCII(key, "replaygain_album_gain")) {
280
			rgi.tuples[REPLAY_GAIN_ALBUM].gain = atof(value);
281
			found = true;
282
		} else if (StringEqualsCaseASCII(key, "replaygain_track_peak")) {
283
			rgi.tuples[REPLAY_GAIN_TRACK].peak = atof(value);
284
			found = true;
285
		} else if (StringEqualsCaseASCII(key, "replaygain_album_peak")) {
286
			rgi.tuples[REPLAY_GAIN_ALBUM].peak = atof(value);
287
			found = true;
288 289 290 291 292 293
		}

		free(key);
		free(value);
	}

294
	return found ||
295
		/* fall back on RVA2 if no replaygain tags found */
296
		tag_rva2_parse(tag, rgi);
297
}
298
#endif
299

300
#ifdef HAVE_ID3TAG
301 302 303
gcc_pure
static MixRampInfo
parse_id3_mixramp(struct id3_tag *tag)
304 305 306 307 308 309
{
	int i;
	char *key;
	char *value;
	struct id3_frame *frame;

310
	MixRampInfo result;
311 312 313 314 315 316 317 318 319 320 321 322

	for (i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
		if (frame->nfields < 3)
			continue;

		key = (char *)
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[1]));
		value = (char *)
		    id3_ucs4_latin1duplicate(id3_field_getstring
					     (&frame->fields[2]));

323
		if (StringEqualsCaseASCII(key, "mixramp_start")) {
324
			result.SetStart(value);
325
		} else if (StringEqualsCaseASCII(key, "mixramp_end")) {
326
			result.SetEnd(value);
327 328 329 330 331 332
		}

		free(key);
		free(value);
	}

333
	return result;
334 335 336
}
#endif

337
inline void
Max Kellermann's avatar
Max Kellermann committed
338
MadDecoder::ParseId3(size_t tagsize, Tag **mpd_tag)
Avuton Olrich's avatar
Avuton Olrich committed
339
{
340
#ifdef HAVE_ID3TAG
341
	struct id3_tag *id3_tag = nullptr;
342 343
	id3_length_t count;
	id3_byte_t const *id3_data;
344
	id3_byte_t *allocated = nullptr;
345

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

Avuton Olrich's avatar
Avuton Olrich committed
348
	if (tagsize <= count) {
349 350
		id3_data = stream.this_frame;
		mad_stream_skip(&(stream), tagsize);
Avuton Olrich's avatar
Avuton Olrich committed
351
	} else {
352
		allocated = new id3_byte_t[tagsize];
353 354
		memcpy(allocated, stream.this_frame, count);
		mad_stream_skip(&(stream), count);
355

356 357
		if (!decoder_read_full(decoder, input_stream,
				       allocated + count, tagsize - count)) {
358
			LogDebug(mad_domain, "error parsing ID3 tag");
359
			delete[] allocated;
Max Kellermann's avatar
Max Kellermann committed
360
			return;
Warren Dukes's avatar
Warren Dukes committed
361
		}
362 363 364 365

		id3_data = allocated;
	}

Max Kellermann's avatar
Max Kellermann committed
366
	id3_tag = id3_tag_parse(id3_data, tagsize);
367
	if (id3_tag == nullptr) {
368
		delete[] allocated;
Max Kellermann's avatar
Max Kellermann committed
369 370
		return;
	}
371

Max Kellermann's avatar
Max Kellermann committed
372
	if (mpd_tag) {
Max Kellermann's avatar
Max Kellermann committed
373
		Tag *tmp_tag = tag_id3_import(id3_tag);
374
		if (tmp_tag != nullptr) {
Max Kellermann's avatar
Max Kellermann committed
375
			delete *mpd_tag;
Max Kellermann's avatar
Max Kellermann committed
376
			*mpd_tag = tmp_tag;
377
		}
378
	}
379

380
	if (decoder != nullptr) {
381
		ReplayGainInfo rgi;
382

383
		if (parse_id3_replay_gain_info(rgi, id3_tag)) {
384
			decoder_replay_gain(*decoder, &rgi);
385
			found_replay_gain = true;
386
		}
387

388
		decoder_mixramp(*decoder, parse_id3_mixramp(id3_tag));
389 390
	}

Max Kellermann's avatar
Max Kellermann committed
391
	id3_tag_delete(id3_tag);
Max Kellermann's avatar
Max Kellermann committed
392

393
	delete[] allocated;
394 395 396 397 398 399
#else /* !HAVE_ID3TAG */
	(void)mpd_tag;

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

400
	size_t count = stream.bufend - stream.this_frame;
401 402

	if (tagsize <= count) {
403
		mad_stream_skip(&stream, tagsize);
404
	} else {
405
		mad_stream_skip(&stream, count);
406
		decoder_skip(decoder, input_stream, tagsize - count);
407
	}
408
#endif
409 410 411 412 413 414
}

#ifndef HAVE_ID3TAG
/**
 * This function emulates libid3tag when it is disabled.  Instead of
 * doing a real analyzation of the frame, it just checks whether the
415 416
 * frame begins with the string "ID3".  If so, it returns the length
 * of the ID3 frame.
417 418 419 420
 */
static signed long
id3_tag_query(const void *p0, size_t length)
{
421
	const char *p = (const char *)p0;
422

423 424
	return length >= 10 && memcmp(p, "ID3", 3) == 0
		? (p[8] << 7) + p[9] + 10
425 426 427
		: 0;
}
#endif /* !HAVE_ID3TAG */
428

429
enum mp3_action
Max Kellermann's avatar
Max Kellermann committed
430
MadDecoder::DecodeNextFrameHeader(Tag **tag)
Avuton Olrich's avatar
Avuton Olrich committed
431
{
432 433 434
	if ((stream.buffer == nullptr || stream.error == MAD_ERROR_BUFLEN) &&
	    !FillBuffer())
		return DECODE_BREAK;
435

436 437 438 439 440
	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
441 442 443

			if (tagsize > 0) {
				if (tag && !(*tag)) {
444
					ParseId3((size_t)tagsize, tag);
Avuton Olrich's avatar
Avuton Olrich committed
445
				} else {
446
					mad_stream_skip(&stream, tagsize);
447
				}
448 449 450
				return DECODE_CONT;
			}
		}
451
		if (MAD_RECOVERABLE(stream.error)) {
452
			return DECODE_SKIP;
Avuton Olrich's avatar
Avuton Olrich committed
453
		} else {
454
			if (stream.error == MAD_ERROR_BUFLEN)
Avuton Olrich's avatar
Avuton Olrich committed
455 456
				return DECODE_CONT;
			else {
457 458 459
				FormatWarning(mad_domain,
					      "unrecoverable frame level error: %s",
					      mad_stream_errorstr(&stream));
Warren Dukes's avatar
Warren Dukes committed
460 461 462 463
				return DECODE_BREAK;
			}
		}
	}
464

465 466 467
	enum mad_layer new_layer = frame.header.layer;
	if (layer == (mad_layer)0) {
		if (new_layer != MAD_LAYER_II && new_layer != MAD_LAYER_III) {
468
			/* Only layer 2 and 3 have been tested to work */
469
			return DECODE_SKIP;
470
		}
471 472 473

		layer = new_layer;
	} else if (new_layer != layer) {
474
		/* Don't decode frames with a different layer than the first */
475 476
		return DECODE_SKIP;
	}
Warren Dukes's avatar
Warren Dukes committed
477 478 479 480

	return DECODE_OK;
}

481 482
enum mp3_action
MadDecoder::DecodeNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
483
{
484 485 486 487 488 489 490 491 492
	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
493
			if (tagsize > 0) {
494
				mad_stream_skip(&stream, tagsize);
495 496 497
				return DECODE_CONT;
			}
		}
498
		if (MAD_RECOVERABLE(stream.error)) {
499
			return DECODE_SKIP;
Avuton Olrich's avatar
Avuton Olrich committed
500
		} else {
501
			if (stream.error == MAD_ERROR_BUFLEN)
Avuton Olrich's avatar
Avuton Olrich committed
502 503
				return DECODE_CONT;
			else {
504 505 506
				FormatWarning(mad_domain,
					      "unrecoverable frame level error: %s",
					      mad_stream_errorstr(&stream));
Warren Dukes's avatar
Warren Dukes committed
507 508 509 510 511 512 513 514
				return DECODE_BREAK;
			}
		}
	}

	return DECODE_OK;
}

515
/* xing stuff stolen from alsaplayer, and heavily modified by jat */
516 517
#define XI_MAGIC (('X' << 8) | 'i')
#define NG_MAGIC (('n' << 8) | 'g')
518 519 520 521
#define IN_MAGIC (('I' << 8) | 'n')
#define FO_MAGIC (('f' << 8) | 'o')

enum xing_magic {
522
	XING_MAGIC_XING, /* VBR */
523
	XING_MAGIC_INFO  /* CBR */
524
};
Warren Dukes's avatar
Warren Dukes committed
525 526

struct xing {
527 528 529 530 531 532
	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
533 534 535
};

enum {
Avuton Olrich's avatar
Avuton Olrich committed
536
	XING_FRAMES = 0x00000001L,
537 538
	XING_BYTES  = 0x00000002L,
	XING_TOC    = 0x00000004L,
539
	XING_SCALE  = 0x00000008L
Warren Dukes's avatar
Warren Dukes committed
540 541
};

542
struct lame_version {
543 544
	unsigned major;
	unsigned minor;
545 546
};

547
struct lame {
548
	char encoder[10];       /* 9 byte encoder name/version ("LAME3.97b") */
549
	struct lame_version version; /* struct containing just the version */
550
	float peak;             /* replaygain peak */
Max Kellermann's avatar
Max Kellermann committed
551 552 553 554
	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 */
555
	int crc;                /* CRC of the first 190 bytes of this frame */
556 557
};

Max Kellermann's avatar
Max Kellermann committed
558 559
static bool
parse_xing(struct xing *xing, struct mad_bitptr *ptr, int *oldbitlen)
Warren Dukes's avatar
Warren Dukes committed
560
{
561
	unsigned long bits;
562
	int bitlen;
563 564 565
	int bitsleft;
	int i;

566
	bitlen = *oldbitlen;
Warren Dukes's avatar
Warren Dukes committed
567

Max Kellermann's avatar
Max Kellermann committed
568 569 570
	if (bitlen < 16)
		return false;

571
	bits = mad_bit_read(ptr, 16);
572 573
	bitlen -= 16;

574
	if (bits == XI_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
575 576 577 578 579 580
		if (bitlen < 16)
			return false;

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

581
		bitlen -= 16;
582 583
		xing->magic = XING_MAGIC_XING;
	} else if (bits == IN_MAGIC) {
Max Kellermann's avatar
Max Kellermann committed
584 585 586 587 588 589
		if (bitlen < 16)
			return false;

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

590 591
		bitlen -= 16;
		xing->magic = XING_MAGIC_INFO;
592 593 594
	}
	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
595 596
	else
		return false;
597

Max Kellermann's avatar
Max Kellermann committed
598 599
	if (bitlen < 32)
		return false;
600
	xing->flags = mad_bit_read(ptr, 32);
601 602 603
	bitlen -= 32;

	if (xing->flags & XING_FRAMES) {
Max Kellermann's avatar
Max Kellermann committed
604 605
		if (bitlen < 32)
			return false;
606
		xing->frames = mad_bit_read(ptr, 32);
607 608 609 610
		bitlen -= 32;
	}

	if (xing->flags & XING_BYTES) {
Max Kellermann's avatar
Max Kellermann committed
611 612
		if (bitlen < 32)
			return false;
613
		xing->bytes = mad_bit_read(ptr, 32);
614 615
		bitlen -= 32;
	}
Warren Dukes's avatar
Warren Dukes committed
616

617
	if (xing->flags & XING_TOC) {
Max Kellermann's avatar
Max Kellermann committed
618 619
		if (bitlen < 800)
			return false;
620
		for (i = 0; i < 100; ++i) xing->toc[i] = mad_bit_read(ptr, 8);
621 622 623 624
		bitlen -= 800;
	}

	if (xing->flags & XING_SCALE) {
Max Kellermann's avatar
Max Kellermann committed
625 626
		if (bitlen < 32)
			return false;
627
		xing->scale = mad_bit_read(ptr, 32);
628 629 630
		bitlen -= 32;
	}

631 632
	/* 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 */
633
	bitsleft = 960 - ((*oldbitlen) - bitlen);
Max Kellermann's avatar
Max Kellermann committed
634 635
	if (bitsleft < 0)
		return false;
636 637 638 639 640
	else if (bitsleft > 0) {
		mad_bit_read(ptr, bitsleft);
		bitlen -= bitsleft;
	}

641
	*oldbitlen = bitlen;
642

Max Kellermann's avatar
Max Kellermann committed
643
	return true;
Warren Dukes's avatar
Warren Dukes committed
644 645
}

Max Kellermann's avatar
Max Kellermann committed
646 647
static bool
parse_lame(struct lame *lame, struct mad_bitptr *ptr, int *bitlen)
648
{
649 650 651 652 653
	int adj = 0;
	int name;
	int orig;
	int sign;
	int gain;
654 655 656 657
	int i;

	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
	 * not all 36 bytes (288 bits) are there. */
658
	if (*bitlen < 288)
Max Kellermann's avatar
Max Kellermann committed
659
		return false;
660

661 662
	for (i = 0; i < 9; i++)
		lame->encoder[i] = (char)mad_bit_read(ptr, 8);
663 664
	lame->encoder[9] = '\0';

665 666
	*bitlen -= 72;

667 668 669
	/* 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. */
670
	if (!StringStartsWith(lame->encoder, "LAME"))
Max Kellermann's avatar
Max Kellermann committed
671
		return false;
672 673 674

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

677 678
	FormatDebug(mad_domain, "detected LAME version %i.%i (\"%s\")",
		    lame->version.major, lame->version.minor, lame->encoder);
679 680 681 682 683 684 685 686 687 688 689

	/* 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 */
	if (lame->version.major < 3 ||
	    (lame->version.major == 3 && lame->version.minor < 95))
		adj = 6;
690 691 692

	mad_bit_read(ptr, 16);

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

Max Kellermann's avatar
Max Kellermann committed
696
	lame->track_gain = 0;
697 698 699 700 701
	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 == 1 && orig != 0) {
Max Kellermann's avatar
Max Kellermann committed
702
		lame->track_gain = ((sign ? -gain : gain) / 10.0) + adj;
703 704
		FormatDebug(mad_domain, "LAME track gain found: %f",
			    lame->track_gain);
705
	}
706

707 708 709 710
	/* 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
711
	lame->album_gain = 0;
712 713 714 715 716 717
#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
718
		lame->album_gain = ((sign ? -gain : gain) / 10.0) + adj;
719 720
		FormatDebug(mad_domain, "LAME album gain found: %f",
			    lame->track_gain);
721
	}
722
#else
723
	mad_bit_read(ptr, 16);
724 725
#endif

726 727
	mad_bit_read(ptr, 16);

Max Kellermann's avatar
Max Kellermann committed
728 729
	lame->encoder_delay = mad_bit_read(ptr, 12);
	lame->encoder_padding = mad_bit_read(ptr, 12);
730

731 732
	FormatDebug(mad_domain, "encoder delay is %i, encoder padding is %i",
		    lame->encoder_delay, lame->encoder_padding);
733

734 735 736 737 738
	mad_bit_read(ptr, 80);

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

	*bitlen -= 216;
739

Max Kellermann's avatar
Max Kellermann committed
740
	return true;
741 742
}

743 744 745 746 747 748 749
static inline float
mp3_frame_duration(const struct mad_frame *frame)
{
	return mad_timer_count(frame->header.duration,
			       MAD_UNITS_MILLISECONDS) / 1000.0;
}

750
inline offset_type
751
MadDecoder::ThisFrameOffset() const
752
{
753
	auto offset = input_stream.GetOffset();
754

755 756
	if (stream.this_frame != nullptr)
		offset -= stream.bufend - stream.this_frame;
757
	else
758
		offset -= stream.bufend - stream.buffer;
759

760 761 762
	return offset;
}

763
inline offset_type
764
MadDecoder::RestIncludingThisFrame() const
765
{
766
	return input_stream.GetSize() - ThisFrameOffset();
767 768
}

769 770
inline void
MadDecoder::FileSizeToSongLength()
771
{
772
	if (input_stream.KnownSize()) {
773
		offset_type rest = RestIncludingThisFrame();
774

775
		float frame_duration = mp3_frame_duration(&frame);
776

777 778
		total_time = (rest * 8.0) / frame.header.bitrate;
		max_frames = total_time / frame_duration + FRAMES_CUSHION;
779
	} else {
780 781
		max_frames = FRAMES_CUSHION;
		total_time = 0;
782 783 784
	}
}

785
inline bool
Max Kellermann's avatar
Max Kellermann committed
786
MadDecoder::DecodeFirstFrame(Tag **tag)
787
{
Warren Dukes's avatar
Warren Dukes committed
788
	struct xing xing;
789
	struct lame lame;
790 791
	struct mad_bitptr ptr;
	int bitlen;
792
	enum mp3_action ret;
Warren Dukes's avatar
Warren Dukes committed
793

794 795 796
	/* stfu gcc */
	memset(&xing, 0, sizeof(struct xing));
	xing.flags = 0;
797

Max Kellermann's avatar
Max Kellermann committed
798
	while (true) {
799
		do {
800
			ret = DecodeNextFrameHeader(tag);
801 802
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
803
			return false;
804
		if (ret == DECODE_SKIP) continue;
805

806
		do {
807
			ret = DecodeNextFrame();
808 809
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
Max Kellermann's avatar
Max Kellermann committed
810
			return false;
811
		if (ret == DECODE_OK) break;
Avuton Olrich's avatar
Avuton Olrich committed
812 813
	}

814 815
	ptr = stream.anc_ptr;
	bitlen = stream.anc_bitlen;
816

817
	FileSizeToSongLength();
818

819 820 821
	/*
	 * if an xing tag exists, use that!
	 */
822
	if (parse_xing(&xing, &ptr, &bitlen)) {
823 824
		found_xing = true;
		mute_frame = MUTEFRAME_SKIP;
825

826
		if ((xing.flags & XING_FRAMES) && xing.frames) {
827
			mad_timer_t duration = frame.header.duration;
Avuton Olrich's avatar
Avuton Olrich committed
828
			mad_timer_multiply(&duration, xing.frames);
829 830
			total_time = ((float)mad_timer_count(duration, MAD_UNITS_MILLISECONDS)) / 1000;
			max_frames = xing.frames;
Warren Dukes's avatar
Warren Dukes committed
831
		}
832 833

		if (parse_lame(&lame, &ptr, &bitlen)) {
834
			if (gapless_playback && input_stream.IsSeekable()) {
835
				drop_start_samples = lame.encoder_delay +
836
				                           DECODERDELAY;
837
				drop_end_samples = lame.encoder_padding;
838 839 840 841
			}

			/* Album gain isn't currently used.  See comment in
			 * parse_lame() for details. -- jat */
842
			if (decoder != nullptr && !found_replay_gain &&
Max Kellermann's avatar
Max Kellermann committed
843
			    lame.track_gain) {
844
				ReplayGainInfo rgi;
845
				rgi.Clear();
846 847
				rgi.tuples[REPLAY_GAIN_TRACK].gain = lame.track_gain;
				rgi.tuples[REPLAY_GAIN_TRACK].peak = lame.peak;
848
				decoder_replay_gain(*decoder, &rgi);
849 850
			}
		}
851
	}
Warren Dukes's avatar
Warren Dukes committed
852

853
	if (!max_frames)
Max Kellermann's avatar
Max Kellermann committed
854
		return false;
855

856
	if (max_frames > 8 * 1024 * 1024) {
857 858 859
		FormatWarning(mad_domain,
			      "mp3 file header indicates too many frames: %lu",
			      max_frames);
Max Kellermann's avatar
Max Kellermann committed
860
		return false;
861 862
	}

863 864
	frame_offsets = new long[max_frames];
	times = new mad_timer_t[max_frames];
Warren Dukes's avatar
Warren Dukes committed
865

Max Kellermann's avatar
Max Kellermann committed
866
	return true;
Warren Dukes's avatar
Warren Dukes committed
867 868
}

869
MadDecoder::~MadDecoder()
Avuton Olrich's avatar
Avuton Olrich committed
870
{
871 872 873
	mad_synth_finish(&synth);
	mad_frame_finish(&frame);
	mad_stream_finish(&stream);
Warren Dukes's avatar
Warren Dukes committed
874

875 876
	delete[] frame_offsets;
	delete[] times;
Warren Dukes's avatar
Warren Dukes committed
877 878 879
}

/* this is primarily used for getting total time for tags */
880
static int
881
mad_decoder_total_file_time(InputStream &is)
Avuton Olrich's avatar
Avuton Olrich committed
882
{
883 884 885 886
	MadDecoder data(nullptr, is);
	return data.DecodeFirstFrame(nullptr)
		? data.total_time + 0.5
		: -1;
Warren Dukes's avatar
Warren Dukes committed
887 888
}

889 890
long
MadDecoder::TimeToFrame(double t) const
891 892 893
{
	unsigned long i;

894
	for (i = 0; i < highest_frame; ++i) {
895
		double frame_time =
896
			mad_timer_count(times[i],
897 898 899 900 901 902 903 904
					MAD_UNITS_MILLISECONDS) / 1000.;
		if (frame_time >= t)
			break;
	}

	return i;
}

905 906
void
MadDecoder::UpdateTimerNextFrame()
Avuton Olrich's avatar
Avuton Olrich committed
907
{
908 909 910 911 912 913 914 915
	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;
916
		else
917
			highest_frame++;
918

919
		frame_offsets[current_frame] = ThisFrameOffset();
920

921 922
		mad_timer_add(&timer, frame.header.duration);
		times[current_frame] = timer;
923
	} else
924 925
		/* get the new timer value from "times" */
		timer = times[current_frame];
926

927 928
	current_frame++;
	elapsed_time = mad_timer_count(timer, MAD_UNITS_MILLISECONDS) / 1000.0;
929 930
}

931
DecoderCommand
932
MadDecoder::SendPCM(unsigned i, unsigned pcm_length)
933 934 935
{
	unsigned max_samples;

936 937 938
	max_samples = sizeof(output_buffer) /
		sizeof(output_buffer[0]) /
		MAD_NCHANNELS(&frame.header);
939 940 941 942 943 944 945 946

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

		i += num_samples;

947
		mad_fixed_to_24_buffer(output_buffer, &synth,
948
				       i - num_samples, i,
949 950
				       MAD_NCHANNELS(&frame.header));
		num_samples *= MAD_NCHANNELS(&frame.header);
951

952
		auto cmd = decoder_data(*decoder, input_stream, output_buffer,
953 954 955
					sizeof(output_buffer[0]) * num_samples,
					bit_rate / 1000);
		if (cmd != DecoderCommand::NONE)
956 957 958
			return cmd;
	}

959
	return DecoderCommand::NONE;
960 961
}

962
inline DecoderCommand
963
MadDecoder::SyncAndSend()
964
{
965 966 967 968 969 970 971 972 973
	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;
974 975
	}

976 977
	if (drop_start_frames > 0) {
		drop_start_frames--;
978
		return DecoderCommand::NONE;
979 980
	} else if ((drop_end_frames > 0) &&
		   (current_frame == (max_frames + 1 - drop_end_frames))) {
981 982
		/* stop decoding, effectively dropping all remaining
		   frames */
983
		return DecoderCommand::STOP;
984 985
	}

986 987 988 989 990
	unsigned i = 0;
	if (!decoded_first_frame) {
		i = drop_start_samples;
		decoded_first_frame = true;
	}
991

992 993 994 995
	unsigned pcm_length = synth.pcm.length;
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames)) {
		if (drop_end_samples >= pcm_length)
996 997
			pcm_length = 0;
		else
998
			pcm_length -= drop_end_samples;
999 1000
	}

1001 1002
	auto cmd = SendPCM(i, pcm_length);
	if (cmd != DecoderCommand::NONE)
1003 1004
		return cmd;

1005 1006
	if (drop_end_samples &&
	    (current_frame == max_frames - drop_end_frames))
1007 1008
		/* stop decoding, effectively dropping
		 * all remaining samples */
1009
		return DecoderCommand::STOP;
1010

1011
	return DecoderCommand::NONE;
1012 1013
}

1014 1015
inline bool
MadDecoder::Read()
1016
{
1017
	enum mp3_action ret;
1018

1019
	UpdateTimerNextFrame();
Warren Dukes's avatar
Warren Dukes committed
1020

1021
	switch (mute_frame) {
1022 1023
		DecoderCommand cmd;

Avuton Olrich's avatar
Avuton Olrich committed
1024
	case MUTEFRAME_SKIP:
1025
		mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
1026 1027
		break;
	case MUTEFRAME_SEEK:
1028 1029
		if (elapsed_time >= seek_where)
			mute_frame = MUTEFRAME_NONE;
Avuton Olrich's avatar
Avuton Olrich committed
1030
		break;
1031
	case MUTEFRAME_NONE:
1032
		cmd = SyncAndSend();
1033
		if (cmd == DecoderCommand::SEEK) {
1034
			unsigned long j;
1035

1036
			assert(input_stream.IsSeekable());
1037

1038
			j = TimeToFrame(decoder_seek_where(*decoder));
1039 1040 1041
			if (j < highest_frame) {
				if (Seek(frame_offsets[j])) {
					current_frame = j;
1042
					decoder_command_finished(*decoder);
Avuton Olrich's avatar
Avuton Olrich committed
1043
				} else
1044
					decoder_seek_error(*decoder);
Max Kellermann's avatar
Max Kellermann committed
1045
			} else {
1046
				seek_where = decoder_seek_where(*decoder);
1047
				mute_frame = MUTEFRAME_SEEK;
1048
				decoder_command_finished(*decoder);
Max Kellermann's avatar
Max Kellermann committed
1049
			}
1050
		} else if (cmd != DecoderCommand::NONE)
1051
			return false;
Warren Dukes's avatar
Warren Dukes committed
1052 1053
	}

Max Kellermann's avatar
Max Kellermann committed
1054
	while (true) {
1055 1056
		bool skip = false;

1057
		do {
Max Kellermann's avatar
Max Kellermann committed
1058
			Tag *tag = nullptr;
1059

1060
			ret = DecodeNextFrameHeader(&tag);
1061

1062
			if (tag != nullptr) {
1063
				decoder_tag(*decoder, input_stream,
1064
					    std::move(*tag));
Max Kellermann's avatar
Max Kellermann committed
1065
				delete tag;
1066
			}
1067 1068
		} while (ret == DECODE_CONT);
		if (ret == DECODE_BREAK)
1069
			return false;
Avuton Olrich's avatar
Avuton Olrich committed
1070
		else if (ret == DECODE_SKIP)
1071
			skip = true;
1072

1073
		if (mute_frame == MUTEFRAME_NONE) {
1074
			do {
1075
				ret = DecodeNextFrame();
1076 1077
			} while (ret == DECODE_CONT);
			if (ret == DECODE_BREAK)
1078
				return false;
Warren Dukes's avatar
Warren Dukes committed
1079
		}
1080

Avuton Olrich's avatar
Avuton Olrich committed
1081 1082
		if (!skip && ret == DECODE_OK)
			break;
Warren Dukes's avatar
Warren Dukes committed
1083
	}
Warren Dukes's avatar
Warren Dukes committed
1084

1085
	return ret != DECODE_BREAK;
Warren Dukes's avatar
Warren Dukes committed
1086 1087
}

1088
static void
1089
mp3_decode(Decoder &decoder, InputStream &input_stream)
Avuton Olrich's avatar
Avuton Olrich committed
1090
{
1091
	MadDecoder data(&decoder, input_stream);
1092

Max Kellermann's avatar
Max Kellermann committed
1093
	Tag *tag = nullptr;
1094
	if (!data.DecodeFirstFrame(&tag)) {
Max Kellermann's avatar
Max Kellermann committed
1095
		delete tag;
1096

1097
		if (decoder_get_command(decoder) == DecoderCommand::NONE)
1098
			LogError(mad_domain,
Max Kellermann's avatar
Max Kellermann committed
1099
				 "input/Input does not appear to be a mp3 bit stream");
1100
		return;
Warren Dukes's avatar
Warren Dukes committed
1101 1102
	}

1103
	Error error;
1104 1105
	AudioFormat audio_format;
	if (!audio_format_init_checked(audio_format,
1106
				       data.frame.header.samplerate,
1107
				       SampleFormat::S24_P32,
1108
				       MAD_NCHANNELS(&data.frame.header),
1109
				       error)) {
1110
		LogError(error);
Max Kellermann's avatar
Max Kellermann committed
1111
		delete tag;
1112 1113
		return;
	}
Avuton Olrich's avatar
Avuton Olrich committed
1114

1115
	decoder_initialized(decoder, audio_format,
1116
			    input_stream.IsSeekable(),
1117
			    data.total_time);
Warren Dukes's avatar
Warren Dukes committed
1118

1119
	if (tag != nullptr) {
1120
		decoder_tag(decoder, input_stream, std::move(*tag));
Max Kellermann's avatar
Max Kellermann committed
1121
		delete tag;
1122 1123
	}

1124
	while (data.Read()) {}
Warren Dukes's avatar
Warren Dukes committed
1125 1126
}

1127
static bool
1128
mad_decoder_scan_stream(InputStream &is,
1129
			const struct tag_handler *handler, void *handler_ctx)
Avuton Olrich's avatar
Avuton Olrich committed
1130
{
Max Kellermann's avatar
Max Kellermann committed
1131
	int total_time;
Warren Dukes's avatar
Warren Dukes committed
1132

1133 1134
	total_time = mad_decoder_total_file_time(is);
	if (total_time < 0)
1135
		return false;
Warren Dukes's avatar
Warren Dukes committed
1136

1137 1138
	tag_handler_invoke_duration(handler, handler_ctx, total_time);
	return true;
Warren Dukes's avatar
Warren Dukes committed
1139 1140
}

1141 1142
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
1143

1144
const struct DecoderPlugin mad_decoder_plugin = {
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	"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
1155
};