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