1 /*
2  *  Squeezelite - lightweight headless squeezebox emulator
3  *
4  *  (c) Adrian Smith 2012-2015, triode1@btinternet.com
5  *      Ralph Irving 2015-2017, ralph_irving@hotmail.com
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21 
22 #include "squeezelite.h"
23 
24 #include <mad.h>
25 
26 #define MAD_DELAY 529
27 
28 #define READBUF_SIZE 2048 // local buffer used by decoder: FIXME merge with any other decoders needing one?
29 
30 struct mad {
31 	u8_t *readbuf;
32 	unsigned readbuf_len;
33 	struct mad_stream stream;
34 	struct mad_frame frame;
35 	struct mad_synth synth;
36 	enum mad_error last_error;
37 	// for lame gapless processing
38 	int checktags;
39 	u32_t consume;
40 	u32_t skip;
41 	u64_t samples;
42 	u32_t padding;
43 #if !LINKALL
44 	// mad symbols to be dynamically loaded
45 	void (* mad_stream_init)(struct mad_stream *);
46 	void (* mad_frame_init)(struct mad_frame *);
47 	void (* mad_synth_init)(struct mad_synth *);
48 	void (* mad_frame_finish)(struct mad_frame *);
49 	void (* mad_stream_finish)(struct mad_stream *);
50 	void (* mad_stream_buffer)(struct mad_stream *, unsigned char const *, unsigned long);
51 	int  (* mad_frame_decode)(struct mad_frame *, struct mad_stream *);
52 	void (* mad_synth_frame)(struct mad_synth *, struct mad_frame const *);
53 	char const *(* mad_stream_errorstr)(struct mad_stream const *);
54 #endif
55 };
56 
57 static struct mad *m;
58 
59 extern log_level loglevel;
60 
61 extern struct buffer *streambuf;
62 extern struct buffer *outputbuf;
63 extern struct streamstate stream;
64 extern struct outputstate output;
65 extern struct decodestate decode;
66 extern struct processstate process;
67 
68 #define LOCK_S   mutex_lock(streambuf->mutex)
69 #define UNLOCK_S mutex_unlock(streambuf->mutex)
70 #define LOCK_O   mutex_lock(outputbuf->mutex)
71 #define UNLOCK_O mutex_unlock(outputbuf->mutex)
72 #if PROCESS
73 #define LOCK_O_direct   if (decode.direct) mutex_lock(outputbuf->mutex)
74 #define UNLOCK_O_direct if (decode.direct) mutex_unlock(outputbuf->mutex)
75 #define IF_DIRECT(x)    if (decode.direct) { x }
76 #define IF_PROCESS(x)   if (!decode.direct) { x }
77 #else
78 #define LOCK_O_direct   mutex_lock(outputbuf->mutex)
79 #define UNLOCK_O_direct mutex_unlock(outputbuf->mutex)
80 #define IF_DIRECT(x)    { x }
81 #define IF_PROCESS(x)
82 #endif
83 
84 #if LINKALL
85 #define MAD(h, fn, ...) (mad_ ## fn)(__VA_ARGS__)
86 #else
87 #define MAD(h, fn, ...) (h)->mad_##fn(__VA_ARGS__)
88 #endif
89 
90 // based on libmad minimad.c scale
scale(mad_fixed_t sample)91 static inline ISAMPLE_T scale(mad_fixed_t sample) {
92 	sample += (1L << (MAD_F_FRACBITS - 24));
93 
94 	if (sample >= MAD_F_ONE)
95 		sample = MAD_F_ONE - 1;
96 	else if (sample < -MAD_F_ONE)
97 		sample = -MAD_F_ONE;
98 #if BYTES_PER_FRAME == 4
99 	return (ISAMPLE_T)((sample >> (MAD_F_FRACBITS + 1 - 24)) >> 8);
100 #else
101 	return (ISAMPLE_T)((sample >> (MAD_F_FRACBITS + 1 - 24)) << 8);
102 #endif
103 }
104 
105 // check for id3.2 tag at start of file - http://id3.org/id3v2.4.0-structure, return length
_check_id3_tag(size_t bytes)106 static unsigned _check_id3_tag(size_t bytes) {
107 	u8_t *ptr = streambuf->readp;
108 	u32_t size = 0;
109 
110 	if (bytes > 10 && *ptr == 'I' && *(ptr+1) == 'D' && *(ptr+2) == '3') {
111 		// size is encoded as syncsafe integer, add 10 if footer present
112 		if (*(ptr+6) < 0x80 && *(ptr+7) < 0x80 && *(ptr+8) < 0x80 && *(ptr+9) < 0x80) {
113 			size = 10 + (*(ptr+6) << 21) + (*(ptr+7) << 14) + (*(ptr+8) << 7) + *(ptr+9) + ((*(ptr+5) & 0x10) ? 10 : 0);
114 			LOG_DEBUG("id3.2 tag len: %u", size);
115 		}
116 	}
117 
118 	return size;
119 }
120 
121 // check for lame gapless params, don't advance streambuf
_check_lame_header(size_t bytes)122 static void _check_lame_header(size_t bytes) {
123 	u8_t *ptr = streambuf->readp;
124 
125 	if (*ptr == 0xff && (*(ptr+1) & 0xf0) == 0xf0 && bytes > 180) {
126 
127 		u32_t frame_count = 0, enc_delay = 0, enc_padding = 0;
128 		u8_t flags;
129 
130 		// 2 channels
131 		if (!memcmp(ptr + 36, "Xing", 4) || !memcmp(ptr + 36, "Info", 4)) {
132 			ptr += 36 + 7;
133 		// mono
134 		} else if (!memcmp(ptr + 21, "Xing", 4) || !memcmp(ptr + 21, "Info", 4)) {
135 			ptr += 21 + 7;
136 		}
137 
138 		flags = *ptr;
139 
140 		if (flags & 0x01) {
141 			frame_count = unpackN((u32_t *)(ptr + 1));
142 			ptr += 4;
143 		}
144 		if (flags & 0x02) ptr += 4;
145 		if (flags & 0x04) ptr += 100;
146 		if (flags & 0x08) ptr += 4;
147 
148 		if (!!memcmp(ptr+1, "LAME", 4)) {
149 			return;
150 		}
151 
152 		ptr += 22;
153 
154 		enc_delay   = (*ptr << 4 | *(ptr + 1) >> 4) + MAD_DELAY;
155 		enc_padding = (*(ptr + 1) & 0xF) << 8 | *(ptr + 2);
156 		enc_padding = enc_padding > MAD_DELAY ? enc_padding - MAD_DELAY : 0;
157 
158 		// add one frame to initial skip for this (empty) frame
159 		m->skip    = enc_delay + 1152;
160 		m->samples = frame_count * 1152 - enc_delay - enc_padding;
161 		m->padding = enc_padding;
162 
163 		LOG_INFO("gapless: skip: %u samples: " FMT_u64 " delay: %u padding: %u", m->skip, m->samples, enc_delay, enc_padding);
164 	}
165 }
166 
mad_decode(void)167 static decode_state mad_decode(void) {
168 	size_t bytes;
169 	bool eos = false;
170 
171 	LOCK_S;
172 	bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
173 
174 	if (m->checktags) {
175 		if (m->checktags == 1) {
176 			m->consume = _check_id3_tag(bytes);
177 			m->checktags = 2;
178 		}
179 		if (m->consume) {
180 			u32_t consume = min(m->consume, bytes);
181 			LOG_DEBUG("consume: %u of %u", consume, m->consume);
182 			_buf_inc_readp(streambuf, consume);
183 			m->consume -= consume;
184 			UNLOCK_S;
185 			return DECODE_RUNNING;
186 		}
187 		if (m->checktags == 2) {
188 			if (!stream.meta_interval) {
189 				_check_lame_header(bytes);
190 			}
191 			m->checktags = 0;
192 		}
193 	}
194 
195 	if (m->stream.next_frame && m->readbuf_len) {
196 		m->readbuf_len -= m->stream.next_frame - m->readbuf;
197 		memmove(m->readbuf, m->stream.next_frame, m->readbuf_len);
198 	}
199 
200 	bytes = min(bytes, READBUF_SIZE - m->readbuf_len);
201 	memcpy(m->readbuf + m->readbuf_len, streambuf->readp, bytes);
202 	m->readbuf_len += bytes;
203 	_buf_inc_readp(streambuf, bytes);
204 
205 	if (stream.state <= DISCONNECT && _buf_used(streambuf) == 0) {
206 		eos = true;
207 		LOG_DEBUG("end of stream");
208 		memset(m->readbuf + m->readbuf_len, 0, MAD_BUFFER_GUARD);
209 		m->readbuf_len += MAD_BUFFER_GUARD;
210 	}
211 
212 	UNLOCK_S;
213 
214 	MAD(m, stream_buffer, &m->stream, m->readbuf, m->readbuf_len);
215 
216 	while (true) {
217 		size_t frames;
218 		s32_t *iptrl;
219 		s32_t *iptrr;
220 		unsigned max_frames;
221 
222 		if (MAD(m, frame_decode, &m->frame, &m->stream) == -1) {
223 			decode_state ret;
224 			if (!eos && m->stream.error == MAD_ERROR_BUFLEN) {
225 				ret = DECODE_RUNNING;
226 			} else if (eos && (m->stream.error == MAD_ERROR_BUFLEN || m->stream.error == MAD_ERROR_LOSTSYNC
227 					|| m->stream.error == MAD_ERROR_BADBITRATE)) {
228 				ret = DECODE_COMPLETE;
229 			} else if (!MAD_RECOVERABLE(m->stream.error)) {
230 				LOG_INFO("mad_frame_decode error: %s - stopping decoder", MAD(m, stream_errorstr, &m->stream));
231 				ret = DECODE_COMPLETE;
232 			} else {
233 				if (m->stream.error != m->last_error) {
234 					// suppress repeat error messages
235 					LOG_DEBUG("mad_frame_decode error: %s", MAD(m, stream_errorstr, &m->stream));
236 				}
237 				ret = DECODE_RUNNING;
238 			}
239 			m->last_error = m->stream.error;
240 			return ret;
241 		};
242 
243 		MAD(m, synth_frame, &m->synth, &m->frame);
244 
245 		if (decode.new_stream) {
246 			LOCK_O;
247 			LOG_INFO("setting track_start");
248 			output.next_sample_rate = decode_newstream(m->synth.pcm.samplerate, output.supported_rates);
249 			IF_DSD(	output.next_fmt = PCM; )
250 			output.track_start = outputbuf->writep;
251 			if (output.fade_mode) _checkfade(true);
252 			decode.new_stream = false;
253 			UNLOCK_O;
254 		}
255 
256 		LOCK_O_direct;
257 
258 		IF_DIRECT(
259 			max_frames = _buf_space(outputbuf) / BYTES_PER_FRAME;
260 		);
261 		IF_PROCESS(
262 			max_frames = process.max_in_frames - process.in_frames;
263 		);
264 
265 		if (m->synth.pcm.length > max_frames) {
266 			LOG_WARN("too many samples - dropping samples");
267 			m->synth.pcm.length = max_frames;
268 		}
269 
270 		frames = m->synth.pcm.length;
271 		iptrl = m->synth.pcm.samples[0];
272 		iptrr = m->synth.pcm.samples[ m->synth.pcm.channels - 1 ];
273 
274 		if (m->skip) {
275 			u32_t skip = min(m->skip, frames);
276 			LOG_DEBUG("gapless: skipping %u frames at start", skip);
277 			frames -= skip;
278 			m->skip -= skip;
279 			iptrl += skip;
280 			iptrr += skip;
281 		}
282 
283 		if (m->samples) {
284 			if (m->samples < frames) {
285 				LOG_DEBUG("gapless: trimming %u frames from end", frames - m->samples);
286 				frames = (size_t)m->samples;
287 			}
288 			m->samples -= frames;
289 			if (m->samples > 0 && eos && !(m->stream.next_frame[0] == 0xff && (m->stream.next_frame[1] & 0xf0) == 0xf0)) {
290 				// this is the last frame to be decoded, but more samples expected so we must have skipped, remove padding
291 				// note this only works if the padding is less than one frame of 1152 bytes otherswise some gap will remain
292 				LOG_DEBUG("gapless: early end - trimming padding from end");
293 				if (frames >= m->padding) {
294 					frames -= m->padding;
295 				} else {
296 					frames = 0;
297 				}
298 				m->samples = 0;
299 			}
300 		}
301 
302 		LOG_SDEBUG("write %u frames", frames);
303 
304 		while (frames > 0) {
305 			size_t f, count;
306 			ISAMPLE_T *optr;
307 
308 			IF_DIRECT(
309 				f = min(frames, _buf_cont_write(outputbuf) / BYTES_PER_FRAME);
310 				optr = (ISAMPLE_T *)outputbuf->writep;
311 			);
312 			IF_PROCESS(
313 				f = min(frames, process.max_in_frames - process.in_frames);
314 				optr = (ISAMPLE_T *)((u8_t *)process.inbuf + process.in_frames * BYTES_PER_FRAME);
315 			);
316 
317 			count = f;
318 
319 			while (count--) {
320 				*optr++ = scale(*iptrl++);
321 				*optr++ = scale(*iptrr++);
322 			}
323 
324 			frames -= f;
325 
326 			IF_DIRECT(
327 				_buf_inc_writep(outputbuf, f * BYTES_PER_FRAME);
328 			);
329 			IF_PROCESS(
330 				process.in_frames += f;
331 			);
332 		}
333 
334 		UNLOCK_O_direct;
335 	}
336 
337 	return eos ? DECODE_COMPLETE : DECODE_RUNNING;
338 }
339 
mad_open(u8_t size,u8_t rate,u8_t chan,u8_t endianness)340 static void mad_open(u8_t size, u8_t rate, u8_t chan, u8_t endianness) {
341 	if (!m->readbuf) {
342 		m->readbuf = malloc(READBUF_SIZE + MAD_BUFFER_GUARD);
343 	}
344 	m->checktags = 1;
345 	m->consume = 0;
346 	m->skip = MAD_DELAY;
347 	m->samples = 0;
348 	m->readbuf_len = 0;
349 	m->last_error = MAD_ERROR_NONE;
350 	MAD(m, stream_init, &m->stream);
351 	MAD(m, frame_init, &m->frame);
352 	MAD(m, synth_init, &m->synth);
353 }
354 
mad_close(void)355 static void mad_close(void) {
356 	mad_synth_finish(&m->synth); // macro only in current version
357 	MAD(m, frame_finish, &m->frame);
358 	MAD(m, stream_finish, &m->stream);
359 	free(m->readbuf);
360 	m->readbuf = NULL;
361 }
362 
load_mad()363 static bool load_mad() {
364 #if !LINKALL
365 	void *handle = dlopen(LIBMAD, RTLD_NOW);
366 	char *err;
367 
368 	if (!handle) {
369 		LOG_INFO("dlerror: %s", dlerror());
370 		return false;
371 	}
372 
373 	m->mad_stream_init = dlsym(handle, "mad_stream_init");
374 	m->mad_frame_init = dlsym(handle, "mad_frame_init");
375 	m->mad_synth_init = dlsym(handle, "mad_synth_init");
376 	m->mad_frame_finish = dlsym(handle, "mad_frame_finish");
377 	m->mad_stream_finish = dlsym(handle, "mad_stream_finish");
378 	m->mad_stream_buffer = dlsym(handle, "mad_stream_buffer");
379 	m->mad_frame_decode = dlsym(handle, "mad_frame_decode");
380 	m->mad_synth_frame = dlsym(handle, "mad_synth_frame");
381 	m->mad_stream_errorstr = dlsym(handle, "mad_stream_errorstr");
382 
383 	if ((err = dlerror()) != NULL) {
384 		LOG_INFO("dlerror: %s", err);
385 		return false;
386 	}
387 
388 	LOG_INFO("loaded "LIBMAD);
389 #endif
390 
391 	return true;
392 }
393 
register_mad(void)394 struct codec *register_mad(void) {
395 	static struct codec ret = {
396 		'm',          // id
397 		"mp3",        // types
398 		READBUF_SIZE, // min read
399 		206800,       // min space
400 		mad_open,     // open
401 		mad_close,    // close
402 		mad_decode,   // decode
403 	};
404 
405 	m = malloc(sizeof(struct mad));
406 	if (!m) {
407 		return NULL;
408 	}
409 
410 	m->readbuf = NULL;
411 	m->readbuf_len = 0;
412 
413 	if (!load_mad()) {
414 		return NULL;
415 	}
416 
417 	LOG_INFO("using mad to decode mp3");
418 	return &ret;
419 }
420