1 /*
2  * Copyright 2008-2013 Various Authors
3  * Copyright 2004-2005 Timo Hirvonen
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 /*
20  * Gapless decoding added by Chun-Yu Shei <cshei AT cs.indiana.edu>
21  */
22 
23 /*
24  * Xing code copied from xmms-mad plugin.
25  * Lame code copied from mpd
26  */
27 
28 #include "nomad.h"
29 #include "id3.h"
30 #include "misc.h"
31 
32 #include <mad.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <string.h>
37 #include <errno.h>
38 
39 #ifndef WIN32
40 #include <unistd.h>
41 #include <limits.h>
42 #endif
43 
44 #define INPUT_BUFFER_SIZE	(5 * 8192)
45 #define SEEK_IDX_INTERVAL	15
46 
47 /* the number of samples of silence the decoder inserts at start */
48 #define DECODERDELAY		529
49 
50 #define XING_MAGIC (('X' << 24) | ('i' << 16) | ('n' << 8) | 'g')
51 #define INFO_MAGIC (('I' << 24) | ('n' << 16) | ('f' << 8) | 'o')
52 
53 #define xnew(type, n)			(type *)xmalloc(sizeof(type) * (n))
54 #define xrenew(type, mem, n)	(type *)xrealloc(mem, sizeof(type) * (n))
55 
56 # define mad_f_tofloat(x) \
57     ((float) ((x) / (float) (1L << MAD_F_FRACBITS)))
58 
xrealloc(void * ptr,size_t size)59 static inline void * xrealloc(void *ptr, size_t size)
60 {
61     return realloc(ptr, size);
62 }
63 
xmalloc(size_t size)64 static inline void * xmalloc(size_t size)
65 {
66     return malloc(size);
67 }
68 
69 struct seek_idx_entry {
70 	off_t offset;
71 	mad_timer_t timer;
72 };
73 
74 struct nomad {
75 	struct mad_stream stream;
76 	struct mad_frame frame;
77 	struct mad_synth synth;
78 	mad_timer_t timer;
79 	unsigned long cur_frame;
80 	off_t input_offset;
81 	/* MAD_BUFFER_GUARD zeros are required at the end of the stream to decode the last frame
82 	   ref: http://www.mars.org/mailman/public/mad-dev/2001-May/000262.html */
83 	unsigned char input_buffer[INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
84 	int i;
85 	unsigned int has_xing : 1;
86 	unsigned int has_lame : 1;
87 	unsigned int seen_first_frame : 1;
88 	unsigned int readEOF : 1;
89 	int start_drop_frames;
90 	int start_drop_samples;
91 	int end_drop_samples;
92 	int end_drop_frames;
93 
94 	struct nomad_xing xing;
95 	struct nomad_lame lame;
96 
97 	struct {
98 		int size;
99 		struct seek_idx_entry *table;
100 	} seek_idx;
101 
102 	struct {
103 		unsigned long long int bitrate_sum;
104 		unsigned long nr_frames;
105 	} current;
106 
107 	struct nomad_info info;
108 	void *datasource;
109 	int datasource_fd;
110 	struct nomad_callbacks cbs;
111 };
112 
scale(mad_fixed_t sample)113 static inline int scale(mad_fixed_t sample)
114 {
115 	sample += 1L << (MAD_F_FRACBITS - 16);
116 	if (sample >= MAD_F_ONE) {
117 		sample = MAD_F_ONE - 1;
118 	} else if (sample < -MAD_F_ONE) {
119 		sample = -MAD_F_ONE;
120 	}
121 	return sample >> (MAD_F_FRACBITS - 15);
122 }
123 
timer_to_seconds(mad_timer_t timer)124 static inline double timer_to_seconds(mad_timer_t timer)
125 {
126 	signed long ms;
127 
128 	ms = mad_timer_count(timer, MAD_UNITS_MILLISECONDS);
129 	return (double)ms / 1000.0;
130 }
131 
parse_lame(struct nomad * nomad,struct mad_bitptr ptr,int bitlen)132 static int parse_lame(struct nomad *nomad, struct mad_bitptr ptr, int bitlen)
133 {
134 	int i, adj = 0;
135 	unsigned int version_major, version_minor;
136 	float val;
137 
138 	/* Unlike the xing header, the lame tag has a fixed length.  Fail if
139 	 * not all 36 bytes (288 bits) are there. */
140 	if (bitlen < 288) return 0;
141 
142 	for (i = 0; i < 9; i++) nomad->lame.encoder[i] = (char)mad_bit_read(&ptr, 8);
143 	nomad->lame.encoder[9] = '\0';
144 
145 	/* This is technically incorrect, since the encoder might not be lame.
146 	 * But there's no other way to determine if this is a lame tag, and we
147 	 * wouldn't want to go reading a tag that's not there. */
148 	if (strncmp(nomad->lame.encoder, "LAME", 4) != 0) return 0;
149 
150 	if (sscanf(nomad->lame.encoder + 4, "%u.%u", &version_major, &version_minor) != 2)
151 		return 0;
152 
153 #if defined(DEBUG_LAME)
154 	d_print("detected LAME version %s\n", nomad->lame.encoder + 4);
155 #endif
156 
157 	i = mad_bit_read(&ptr, 4);
158 #if defined(DEBUG_LAME)
159 	d_print("LAME tag revision: %d\n", i);
160 #endif
161 	nomad->lame.vbr_method = mad_bit_read(&ptr, 4);
162 
163 	/* ReplayGain in LAME tag was added in 3.94 */
164 	if (version_major > 3 || (version_major == 3 && version_minor >= 94)) {
165 		/* lowpass */
166 		mad_bit_read(&ptr, 8);
167 
168 		/* The reference volume was changed from the 83dB used in the
169 		 * ReplayGain spec to 89dB in lame 3.95.1.  Bump the gain for older
170 		 * versions, since everyone else uses 89dB instead of 83dB.
171 		 * Unfortunately, lame didn't differentiate between 3.95 and 3.95.1, so
172 		 * it's impossible to make the proper adjustment for 3.95.
173 		 * Fortunately, 3.95 was only out for about a day before 3.95.1 was
174 		 * released. -- tmz */
175 		if (version_major < 3 || (version_major == 3 && version_minor < 95))
176 			adj = 6;
177 
178 		val = mad_bit_read(&ptr, 32) / (float) (1 << 23);
179 		/* peak value of 0.0 means lame didn't calculate the peak at all
180 		 * (--replaygain-fast), even silence has a value > 0.0 */
181 		if (val)
182 			nomad->lame.peak = val;
183 		for (i = 0; i < 2; i++) {
184 			int gain, gain_type;
185 			gain_type = replaygain_decode(mad_bit_read(&ptr, 16), &gain);
186 			val = gain / 10.f + adj;
187 			if (gain_type == 1)
188 				nomad->lame.trackGain = val;
189 			/* LAME currently doesn't store any album gain!
190 			else if (gain_type == 2)
191 				nomad->lame.albumGain = val;
192 			*/
193 		}
194 
195 		/*
196 		 * 4 encoding flags
197 		 * 4 ATH type
198 		 * 8 minimal bitrate (if ABR -> specified bitrate)
199 		 */
200 		mad_bit_read(&ptr, 16);
201 	} else
202 		mad_bit_read(&ptr, 88);
203 
204 	nomad->lame.encoderDelay = mad_bit_read(&ptr, 12);
205 	nomad->lame.encoderPadding = mad_bit_read(&ptr, 12);
206 #if defined(DEBUG_LAME)
207 	if (adj > 0)
208 		d_print("adjusted gains by %+d dB (old LAME)\n", adj);
209 	if (!isnan(nomad->lame.peak))
210 		d_print("peak: %f\n", nomad->lame.peak);
211 	if (!isnan(nomad->lame.trackGain))
212 		d_print("trackGain: %+.1f dB\n", nomad->lame.trackGain);
213 	if (!isnan(nomad->lame.albumGain))
214 		d_print("albumGain: %+.1f dB\n", nomad->lame.albumGain);
215 	d_print("encoderDelay: %d, encoderPadding: %d\n", nomad->lame.encoderDelay, nomad->lame.encoderPadding);
216 #endif
217 
218 	mad_bit_read(&ptr, 96);
219 
220 	nomad->start_drop_frames = 1;	/* XING/LAME header is an empty frame */
221 	nomad->start_drop_samples = nomad->lame.encoderDelay + DECODERDELAY;
222 	nomad->end_drop_samples = nomad->lame.encoderPadding - DECODERDELAY;
223 
224 	nomad->has_lame = 1;
225 
226 	return 1;
227 }
228 
229 /*
230  * format:
231  *
232  *   4 "Xing"
233  *   4 flags
234  *   4 frames (optional)
235  *   4 bytes  (optional)
236  * 100 TOC    (optional)
237  *   4 scale  (optional)
238  */
xing_parse(struct nomad * nomad)239 static int xing_parse(struct nomad *nomad)
240 {
241 	struct mad_bitptr ptr = nomad->stream.anc_ptr;
242 	struct mad_bitptr start = ptr;
243 	int oldbitlen = nomad->stream.anc_bitlen;
244 	int bitlen = nomad->stream.anc_bitlen;
245 	int bitsleft;
246 	unsigned xing_id;
247 
248 	nomad->has_xing = 0;
249 	nomad->has_lame = 0;
250 	if (bitlen < 64)
251 		return -1;
252 	xing_id = mad_bit_read(&ptr, 32);
253 	if (xing_id != XING_MAGIC && xing_id != INFO_MAGIC) {
254 		/*
255 		 * Due to an unfortunate historical accident, a Xing VBR tag
256 		 * may be misplaced in a stream with CRC protection. We check
257 		 * for this by assuming the tag began two octets prior and the
258 		 * high bits of the following flags field are always zero.
259 		 */
260 		if (xing_id != (((XING_MAGIC+0UL) << 16) & 0xffffffffL) &&
261 				xing_id != (((INFO_MAGIC+0UL) << 16) & 0xffffffffL))
262 			return -1;
263 		xing_id >>= 16;
264 		ptr = start;
265 		mad_bit_skip(&ptr, 16);
266 		bitlen += 16;
267 	}
268 	nomad->xing.is_info = ((xing_id & 0x0000ffffL) == (INFO_MAGIC & 0x0000ffffL));
269 	nomad->xing.flags = mad_bit_read(&ptr, 32);
270 	bitlen -= 64;
271 	if (nomad->xing.flags & XING_FRAMES) {
272 		if (bitlen < 32)
273 			return -1;
274 		nomad->xing.nr_frames = mad_bit_read(&ptr, 32);
275 		bitlen -= 32;
276 	}
277 	if (nomad->xing.flags & XING_BYTES) {
278 		if (bitlen < 32)
279 			return -1;
280 		nomad->xing.bytes = mad_bit_read(&ptr, 32);
281 		bitlen -= 32;
282 	}
283 	if (nomad->xing.flags & XING_TOC) {
284 		int i;
285 
286 		if (bitlen < 800)
287 			return -1;
288 		for (i = 0; i < 100; i++)
289 			nomad->xing.toc[i] = mad_bit_read(&ptr, 8);
290 		bitlen -= 800;
291 	}
292 	if (nomad->xing.flags & XING_SCALE) {
293 		if (bitlen < 32)
294 			return -1;
295 		nomad->xing.scale = mad_bit_read(&ptr, 32);
296 		bitlen -= 32;
297 	}
298 
299 	/* Make sure we consume no less than 120 bytes (960 bits) in hopes that
300 	 * the LAME tag is found there, and not right after the Xing header */
301 	bitsleft = 960 - (oldbitlen - bitlen);
302 	if (bitsleft < 0) return -1;
303 	else if (bitsleft > 0) {
304 		mad_bit_read(&ptr, bitsleft);
305 		bitlen -= bitsleft;
306 	}
307 
308 	nomad->has_xing = 1;
309 #if defined(DEBUG_XING)
310 	if (nomad->xing.flags & XING_FRAMES)
311 		d_print("frames: %d (xing)\n", nomad->xing.nr_frames);
312 #endif
313 
314 	parse_lame(nomad, ptr, bitlen);
315 
316 	return 0;
317 }
318 
319 /*
320  * returns:
321  *    0: eof
322  *   -1: error
323  *   >0: ok
324  */
fill_buffer(struct nomad * nomad)325 static int fill_buffer(struct nomad *nomad)
326 {
327 	if (nomad->stream.buffer == NULL || nomad->stream.error == MAD_ERROR_BUFLEN) {
328 		ssize_t read_size, remaining, len;
329 		unsigned char *read_start;
330 
331 		if (nomad->stream.next_frame != NULL) {
332 			remaining = nomad->stream.bufend - nomad->stream.next_frame;
333 			memmove(nomad->input_buffer, nomad->stream.next_frame, remaining);
334 			read_start = nomad->input_buffer + remaining;
335 			read_size = INPUT_BUFFER_SIZE - remaining;
336 		} else {
337 			read_size = INPUT_BUFFER_SIZE;
338 			read_start = nomad->input_buffer;
339 			remaining = 0;
340 		}
341 		read_size = nomad->cbs.read(nomad->datasource, read_start, read_size);
342 		if (read_size == -1) {
343 			if (errno != EAGAIN)
344 				d_print("read error on bitstream (%d:%s)\n", errno, strerror(errno));
345 			return -1;
346 		}
347 		if (read_size == 0) {
348 			if (!nomad->readEOF) {
349 				memset(nomad->input_buffer + remaining, 0, MAD_BUFFER_GUARD);
350 				remaining += MAD_BUFFER_GUARD;
351 				d_print("hit end of stream, appended MAD_BUFFER_GUARD zeros\n");
352 				nomad->readEOF = 1;
353 			}
354 			else return 0;
355 		}
356 
357 		len = read_size + remaining;
358 
359 		nomad->input_offset += read_size;
360 
361 		mad_stream_buffer(&nomad->stream, nomad->input_buffer, len);
362 		nomad->stream.error = 0;
363 	}
364 	return 1;
365 }
366 
handle_lost_sync(struct nomad * nomad)367 static void handle_lost_sync(struct nomad *nomad)
368 {
369 	unsigned long frame;
370 	int size;
371 
372 	frame = nomad->cur_frame;
373 	if (frame == 0) {
374 		/* cur_frame is not set when scanning file */
375 		frame = nomad->info.nr_frames;
376 	}
377 
378 	size = id3_tag_size((const char *)nomad->stream.this_frame,
379 			nomad->stream.bufend - nomad->stream.this_frame);
380 	if (size > 0) {
381 		d_print("frame %ld, skipping ID3 tag (%d bytes)\n", frame, size);
382 		mad_stream_skip(&nomad->stream, size);
383 	} else {
384 		d_print("frame %ld\n", frame);
385 	}
386 }
387 
388 
389 /* Builds a seek index as the file is decoded
390  * NOTE: increases nomad->timer (current position)
391  */
build_seek_index(struct nomad * nomad)392 static void build_seek_index(struct nomad *nomad)
393 {
394 	mad_timer_t timer_now = nomad->timer;
395 	off_t offset;
396 	int idx;
397 
398 	mad_timer_add(&nomad->timer, nomad->frame.header.duration);
399 
400 	if (nomad->has_xing)
401 		return;
402 
403 	if (nomad->timer.seconds < (nomad->seek_idx.size + 1) * SEEK_IDX_INTERVAL)
404 		return;
405 
406 	/* offset = ftell() */
407 	offset = nomad->input_offset;
408 	/* subtract by buffer length to get offset to start of buffer */
409 	offset -= (nomad->stream.bufend - nomad->input_buffer);
410 	/* then add offset to the current frame */
411 	offset += (nomad->stream.this_frame - nomad->input_buffer);
412 
413 	idx = nomad->seek_idx.size;
414 
415 	nomad->seek_idx.table = xrenew(struct seek_idx_entry, nomad->seek_idx.table, idx + 1);
416 	nomad->seek_idx.table[idx].offset = offset;
417 	nomad->seek_idx.table[idx].timer = timer_now;
418 
419 	nomad->seek_idx.size++;
420 }
421 
calc_frames_fast(struct nomad * nomad)422 static void calc_frames_fast(struct nomad *nomad)
423 {
424 	if (nomad->has_xing && (nomad->xing.flags & XING_FRAMES) && nomad->xing.nr_frames) {
425 		nomad->info.nr_frames = nomad->xing.nr_frames;
426 		mad_timer_multiply(&nomad->timer, nomad->info.nr_frames);
427 	} else {
428 		nomad->info.nr_frames = nomad->info.filesize /
429 			(nomad->stream.next_frame - nomad->stream.this_frame);
430 		mad_timer_multiply(&nomad->timer, nomad->info.nr_frames);
431 	}
432 }
433 
calc_bitrate_fast(struct nomad * nomad)434 static void calc_bitrate_fast(struct nomad *nomad)
435 {
436 	nomad->info.vbr = nomad->has_xing ? !nomad->xing.is_info : 0;
437 
438 	if (nomad->has_lame && nomad->lame.vbr_method == 1)
439 		nomad->info.vbr = 0;
440 
441 	if (nomad->has_xing && (nomad->xing.flags & XING_BYTES) && nomad->xing.bytes)
442 		nomad->info.avg_bitrate = (nomad->xing.bytes * 8.0) / nomad->info.duration;
443 	else
444 		nomad->info.avg_bitrate = nomad->frame.header.bitrate;
445 }
446 
447 /*
448  * fields
449  *     nomad->info.avg_bitrate and
450  *     nomad->info.vbr
451  * are only estimated
452  */
scan(struct nomad * nomad)453 static int scan(struct nomad *nomad)
454 {
455 	struct mad_header *header = &nomad->frame.header;
456 
457 	while (1) {
458 		int rc;
459 
460 		rc = fill_buffer(nomad);
461 		if (rc == -1)
462 			return -1;
463 		if (rc == 0)
464 			break;
465 
466 		if (mad_frame_decode(&nomad->frame, &nomad->stream) == -1) {
467 			if (nomad->stream.error == MAD_ERROR_BUFLEN)
468 				continue;
469 			if (!MAD_RECOVERABLE(nomad->stream.error)) {
470 				d_print("unrecoverable frame level error.\n");
471 				return -1;
472 			}
473 			if (nomad->stream.error == MAD_ERROR_LOSTSYNC)
474 				handle_lost_sync(nomad);
475 			continue;
476 		}
477 
478 		build_seek_index(nomad);
479 
480 		// first valid frame
481 		nomad->info.sample_rate = header->samplerate;
482 		nomad->info.channels = MAD_NCHANNELS(header);
483 		nomad->info.layer = header->layer;
484 		nomad->info.dual_channel = header->mode == MAD_MODE_DUAL_CHANNEL;
485 		nomad->info.joint_stereo = header->mode == MAD_MODE_JOINT_STEREO;
486 
487 		xing_parse(nomad);
488 		calc_frames_fast(nomad);
489 		break;
490 	}
491 	if (nomad->info.nr_frames == 0) {
492 		d_print("error: not an mp3 file!\n");
493 		return -NOMAD_ERROR_FILE_FORMAT;
494 	}
495 	nomad->info.duration = timer_to_seconds(nomad->timer);
496 	calc_bitrate_fast(nomad);
497 	nomad->cur_frame = 0;
498 	nomad->cbs.lseek(nomad->datasource, 0, SEEK_SET);
499 	nomad->input_offset = 0;
500 	return 0;
501 }
502 
decode(struct nomad * nomad)503 static int decode(struct nomad *nomad)
504 {
505 	int rc;
506 
507 start:
508 	rc = fill_buffer(nomad);
509 	if (rc == -1)
510 		return -1;
511 	if (rc == 0)
512 		return 1;
513 
514 	if (mad_frame_decode(&nomad->frame, &nomad->stream)) {
515 		if (nomad->stream.error == MAD_ERROR_BUFLEN)
516 			goto start;
517 		if (!MAD_RECOVERABLE(nomad->stream.error)) {
518 			d_print("unrecoverable frame level error.\n");
519 			return -1;
520 		}
521 		if (nomad->stream.error == MAD_ERROR_LOSTSYNC)
522 			handle_lost_sync(nomad);
523 		goto start;
524 	}
525 	nomad->cur_frame++;
526 	nomad->current.bitrate_sum += nomad->frame.header.bitrate;
527 	nomad->current.nr_frames++;
528 	if (nomad->info.filesize != -1) {
529 		build_seek_index(nomad);
530 	} else {
531 		mad_timer_add(&nomad->timer, nomad->frame.header.duration);
532 	}
533 	mad_synth_frame(&nomad->synth, &nomad->frame);
534 	return 0;
535 }
536 
init_mad(struct nomad * nomad)537 static void init_mad(struct nomad *nomad)
538 {
539 	mad_stream_init(&nomad->stream);
540 	nomad->stream.options |= MAD_OPTION_IGNORECRC;
541 	mad_frame_init(&nomad->frame);
542 	mad_synth_init(&nomad->synth);
543 	mad_timer_reset(&nomad->timer);
544 	nomad->cur_frame = 0;
545 	nomad->i = -1;
546 	nomad->input_offset = 0;
547 	nomad->seen_first_frame = 0;
548 	nomad->readEOF = 0;
549 }
550 
free_mad(struct nomad * nomad)551 static void free_mad(struct nomad *nomad)
552 {
553 	mad_stream_finish(&nomad->stream);
554 	mad_frame_finish(&nomad->frame);
555 	mad_synth_finish(nomad->synth);
556 }
557 
do_open(struct nomad * nomad)558 static int do_open(struct nomad *nomad)
559 {
560 	int rc;
561 
562 	init_mad(nomad);
563 	nomad->info.filesize = nomad->cbs.lseek(nomad->datasource, 0, SEEK_END);
564 	if (nomad->info.filesize != -1)
565 		nomad->cbs.lseek(nomad->datasource, 0, SEEK_SET);
566 	if (nomad->info.filesize == -1) {
567 		rc = decode(nomad);
568 		if (rc < 0)
569 			goto error;
570 		if (rc == 1)
571 			goto eof;
572 		nomad->info.sample_rate = nomad->frame.header.samplerate;
573 		nomad->info.channels = MAD_NCHANNELS(&nomad->frame.header);
574 		nomad->info.layer = nomad->frame.header.layer;
575 		nomad->info.dual_channel = nomad->frame.header.mode == MAD_MODE_DUAL_CHANNEL;
576 		nomad->info.joint_stereo = nomad->frame.header.mode == MAD_MODE_JOINT_STEREO;
577 
578 		/* unknown */
579 		nomad->info.duration = -1.0;
580 		nomad->info.nr_frames = -1;
581 		nomad->info.vbr = -1;
582 		nomad->info.avg_bitrate = -1;
583 	} else {
584 		rc = scan(nomad);
585 		if (rc < 0)
586 			goto error;
587 		if (rc == 1)
588 			goto eof;
589 		free_mad(nomad);
590 		init_mad(nomad);
591 	}
592 	d_print("\n  frames: %d, br: %d b/s, sr: %d Hz, ch: %d, layer: %d, joint stereo: %d\n"
593 		"  dual channel: %d, vbr: %d, duration: %g s, xing: %d\n",
594 			nomad->info.nr_frames, nomad->info.avg_bitrate,
595 			nomad->info.sample_rate, nomad->info.channels,
596 			nomad->info.layer, nomad->info.joint_stereo,
597 			nomad->info.dual_channel, nomad->info.vbr,
598 			nomad->info.duration,
599 			nomad->has_xing);
600 #if defined(DEBUG_XING)
601 	if (nomad->has_xing)
602 		d_print("xing: flags: 0x%x, frames: %d, bytes: %d, scale: %d\n",
603 			nomad->xing.flags,
604 			nomad->xing.nr_frames,
605 			nomad->xing.bytes,
606 			nomad->xing.scale);
607 #endif
608 	return 0;
609 error:
610 	nomad_close(nomad);
611 	return rc;
612 eof:
613 	nomad_close(nomad);
614 	return -NOMAD_ERROR_FILE_FORMAT;
615 }
616 
nomad_open_callbacks(struct nomad ** nomadp,void * datasource,struct nomad_callbacks * cbs)617 int nomad_open_callbacks(struct nomad **nomadp, void *datasource, struct nomad_callbacks *cbs)
618 {
619 	struct nomad *nomad;
620 
621 	const struct nomad nomad_init = {
622 		.datasource = datasource,
623 		.cbs = {
624 			.read  = cbs->read,
625 			.lseek = cbs->lseek,
626 			.close = cbs->close
627 		}
628 	};
629 
630 	nomad = xnew(struct nomad, 1);
631 	*nomad = nomad_init;
632 	nomad->lame.peak = nomad->lame.trackGain = nomad->lame.albumGain = strtof("NAN", NULL);
633 	*nomadp = nomad;
634 	/* on error do_open calls nomad_close */
635 	return do_open(nomad);
636 }
637 
nomad_close(struct nomad * nomad)638 void nomad_close(struct nomad *nomad)
639 {
640 	free_mad(nomad);
641 	nomad->cbs.close(nomad->datasource);
642 	free(nomad->seek_idx.table);
643 	free(nomad);
644 }
645 
nomad_read(struct nomad * nomad,char * buffer,int count,nomad_sample_format format)646 int nomad_read(struct nomad *nomad, char *buffer, int count, nomad_sample_format format)
647 {
648 	int i, j, size, psize, to;
649 
650 	if (nomad->i == -1) {
651 		int rc;
652 
653 next_frame:
654 		rc = decode(nomad);
655 		if (rc < 0)
656 			return rc;
657 		if (rc == 1)
658 			return 0;
659 		nomad->i = 0;
660 	}
661 
662 	if (nomad->has_lame) {
663 		/* skip samples at start for gapless playback */
664 		if (nomad->start_drop_frames) {
665 			nomad->start_drop_frames--;
666 			/* XING header is an empty frame we want to skip */
667 			if (!nomad->seen_first_frame) {
668 				nomad->cur_frame--;
669 				nomad->seen_first_frame = 1;
670 			}
671 #if defined(DEBUG_LAME)
672 			d_print("skipped a frame at start\n");
673 #endif
674 			goto next_frame;
675 		}
676 		if (nomad->start_drop_samples) {
677 			if (nomad->start_drop_samples < nomad->synth.pcm.length) {
678 				nomad->i += nomad->start_drop_samples;
679 				nomad->start_drop_samples = 0;
680 				/* Take advantage of the fact that this block is only executed once per file, and
681 				   calculate the # of samples/frames to skip at the end.  Note that synth.pcm.length
682 				   is needed for the calculation. */
683 				nomad->end_drop_frames = nomad->end_drop_samples / nomad->synth.pcm.length;
684 				nomad->end_drop_samples = nomad->end_drop_samples % nomad->synth.pcm.length;
685 #if defined(DEBUG_LAME)
686 				d_print("skipped %d samples at start\n", nomad->i);
687 				d_print("will skip %d samples and %d frame(s) at end\n",
688 					nomad->end_drop_samples, nomad->end_drop_frames);
689 #endif
690 			}
691 			else {
692 				nomad->start_drop_samples -= nomad->synth.pcm.length;
693 #if defined(DEBUG_LAME)
694 				d_print("skipped %d samples at start and moving to next frame\n", nomad->synth.pcm.length);
695 #endif
696 				goto next_frame;
697 			}
698 		}
699 		/* skip samples/frames at end for gapless playback */
700 		if (nomad->cur_frame == (nomad->xing.nr_frames + 1 - nomad->end_drop_frames)) {
701 #if defined(DEBUG_LAME)
702 				d_print("skipped %d frame(s) at end\n", nomad->end_drop_frames);
703 #endif
704 			return 0;
705 		}
706 	}
707 
708 	psize = nomad->info.channels * 16 / 8;
709 	size = (nomad->synth.pcm.length - nomad->i) * psize;
710 
711 	if (size > count) {
712 		to = nomad->i + count / psize;
713 	} else {
714 		to = nomad->synth.pcm.length;
715 	}
716 	j = 0;
717 	for (i = nomad->i; i < to; i++) {
718 		short sample;
719 
720 		/* skip samples/frames at end for gapless playback */
721 		if (nomad->has_lame
722 		    && nomad->end_drop_samples
723 		    && (nomad->cur_frame == (nomad->xing.nr_frames - nomad->end_drop_frames))
724 		    && i == (nomad->synth.pcm.length - nomad->end_drop_samples)) {
725 			nomad->i = -1;
726 #if defined(DEBUG_LAME)
727 			d_print("skipped %d samples at end of frame %d\n", nomad->end_drop_samples, (int)nomad->cur_frame);
728 #endif
729 			return j;
730 		}
731         if (format == SAMPLE_FORMAT_16_BIT_PCM) {
732             sample = scale(nomad->synth.pcm.samples[0][i]);
733             buffer[j++] = (sample >> 0) & 0xff;
734             buffer[j++] = (sample >> 8) & 0xff;
735         }
736         else { /* SAMPLE_FORMAT_32_BIT_FLOAT */
737             ((float*)buffer)[j++] = mad_f_tofloat(nomad->synth.pcm.samples[0][i]);
738         }
739 
740 		if (nomad->info.channels == 2) {
741             if (format == SAMPLE_FORMAT_16_BIT_PCM) {
742                 sample = scale(nomad->synth.pcm.samples[1][i]);
743                 buffer[j++] = (sample >> 0) & 0xff;
744                 buffer[j++] = (sample >> 8) & 0xff;
745             }
746             else { /* SAMPLE_FORMAT_32_BIT_FLOAT */
747                 ((float*) buffer)[j++] = mad_f_tofloat(nomad->synth.pcm.samples[1][i]);
748             }
749 		}
750 	}
751 	if (to != nomad->synth.pcm.length) {
752 		nomad->i = i;
753 	} else {
754 		nomad->i = -1;
755 	}
756 	return j;
757 }
758 
nomad_time_seek_accurate(struct nomad * nomad,double pos)759 static int nomad_time_seek_accurate(struct nomad *nomad, double pos)
760 {
761 	int rc;
762 
763 	/* seek to beginning of file and search frame-by-frame */
764 	if (nomad->cbs.lseek(nomad->datasource, 0, SEEK_SET) == -1)
765 		return -1;
766 
767 	/* XING header should NOT be counted - if we're here, we know it's present */
768 	nomad->cur_frame = -1;
769 
770 	while (timer_to_seconds(nomad->timer) < pos) {
771 		rc = fill_buffer(nomad);
772 		if (rc == -1)
773 			return -1;
774 		if (rc == 0)
775 			return 1;
776 
777 		if (mad_header_decode(&nomad->frame.header, &nomad->stream)) {
778 			if (nomad->stream.error == MAD_ERROR_BUFLEN)
779 				continue;
780 			if (!MAD_RECOVERABLE(nomad->stream.error)) {
781 				d_print("unrecoverable frame level error.\n");
782 				return -1;
783 			}
784 			if (nomad->stream.error == MAD_ERROR_LOSTSYNC)
785 				handle_lost_sync(nomad);
786 			continue;
787 		}
788 		nomad->cur_frame++;
789 		mad_timer_add(&nomad->timer, nomad->frame.header.duration);
790 	}
791 #if defined(DEBUG_LAME)
792 		d_print("seeked to %g = %g\n", pos, timer_to_seconds(nomad->timer));
793 #endif
794 	return 0;
795 }
796 
nomad_time_seek(struct nomad * nomad,double pos)797 int nomad_time_seek(struct nomad *nomad, double pos)
798 {
799 	off_t offset = 0;
800 
801 	if (pos < 0.0 || pos > nomad->info.duration) {
802 		errno = EINVAL;
803 		return -1;
804 	}
805 	if (nomad->info.filesize == -1) {
806 		errno = ESPIPE;
807 		return -1;
808 	}
809 	free_mad(nomad);
810 	init_mad(nomad);
811 
812 	/* if file has a LAME header, perform frame-accurate seek for gapless playback */
813 	if (nomad->has_lame) {
814 		return nomad_time_seek_accurate(nomad, pos);
815 	} else if (nomad->has_xing) {
816 		/* calculate seek offset */
817 		/* seek to truncate(pos / duration * 100) / 100 * duration */
818 		double k, tmp_pos;
819 		int ki;
820 
821 		k = pos / nomad->info.duration * 100.0;
822 		ki = k;
823 		tmp_pos = ((double)ki) / 100.0 * nomad->info.duration;
824 		nomad->timer.seconds = (signed int)tmp_pos;
825 		nomad->timer.fraction = (tmp_pos - (double)nomad->timer.seconds) * MAD_TIMER_RESOLUTION;
826 #if defined(DEBUG_XING)
827 		d_print("seeking to %g = %g %d%%\n",
828 				pos,
829 				timer_to_seconds(nomad->timer),
830 				ki);
831 #endif
832 		offset = ((unsigned long long)nomad->xing.toc[ki] * nomad->xing.bytes) / 256;
833 	} else if (nomad->seek_idx.size > 0) {
834 		int idx = (int)(pos / SEEK_IDX_INTERVAL) - 1;
835 
836 		if (idx > nomad->seek_idx.size - 1)
837 			idx = nomad->seek_idx.size - 1;
838 
839 		if (idx >= 0) {
840 			offset = nomad->seek_idx.table[idx].offset;
841 			nomad->timer = nomad->seek_idx.table[idx].timer;
842 		}
843 	}
844 	if (nomad->cbs.lseek(nomad->datasource, offset, SEEK_SET) == -1)
845 		return -1;
846 
847 	nomad->input_offset = offset;
848 	while (timer_to_seconds(nomad->timer) < pos) {
849 		int rc;
850 
851 		rc = fill_buffer(nomad);
852 		if (rc == -1)
853 			return -1;
854 		if (rc == 0)
855 			return 0;
856 
857 		if (mad_header_decode(&nomad->frame.header, &nomad->stream) == 0) {
858 			build_seek_index(nomad);
859 		} else {
860 			if (!MAD_RECOVERABLE(nomad->stream.error) && nomad->stream.error != MAD_ERROR_BUFLEN) {
861 				d_print("unrecoverable frame level error.\n");
862 				return -1;
863 			}
864 			if (nomad->stream.error == MAD_ERROR_LOSTSYNC)
865 				handle_lost_sync(nomad);
866 		}
867 	}
868 #if defined(DEBUG_XING)
869 	if (nomad->has_xing)
870 		d_print("seeked to %g = %g\n", pos, timer_to_seconds(nomad->timer));
871 #endif
872 	return 0;
873 }
874 
nomad_xing(struct nomad * nomad)875 const struct nomad_xing *nomad_xing(struct nomad *nomad)
876 {
877 	return nomad->has_xing ? &nomad->xing : NULL;
878 }
879 
nomad_lame(struct nomad * nomad)880 const struct nomad_lame *nomad_lame(struct nomad *nomad)
881 {
882 	return nomad->has_lame ? &nomad->lame : NULL;
883 }
884 
nomad_info(struct nomad * nomad)885 const struct nomad_info *nomad_info(struct nomad *nomad)
886 {
887 	return &nomad->info;
888 }
889 
nomad_current_bitrate(struct nomad * nomad)890 long nomad_current_bitrate(struct nomad *nomad)
891 {
892 	long bitrate = -1;
893 	if (nomad->current.nr_frames > 0) {
894 		bitrate = nomad->current.bitrate_sum / nomad->current.nr_frames;
895 		nomad->current.bitrate_sum = 0;
896 		nomad->current.nr_frames = 0;
897 	}
898 	return bitrate;
899 }
900