1 /*
2   Copyright (c) 2005-2009, The Musepack Development Team
3   All rights reserved.
4 
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions are
7   met:
8 
9   * Redistributions of source code must retain the above copyright
10   notice, this list of conditions and the following disclaimer.
11 
12   * Redistributions in binary form must reproduce the above
13   copyright notice, this list of conditions and the following
14   disclaimer in the documentation and/or other materials provided
15   with the distribution.
16 
17   * Neither the name of the The Musepack Development Team nor the
18   names of its contributors may be used to endorse or promote
19   products derived from this software without specific prior
20   written permission.
21 
22   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34 
35 #include <math.h>
36 #include <string.h>
37 #include "streaminfo.h"
38 #include "mpcdec.h"
39 #include "minimax.h"
40 #include "internal.h"
41 #include "decoder.h"
42 #include "huffman.h"
43 #include "mpc_bits_reader.h"
44 
45 /// maximum number of seek points in the table. The distance between points will
46 /// be adapted so this value is never exceeded.
47 #define MAX_SEEK_TABLE_SIZE	65536
48 
49 // streaminfo.c
50 mpc_status streaminfo_read_header_sv8(mpc_streaminfo* si,
51 									  const mpc_bits_reader * r_in,
52 									  mpc_size_t block_size);
53 mpc_status streaminfo_read_header_sv7(mpc_streaminfo* si, mpc_bits_reader * r_in);
54 void  streaminfo_encoder_info(mpc_streaminfo* si, const mpc_bits_reader * r_in);
55 void  streaminfo_gain(mpc_streaminfo* si, const mpc_bits_reader * r_in);
56 
57 // mpc_decoder.c
58 void mpc_decoder_reset_scf(mpc_decoder * d, int value);
59 
60 enum {
61 	MPC_BUFFER_SWAP = 1,
62 	MPC_BUFFER_FULL = 2,
63 };
64 
mpc_demux_clear_buff(mpc_demux * d)65 static void mpc_demux_clear_buff(mpc_demux * d)
66 {
67 	d->bytes_total = 0;
68 	d->bits_reader.buff = d->buffer;
69 	d->bits_reader.count = 8;
70 	d->block_bits = 0;
71 	d->block_frames = 0;
72 }
73 
74 // Returns the amount of unread bytes in the demux buffer.
75 // Unchecked version - may return a negative value when we've been reading
76 // past the end of the valid data as a result of some problem with the file.
mpc_unread_bytes_unchecked(mpc_demux * d)77 static mpc_int32_t mpc_unread_bytes_unchecked(mpc_demux * d) {
78 	return d->bytes_total + d->buffer - d->bits_reader.buff - ((8 - d->bits_reader.count) >> 3);
79 }
80 
81 
82 // Returns the number of bytes available in the buffer.
83 static mpc_uint32_t
mpc_demux_fill(mpc_demux * d,mpc_uint32_t min_bytes,int flags)84 mpc_demux_fill(mpc_demux * d, mpc_uint32_t min_bytes, int flags)
85 {
86 	mpc_uint32_t unread_bytes = (mpc_uint32_t) mpc_unread_bytes_unchecked(d);
87 	int offset = 0;
88 
89 	if ((mpc_int32_t) unread_bytes < 0)
90 		return 0; // Error - we've been reading past the end of the buffer - abort
91 
92 	if (min_bytes == 0 || min_bytes > DEMUX_BUFFER_SIZE ||
93 		    (unread_bytes < min_bytes && (flags & MPC_BUFFER_FULL) != 0 ))
94 		min_bytes = DEMUX_BUFFER_SIZE;
95 
96 	if (unread_bytes < min_bytes) {
97 		mpc_uint32_t bytes2read = min_bytes - unread_bytes;
98 		mpc_uint32_t bytes_free = DEMUX_BUFFER_SIZE - d->bytes_total;
99 		mpc_uint32_t bytesread;
100 
101 		if (flags & MPC_BUFFER_SWAP) {
102 			bytes2read &= -1 << 2;
103 			offset = (unread_bytes + 3) & ( -1 << 2);
104 			offset -= unread_bytes;
105 		}
106 
107 		if (bytes2read > bytes_free) {
108 			if (d->bits_reader.count == 0) {
109 				d->bits_reader.count = 8;
110 				d->bits_reader.buff++;
111 			}
112 			memmove(d->buffer + offset, d->bits_reader.buff, unread_bytes);
113 			d->bits_reader.buff = d->buffer + offset;
114 			d->bytes_total = unread_bytes + offset;
115 		}
116 		bytesread = d->r->read(d->r, d->buffer + d->bytes_total, bytes2read);
117 		if (bytesread < bytes2read) {
118 			memset(d->buffer + d->bytes_total + bytesread, 0, bytes2read - bytesread); // FIXME : why ?
119 		}
120 		if (flags & MPC_BUFFER_SWAP) {
121 			unsigned int i, * tmp = (unsigned int *) (d->buffer + d->bytes_total);
122 			for(i = 0 ;i < (bytes2read >> 2); i++)
123 				tmp[i] = mpc_swap32(tmp[i]);
124 		}
125 		d->bytes_total += bytesread;
126 		unread_bytes += bytesread;
127 	}
128 
129 	return unread_bytes;
130 }
131 
132 /**
133  * seek to a bit position in the stream
134  * @param d demuxer context
135  * @param fpos position in the stream in bits from the beginning of mpc datas
136  * @param min_bytes number of bytes to load after seeking
137  */
138 static mpc_status
mpc_demux_seek(mpc_demux * d,mpc_seek_t fpos,mpc_uint32_t min_bytes)139 mpc_demux_seek(mpc_demux * d, mpc_seek_t fpos, mpc_uint32_t min_bytes) {
140 	mpc_seek_t start_pos, end_pos;
141 	mpc_int_t bit_offset;
142 
143 	// get current buffer position
144 	end_pos = ((mpc_seek_t)(d->r->tell(d->r))) << 3;
145 	start_pos =	end_pos - (d->bytes_total << 3);
146 
147 	if (fpos >= start_pos && fpos < end_pos) {
148 		d->bits_reader.buff = d->buffer + ((fpos - start_pos) >> 3);
149 		bit_offset = fpos & 7;
150 		d->block_bits = 0;
151 		d->block_frames = 0;
152 	} else {
153 		mpc_seek_t next_pos = fpos >> 3;
154 		if (d->si.stream_version == 7)
155 			next_pos = ((next_pos - d->si.header_position) & (-1 << 2)) + d->si.header_position;
156 		bit_offset = (int) (fpos - (next_pos << 3));
157 
158 		mpc_demux_clear_buff(d);
159 		if (!d->r->seek(d->r, (mpc_int32_t) next_pos))
160 			return MPC_STATUS_FAIL;
161 	}
162 
163 	if (d->si.stream_version == 7)
164 		mpc_demux_fill(d, (min_bytes + ((bit_offset + 7) >> 3) + 3) & (~3), MPC_BUFFER_SWAP);
165 	else
166 		mpc_demux_fill(d, min_bytes + ((bit_offset + 7) >> 3), 0);
167 	d->bits_reader.buff += bit_offset >> 3;
168 	d->bits_reader.count = 8 - (bit_offset & 7);
169 
170 	return MPC_STATUS_OK;
171 }
172 
173 /**
174  * return the current position in the stream (in bits) from the beginning
175  * of the file
176  * @param d demuxer context
177  * @return current stream position in bits
178  */
mpc_demux_pos(mpc_demux * d)179 mpc_seek_t mpc_demux_pos(mpc_demux * d)
180 {
181 	return (((mpc_seek_t)(d->r->tell(d->r)) - d->bytes_total +
182 	         d->bits_reader.buff - d->buffer) << 3) + 8 - d->bits_reader.count;
183 }
184 
185 /**
186  * Searches for a ID3v2-tag and reads the length (in bytes) of it.
187  *
188  * @param d demuxer context
189  * @return size of tag, in bytes
190  * @return MPC_STATUS_FAIL on errors of any kind
191  */
mpc_demux_skip_id3v2(mpc_demux * d)192 static mpc_int32_t mpc_demux_skip_id3v2(mpc_demux * d)
193 {
194 	mpc_uint8_t  tmp [4];
195 	mpc_bool_t footerPresent;     // ID3v2.4-flag
196 	mpc_int32_t size;
197 
198     // we must be at the beginning of the stream
199 	mpc_demux_fill(d, 3, 0);
200 
201     // check id3-tag
202 	if ( 0 != memcmp( d->bits_reader.buff, "ID3", 3 ) )
203 		return 0;
204 
205 	mpc_demux_fill(d, 10, 0);
206 
207 	mpc_bits_read(&d->bits_reader, 24); // read ID3
208 	mpc_bits_read(&d->bits_reader, 16); // read tag version
209 
210 	tmp[0] = mpc_bits_read(&d->bits_reader, 8); // read flags
211 	footerPresent = tmp[0] & 0x10;
212 	if ( tmp[0] & 0x0F )
213 		return MPC_STATUS_FAIL; // not (yet???) allowed
214 
215 	tmp[0] = mpc_bits_read(&d->bits_reader, 8); // read size
216 	tmp[1] = mpc_bits_read(&d->bits_reader, 8); // read size
217 	tmp[2] = mpc_bits_read(&d->bits_reader, 8); // read size
218 	tmp[3] = mpc_bits_read(&d->bits_reader, 8); // read size
219 
220 	if ( (tmp[0] | tmp[1] | tmp[2] | tmp[3]) & 0x80 )
221 		return MPC_STATUS_FAIL; // not allowed
222 
223     // read headerSize (syncsave: 4 * $0xxxxxxx = 28 significant bits)
224 	size = tmp[0] << 21;
225 	size |= tmp[1] << 14;
226 	size |= tmp[2] << 7;
227 	size |= tmp[3];
228 
229 	size += 10; //header
230 
231 	if ( footerPresent ) size += 10;
232 
233 	// This is called before file headers get read, streamversion etc isn't yet known, demuxing isn't properly initialized and we can't call mpc_demux_seek() from here.
234 	mpc_demux_clear_buff(d);
235 	if (!d->r->seek(d->r, size))
236 		return MPC_STATUS_FAIL;
237 
238 	return size;
239 }
240 
mpc_demux_seek_init(mpc_demux * d)241 static mpc_status mpc_demux_seek_init(mpc_demux * d)
242 {
243 	size_t seek_table_size;
244 	if (d->seek_table != 0)
245 		return MPC_STATUS_OK;
246 
247 	d->seek_pwr = 6;
248 	if (d->si.block_pwr > d->seek_pwr)
249 		d->seek_pwr = d->si.block_pwr;
250 	seek_table_size = (2 + d->si.samples / (MPC_FRAME_LENGTH << d->seek_pwr));
251 	while (seek_table_size > MAX_SEEK_TABLE_SIZE) {
252 		d->seek_pwr++;
253 		seek_table_size = (2 + d->si.samples / (MPC_FRAME_LENGTH << d->seek_pwr));
254 	}
255 	d->seek_table = malloc((size_t)(seek_table_size * sizeof(mpc_seek_t)));
256 	if (d->seek_table == 0)
257 		return MPC_STATUS_FAIL;
258 	d->seek_table[0] = (mpc_seek_t)mpc_demux_pos(d);
259 	d->seek_table_size = 1;
260 
261 	return MPC_STATUS_OK;
262 }
263 
mpc_demux_ST(mpc_demux * d)264 static mpc_status mpc_demux_ST(mpc_demux * d)
265 {
266 	mpc_uint64_t tmp;
267 	mpc_seek_t * table, last[2];
268 	mpc_bits_reader r = d->bits_reader;
269 	mpc_uint_t i, diff_pwr = 0, mask;
270 	mpc_uint32_t file_table_size;
271 
272 	if (d->seek_table != 0)
273 		return MPC_STATUS_OK;
274 
275 	mpc_bits_get_size(&r, &tmp);
276 	file_table_size = (mpc_seek_t) tmp;
277 	d->seek_pwr = d->si.block_pwr + mpc_bits_read(&r, 4);
278 
279 	tmp = 2 + d->si.samples / (MPC_FRAME_LENGTH << d->seek_pwr);
280 	while (tmp > MAX_SEEK_TABLE_SIZE) {
281 		d->seek_pwr++;
282 		diff_pwr++;
283 		tmp = 2 + d->si.samples / (MPC_FRAME_LENGTH << d->seek_pwr);
284 	}
285 	if ((file_table_size >> diff_pwr) > tmp)
286 		file_table_size = tmp << diff_pwr;
287 	d->seek_table = malloc((size_t) (tmp * sizeof(mpc_seek_t)));
288 	d->seek_table_size = (file_table_size + ((1 << diff_pwr) - 1)) >> diff_pwr;
289 
290 	table = d->seek_table;
291 	mpc_bits_get_size(&r, &tmp);
292 	table[0] = last[0] = (mpc_seek_t) (tmp + d->si.header_position) * 8;
293 
294 	if (d->seek_table_size == 1)
295 		return MPC_STATUS_OK;
296 
297 	mpc_bits_get_size(&r, &tmp);
298 	last[1] = (mpc_seek_t) (tmp + d->si.header_position) * 8;
299 	if (diff_pwr == 0) table[1] = last[1];
300 
301 	mask = (1 << diff_pwr) - 1;
302 	for (i = 2; i < file_table_size; i++) {
303 		int code = mpc_bits_golomb_dec(&r, 12);
304 		if (code & 1)
305 			code = -(code & (-1 << 1));
306 		code <<= 2;
307 		last[i & 1] = code + 2 * last[(i-1) & 1] - last[i & 1];
308 		if ((i & mask) == 0)
309 			table[i >> diff_pwr] = last[i & 1];
310 	}
311 	return MPC_STATUS_OK;
312 }
313 
mpc_demux_SP(mpc_demux * d,int size,int block_size)314 static mpc_status mpc_demux_SP(mpc_demux * d, int size, int block_size)
315 {
316 	mpc_seek_t cur;
317 	mpc_uint64_t ptr;
318 	mpc_block b;
319 	int st_head_size;
320 
321 	cur = mpc_demux_pos(d);
322 	mpc_bits_get_size(&d->bits_reader, &ptr);
323 	MPC_AUTO_FAIL( mpc_demux_seek(d, (ptr - size) * 8 + cur, 11) );
324 	st_head_size = mpc_bits_get_block(&d->bits_reader, &b);
325 	if (memcmp(b.key, "ST", 2) == 0) {
326 		d->chap_pos = (ptr - size + b.size + st_head_size) * 8 + cur;
327 		d->chap_nb = -1;
328 		if (mpc_demux_fill(d, (mpc_uint32_t) b.size, 0) < b.size)
329 			return MPC_STATUS_FAIL;
330 		MPC_AUTO_FAIL( mpc_demux_ST(d) );
331 	}
332 	return mpc_demux_seek(d, cur, 11 + block_size);
333 }
334 
mpc_demux_chap_empty(mpc_demux * d)335 static void mpc_demux_chap_empty(mpc_demux * d) {
336 	free(d->chap); d->chap = 0;
337 	d->chap_nb = 0; // -1 for undefined, 0 for no chapters
338 	d->chap_pos = 0;
339 }
340 
mpc_demux_chap_find_inner(mpc_demux * d)341 static mpc_status mpc_demux_chap_find_inner(mpc_demux * d)
342 {
343 	mpc_block b;
344 	int tag_size = 0, chap_size = 0, size, i = 0;
345 
346 	d->chap_nb = 0;
347 
348 	if (d->si.stream_version < 8)
349 		return MPC_STATUS_OK;
350 
351 	if (d->chap_pos == 0) {
352 		mpc_uint64_t cur_pos = (d->si.header_position + 4) * 8;
353 		MPC_AUTO_FAIL( mpc_demux_seek(d, cur_pos, 11) ); // seek to the beginning of the stream
354 		size = mpc_bits_get_block(&d->bits_reader, &b);
355 		while (memcmp(b.key, "SE", 2) != 0) {
356 			mpc_uint64_t new_pos = cur_pos + (size + b.size) * 8;
357 			MPC_AUTO_FAIL(mpc_check_key(b.key));
358 
359 			if (memcmp(b.key, "CT", 2) == 0) {
360 				if (d->chap_pos == 0) d->chap_pos = cur_pos;
361 			} else {
362 				d->chap_pos = 0;
363 			}
364 			if (new_pos <= cur_pos)
365 				return MPC_STATUS_FAIL;
366 			cur_pos = new_pos;
367 
368 			MPC_AUTO_FAIL( mpc_demux_seek(d, cur_pos, 11) );
369 			size = mpc_bits_get_block(&d->bits_reader, &b);
370 		}
371 		if (d->chap_pos == 0)
372 			d->chap_pos = cur_pos;
373 	}
374 
375 	mpc_demux_seek(d, d->chap_pos, 20);
376 	size = mpc_bits_get_block(&d->bits_reader, &b);
377 	while (memcmp(b.key, "CT", 2) == 0) {
378 		mpc_uint64_t chap_sample;
379 		d->chap_nb++;
380 		chap_size += size;
381 		size = mpc_bits_get_size(&d->bits_reader, &chap_sample) + 4;
382 		chap_size += size;
383 		tag_size += b.size - size;
384 		MPC_AUTO_FAIL( mpc_demux_seek(d, d->chap_pos + (chap_size + tag_size) * 8, 20) );
385 		size = mpc_bits_get_block(&d->bits_reader, &b);
386 	}
387 
388 	if (d->chap_nb > 0) {
389 		char * ptag;
390 		d->chap = malloc(sizeof(mpc_chap_info) * d->chap_nb + tag_size);
391 		if (d->chap == 0)
392 			return MPC_STATUS_FAIL;
393 
394 		ptag = (char*)(d->chap + d->chap_nb);
395 
396 		MPC_AUTO_FAIL( mpc_demux_seek(d, d->chap_pos, 11) );
397 		size = mpc_bits_get_block(&d->bits_reader, &b);
398 		while (memcmp(b.key, "CT", 2) == 0) {
399 			mpc_uint_t tmp_size;
400 			char * tmp_ptag = ptag;
401 			if (mpc_demux_fill(d, 11 + (mpc_uint32_t) b.size, 0) < b.size)
402 				return MPC_STATUS_FAIL;
403 			size = mpc_bits_get_size(&d->bits_reader, &d->chap[i].sample) + 4;
404 			d->chap[i].gain = (mpc_uint16_t) mpc_bits_read(&d->bits_reader, 16);
405 			d->chap[i].peak = (mpc_uint16_t) mpc_bits_read(&d->bits_reader, 16);
406 
407 			tmp_size = b.size - size;
408 			do {
409 				mpc_uint_t rd_size = tmp_size;
410 				mpc_uint8_t * tmp_buff = d->bits_reader.buff + ((8 - d->bits_reader.count) >> 3);
411 				mpc_uint32_t avail_bytes = d->bytes_total + d->buffer - tmp_buff;
412 				rd_size = mini(rd_size, avail_bytes);
413 				memcpy(tmp_ptag, tmp_buff, rd_size);
414 				tmp_size -= rd_size;
415 				tmp_ptag += rd_size;
416 				d->bits_reader.buff += rd_size;
417 				mpc_demux_fill(d, tmp_size, 0);
418 			} while (tmp_size > 0);
419 
420 			d->chap[i].tag_size = b.size - size;
421 			d->chap[i].tag = ptag;
422 			ptag += b.size - size;
423 			i++;
424 			size = mpc_bits_get_block(&d->bits_reader, &b);
425 		}
426 	}
427 
428 	d->bits_reader.buff -= size;
429 	return MPC_STATUS_OK;
430 }
431 
mpc_demux_chap_find(mpc_demux * d)432 static mpc_status mpc_demux_chap_find(mpc_demux * d) {
433 	mpc_status s = mpc_demux_chap_find_inner(d);
434 	if (MPC_IS_FAILURE(s))
435 		mpc_demux_chap_empty(d);
436 	return s;
437 }
438 
439 /**
440  * Gets the number of chapters in the stream
441  * @param d pointer to a musepack demuxer
442  * @return the number of chapters found in the stream
443  */
mpc_demux_chap_nb(mpc_demux * d)444 mpc_int_t mpc_demux_chap_nb(mpc_demux * d)
445 {
446 	if (d->chap_nb == -1)
447 		mpc_demux_chap_find(d);
448 	return d->chap_nb;
449 }
450 
451 /**
452  * Gets datas associated to a given chapter
453  * The chapter tag is an APEv2 tag without the preamble
454  * @param d pointer to a musepack demuxer
455  * @param chap_nb chapter number you want datas (from 0 to mpc_demux_chap_nb(d) - 1)
456  * @return the chapter information structure
457  */
mpc_demux_chap(mpc_demux * d,int chap_nb)458 mpc_chap_info const * mpc_demux_chap(mpc_demux * d, int chap_nb)
459 {
460 	if (d->chap_nb == -1)
461 		mpc_demux_chap_find(d);
462 	if (chap_nb >= d->chap_nb || chap_nb < 0)
463 		return 0;
464 	return &d->chap[chap_nb];
465 }
466 
mpc_demux_header(mpc_demux * d)467 static mpc_status mpc_demux_header(mpc_demux * d)
468 {
469 	char magic[4];
470 
471 	d->si.pns = 0xFF;
472 	d->si.profile_name = "n.a.";
473 
474     // get header position
475 	d->si.header_position = mpc_demux_skip_id3v2(d);
476 	if(d->si.header_position < 0)
477 		return MPC_STATUS_FAIL;
478 
479 	d->si.tag_offset = d->si.total_file_length = d->r->get_size(d->r);
480 
481 	mpc_demux_fill(d, 4, 0);
482 	magic[0] = mpc_bits_read(&d->bits_reader, 8);
483 	magic[1] = mpc_bits_read(&d->bits_reader, 8);
484 	magic[2] = mpc_bits_read(&d->bits_reader, 8);
485 	magic[3] = mpc_bits_read(&d->bits_reader, 8);
486 
487 	if (memcmp(magic, "MP+", 3) == 0) {
488 		d->si.stream_version = magic[3] & 15;
489 		d->si.pns = magic[3] >> 4;
490 		if (d->si.stream_version != 7)
491 			return MPC_STATUS_FAIL;
492 		if (mpc_demux_fill(d, 6 * 4, MPC_BUFFER_SWAP) < 6 * 4) // header block size + endian convertion
493 			return MPC_STATUS_FAIL;
494 		MPC_AUTO_FAIL( streaminfo_read_header_sv7(&d->si, &d->bits_reader) );
495 	} else if (memcmp(magic, "MPCK", 4) == 0) {
496 		mpc_block b;
497 		int size;
498 		mpc_demux_fill(d, 11, 0); // max header block size
499 		size = mpc_bits_get_block(&d->bits_reader, &b);
500 		while( memcmp(b.key, "AP", 2) != 0 ){ // scan all blocks until audio
501 			if (mpc_check_key(b.key) != MPC_STATUS_OK)
502 				return MPC_STATUS_FAIL;
503 			if (b.size > (mpc_uint64_t) DEMUX_BUFFER_SIZE - 11)
504 				return MPC_STATUS_FAIL;
505 
506 			if (mpc_demux_fill(d, 11 + (mpc_uint32_t) b.size, 0) <= b.size)
507 				return MPC_STATUS_FAIL;
508 
509 			if (memcmp(b.key, "SH", 2) == 0) {
510 				MPC_AUTO_FAIL( streaminfo_read_header_sv8(&d->si, &d->bits_reader, (mpc_uint32_t) b.size) );
511 			} else if (memcmp(b.key, "RG", 2) == 0) {
512 				streaminfo_gain(&d->si, &d->bits_reader);
513 			} else if (memcmp(b.key, "EI", 2) == 0) {
514 				streaminfo_encoder_info(&d->si, &d->bits_reader);
515 			} else if (memcmp(b.key, "SO", 2) == 0) {
516 				MPC_AUTO_FAIL( mpc_demux_SP(d, size, (mpc_uint32_t) b.size) );
517 			} else if (memcmp(b.key, "ST", 2) == 0) {
518 				MPC_AUTO_FAIL( mpc_demux_ST(d) );
519 			}
520 			d->bits_reader.buff += b.size;
521 			size = mpc_bits_get_block(&d->bits_reader, &b);
522 		}
523 		d->bits_reader.buff -= size;
524 		if (d->si.stream_version == 0) // si not initialized !!!
525 			return MPC_STATUS_FAIL;
526 	} else {
527 		return MPC_STATUS_FAIL;
528 	}
529 
530 	return MPC_STATUS_OK;
531 }
532 
mpc_demux_init(mpc_reader * p_reader)533 mpc_demux * mpc_demux_init(mpc_reader * p_reader)
534 {
535 	mpc_demux* p_tmp = malloc(sizeof(mpc_demux));
536 
537 	if (p_tmp != 0) {
538 		memset(p_tmp, 0, sizeof(mpc_demux));
539 		p_tmp->r = p_reader;
540 		p_tmp->chap_nb = -1;
541 		mpc_demux_clear_buff(p_tmp);
542 		if (mpc_demux_header(p_tmp) == MPC_STATUS_OK &&
543 				  mpc_demux_seek_init(p_tmp) == MPC_STATUS_OK) {
544 			p_tmp->d = mpc_decoder_init(&p_tmp->si);
545 		} else {
546 			if (p_tmp->seek_table)
547 				free(p_tmp->seek_table);
548 			free(p_tmp);
549 			p_tmp = 0;
550 		}
551 	}
552 
553 	return p_tmp;
554 }
555 
mpc_demux_exit(mpc_demux * d)556 void mpc_demux_exit(mpc_demux * d)
557 {
558 	mpc_decoder_exit(d->d);
559 	free(d->seek_table);
560 	free(d->chap);
561 	free(d);
562 }
563 
mpc_demux_get_info(mpc_demux * d,mpc_streaminfo * i)564 void mpc_demux_get_info(mpc_demux * d, mpc_streaminfo * i)
565 {
566 	memcpy(i, &d->si, sizeof d->si);
567 }
568 
mpc_demux_decode_inner(mpc_demux * d,mpc_frame_info * i)569 static mpc_status mpc_demux_decode_inner(mpc_demux * d, mpc_frame_info * i)
570 {
571 	mpc_bits_reader r;
572 	if (d->si.stream_version >= 8) {
573 		i->is_key_frame = MPC_FALSE;
574 
575 		if (d->block_frames == 0) {
576 			mpc_block b = {{0,0},0};
577 			d->bits_reader.count &= -8;
578 			if (d->d->decoded_samples == (d->seek_table_size << d->seek_pwr) * MPC_FRAME_LENGTH) {
579 				d->seek_table[d->seek_table_size] = (mpc_seek_t) mpc_demux_pos(d);
580 				d->seek_table_size ++;
581 			}
582 			mpc_demux_fill(d, 11, MPC_BUFFER_FULL); // max header block size
583 			mpc_bits_get_block(&d->bits_reader, &b);
584 			while( memcmp(b.key, "AP", 2) != 0 ) { // scan all blocks until audio
585 				MPC_AUTO_FAIL( mpc_check_key(b.key) );
586 
587 				if (memcmp(b.key, "SE", 2) == 0) { // end block
588 					i->bits = -1;
589 					return MPC_STATUS_OK;
590 				}
591 
592 				if (mpc_demux_fill(d, 11 + (mpc_uint32_t) b.size, MPC_BUFFER_FULL) < b.size)
593 					return MPC_STATUS_FAIL;
594 
595 				d->bits_reader.buff += b.size;
596 				mpc_bits_get_block(&d->bits_reader, &b);
597 			}
598 			d->block_bits = (mpc_uint32_t) b.size * 8;
599 			d->block_frames = 1 << d->si.block_pwr;
600 			i->is_key_frame = MPC_TRUE;
601 		}
602 		if (d->buffer + d->bytes_total - d->bits_reader.buff <= MAX_FRAME_SIZE)
603 			mpc_demux_fill(d, (d->block_bits >> 3) + 1, MPC_BUFFER_FULL);
604 		r = d->bits_reader;
605 		mpc_decoder_decode_frame(d->d, &d->bits_reader, i);
606 		d->block_bits -= ((d->bits_reader.buff - r.buff) << 3) + r.count - d->bits_reader.count;
607 		d->block_frames--;
608 		if (d->block_bits < 0 || (d->block_frames == 0 && d->block_bits > 7))
609 			return MPC_STATUS_FAIL;
610 	} else {
611 		if (d->d->decoded_samples == (d->seek_table_size << d->seek_pwr) * MPC_FRAME_LENGTH) {
612 			d->seek_table[d->seek_table_size] = (mpc_seek_t) mpc_demux_pos(d);
613 			d->seek_table_size ++;
614 		}
615 		mpc_demux_fill(d, MAX_FRAME_SIZE, MPC_BUFFER_FULL | MPC_BUFFER_SWAP);
616 		d->block_bits = (mpc_int_t) mpc_bits_read(&d->bits_reader, 20); // read frame size
617 		if (MPC_FRAME_LENGTH > d->d->samples - d->d->decoded_samples - 1) d->block_bits += 11; // we will read last frame size
618 		r = d->bits_reader;
619 		mpc_decoder_decode_frame(d->d, &d->bits_reader, i);
620 		if (i->bits != -1 && d->block_bits != ((d->bits_reader.buff - r.buff) << 3) + r.count - d->bits_reader.count)
621 			return MPC_STATUS_FAIL;
622 	}
623 	if (i->bits != -1 && d->buffer + d->bytes_total < d->bits_reader.buff + ((8 - d->bits_reader.count) >> 3))
624 		return MPC_STATUS_FAIL;
625 
626 	return MPC_STATUS_OK;
627 }
628 
mpc_demux_decode(mpc_demux * d,mpc_frame_info * i)629 mpc_status mpc_demux_decode(mpc_demux * d, mpc_frame_info * i) {
630 	for(;;) {
631 		// mpc_demux_decode_inner may return 0 samples and require repeated calls after a seek. Loop over until we have data to return.
632 		mpc_status s = mpc_demux_decode_inner(d, i);
633 		if (MPC_IS_FAILURE(s))
634 			i->bits = -1; // we pretend it's end of file
635 
636 		if (i->bits == -1 || i->samples > 0)
637 			return s;
638 	}
639 }
640 
mpc_demux_seek_second(mpc_demux * d,double seconds)641 mpc_status mpc_demux_seek_second(mpc_demux * d, double seconds)
642 {
643 	return mpc_demux_seek_sample(d, (mpc_int64_t)(seconds * (double)d->si.sample_freq + 0.5));
644 }
645 
mpc_demux_seek_sample(mpc_demux * d,mpc_uint64_t destsample)646 mpc_status mpc_demux_seek_sample(mpc_demux * d, mpc_uint64_t destsample)
647 {
648 	mpc_uint32_t fwd, samples_to_skip, i;
649 	mpc_uint32_t block_samples = MPC_FRAME_LENGTH << d->si.block_pwr;
650 	mpc_seek_t fpos;
651 
652 	destsample += d->si.beg_silence;
653 	if (destsample > d->si.samples) destsample = d->si.samples;
654 	fwd = (mpc_uint32_t) (destsample / block_samples);
655 	samples_to_skip = MPC_DECODER_SYNTH_DELAY +
656 			(mpc_uint32_t) (destsample % block_samples);
657 	if (d->si.stream_version == 7) {
658 		if (fwd > 32) {
659 			fwd -= 32;
660 			samples_to_skip += MPC_FRAME_LENGTH * 32;
661 		} else {
662 			samples_to_skip += MPC_FRAME_LENGTH * fwd;
663 			fwd = 0;
664 		}
665 	}
666 
667 	i = fwd >> (d->seek_pwr - d->si.block_pwr);
668 	if (i >= d->seek_table_size)
669 		i = d->seek_table_size - 1;
670 	fpos = d->seek_table[i];
671 	i <<= d->seek_pwr - d->si.block_pwr;
672 	d->d->decoded_samples = i * block_samples;
673 
674 	if (d->si.stream_version >= 8) {
675 		mpc_block b;
676 		int size;
677 		mpc_demux_seek(d, fpos, 11);
678 		size = mpc_bits_get_block(&d->bits_reader, &b);
679 		while(i < fwd) {
680 			if (memcmp(b.key, "AP", 2) == 0) {
681 				if (d->d->decoded_samples == (d->seek_table_size << d->seek_pwr) * MPC_FRAME_LENGTH) {
682 					d->seek_table[d->seek_table_size] = (mpc_seek_t) mpc_demux_pos(d) - 8 * size;
683 					d->seek_table_size ++;
684 				}
685 				d->d->decoded_samples += block_samples;
686 				i++;
687 			}
688 			fpos += ((mpc_uint32_t)b.size + size) * 8;
689 			mpc_demux_seek(d, fpos, 11);
690 			size = mpc_bits_get_block(&d->bits_reader, &b);
691 		}
692 		d->bits_reader.buff -= size;
693 	} else {
694 		mpc_decoder_reset_scf(d->d, fwd != 0);
695 		mpc_demux_seek(d, fpos, 4);
696 		for( ; i < fwd; i++){
697 			if (d->d->decoded_samples == (d->seek_table_size << d->seek_pwr) * MPC_FRAME_LENGTH) {
698 				d->seek_table[d->seek_table_size] = (mpc_seek_t) mpc_demux_pos(d);
699 				d->seek_table_size ++;
700 			}
701 			d->d->decoded_samples += block_samples;
702 			fpos += mpc_bits_read(&d->bits_reader, 20) + 20;
703 			mpc_demux_seek(d, fpos, 4);
704 		}
705 	}
706 	d->d->samples_to_skip = samples_to_skip;
707 	return MPC_STATUS_OK;
708 }
709 
mpc_set_replay_level(mpc_demux * d,float level,mpc_bool_t use_gain,mpc_bool_t use_title,mpc_bool_t clip_prevention)710 void mpc_set_replay_level(mpc_demux * d, float level, mpc_bool_t use_gain,
711 						  mpc_bool_t use_title, mpc_bool_t clip_prevention)
712 {
713 	float peak = (float) ( use_title ? d->si.peak_title : d->si.peak_album );
714 	float gain = (float) ( use_title ? d->si.gain_title : d->si.gain_album );
715 
716 	if(!use_gain && !clip_prevention)
717 		return;
718 
719 	if(!peak)
720 		peak = 1.;
721 	else
722 		peak = (float) ( (1 << 15) / pow(10, peak / (20 * 256)) );
723 
724 	if(!gain)
725 		gain = 1.;
726 	else
727 		gain = (float) pow(10, (level - gain / 256) / 20);
728 
729 	if(clip_prevention && (peak < gain || !use_gain))
730 		gain = peak;
731 
732 	mpc_decoder_scale_output(d->d, gain);
733 }
734