1 /*
2 	libmpg123: MPEG Audio Decoder library
3 
4 	copyright 1995-2020 by the mpg123 project - free software under the terms of the LGPL 2.1
5 	see COPYING and AUTHORS files in distribution or http://mpg123.org
6 
7 */
8 
9 #include "mpg123lib_intern.h"
10 #include "icy2utf8.h"
11 
12 #include "gapless.h"
13 /* Want accurate rounding function regardless of decoder setup. */
14 #define FORCE_ACCURATE
15 #include "sample.h"
16 #include "parse.h"
17 
18 #include "debug.h"
19 
20 #define SEEKFRAME(mh) ((mh)->ignoreframe < 0 ? 0 : (mh)->ignoreframe)
21 
mpg123_init(void)22 int attribute_align_arg mpg123_init(void)
23 {
24 	// Since 1.27.0, this is a no-op and shall stay that way.
25 	return MPG123_OK;
26 }
27 
mpg123_exit(void)28 void attribute_align_arg mpg123_exit(void)
29 {
30 	// Nothing to ever happen here.
31 }
32 
33 /* create a new handle with specified decoder, decoder can be "", "auto" or NULL for auto-detection */
mpg123_new(const char * decoder,int * error)34 mpg123_handle attribute_align_arg *mpg123_new(const char* decoder, int *error)
35 {
36 	return mpg123_parnew(NULL, decoder, error);
37 }
38 
39 // Runtime table calculation is back for specific uses that want minimal
40 // binary size. It's hidden in handle initialization, not in mpg123_init(),
41 // any user of such a minimal build should ensure that there is no trouble
42 // from concurrency or just call mpg123_new() once in single-threaded context.
43 
44 /* ...the full routine with optional initial parameters to override defaults. */
mpg123_parnew(mpg123_pars * mp,const char * decoder,int * error)45 mpg123_handle attribute_align_arg *mpg123_parnew(mpg123_pars *mp, const char* decoder, int *error)
46 {
47 	mpg123_handle *fr = NULL;
48 	int err = MPG123_OK;
49 
50 #ifdef RUNTIME_TABLES
51 	static char tables_initialized = 0;
52 	if(!tables_initialized)
53 	{
54 #ifndef NO_LAYER12
55 		init_layer12(); /* inits also shared tables with layer1 */
56 #endif
57 #ifndef NO_LAYER3
58 		init_layer3();
59 #endif
60 		init_costabs();
61 		tables_initialized = 1;
62 	}
63 #endif
64 
65 	// Silly paranoia checks. Really silly, but libmpg123 has been ported to strange
66 	// platforms in the past.
67 	if((sizeof(short) != 2) || (sizeof(long) < 4))
68 	{
69 		if(error != NULL) *error = MPG123_BAD_TYPES;
70 		return NULL;
71 	}
72 
73 #if (defined REAL_IS_FLOAT) && (defined IEEE_FLOAT)
74 	/* This is rather pointless but it eases my mind to check that we did
75 	   not enable the special rounding on a VAX or something. */
76 	if(12346 != REAL_TO_SHORT_ACCURATE(12345.67f))
77 	{
78 		if(error != NULL) *error = MPG123_BAD_FLOAT;
79 		return NULL;
80 	}
81 #endif
82 
83 	fr = (mpg123_handle*) malloc(sizeof(mpg123_handle));
84 	if(fr != NULL)
85 	{
86 		frame_init_par(fr, mp);
87 		debug("cpu opt setting");
88 		if(frame_cpu_opt(fr, decoder) != 1)
89 		{
90 			err = MPG123_BAD_DECODER;
91 			frame_exit(fr);
92 			free(fr);
93 			fr = NULL;
94 		}
95 	}
96 	if(fr != NULL)
97 	{
98 		fr->decoder_change = 1;
99 	}
100 	else if(err == MPG123_OK) err = MPG123_OUT_OF_MEM;
101 
102 	if(error != NULL) *error = err;
103 	return fr;
104 }
105 
mpg123_decoder(mpg123_handle * mh,const char * decoder)106 int attribute_align_arg mpg123_decoder(mpg123_handle *mh, const char* decoder)
107 {
108 	enum optdec dt = dectype(decoder);
109 
110 	if(mh == NULL) return MPG123_BAD_HANDLE;
111 
112 	if(dt == nodec)
113 	{
114 		mh->err = MPG123_BAD_DECODER;
115 		return MPG123_ERR;
116 	}
117 	if(dt == mh->cpu_opts.type) return MPG123_OK;
118 
119 	/* Now really change. */
120 	/* frame_exit(mh);
121 	frame_init(mh); */
122 	debug("cpu opt setting");
123 	if(frame_cpu_opt(mh, decoder) != 1)
124 	{
125 		mh->err = MPG123_BAD_DECODER;
126 		frame_exit(mh);
127 		return MPG123_ERR;
128 	}
129 	/* New buffers for decoder are created in frame_buffers() */
130 	if((frame_outbuffer(mh) != 0))
131 	{
132 		mh->err = MPG123_NO_BUFFERS;
133 		frame_exit(mh);
134 		return MPG123_ERR;
135 	}
136 	/* Do _not_ call decode_update here! That is only allowed after a first MPEG frame has been met. */
137 	mh->decoder_change = 1;
138 	return MPG123_OK;
139 }
140 
mpg123_param(mpg123_handle * mh,enum mpg123_parms key,long val,double fval)141 int attribute_align_arg mpg123_param(mpg123_handle *mh, enum mpg123_parms key, long val, double fval)
142 {
143 	int r;
144 
145 	if(mh == NULL) return MPG123_BAD_HANDLE;
146 	r = mpg123_par(&mh->p, key, val, fval);
147 	if(r != MPG123_OK){ mh->err = r; r = MPG123_ERR; }
148 	else
149 	{ /* Special treatment for some settings. */
150 #ifdef FRAME_INDEX
151 		if(key == MPG123_INDEX_SIZE)
152 		{ /* Apply frame index size and grow property on the fly. */
153 			r = frame_index_setup(mh);
154 			if(r != MPG123_OK) mh->err = MPG123_INDEX_FAIL;
155 		}
156 #endif
157 #ifndef NO_FEEDER
158 		/* Feeder pool size is applied right away, reader will react to that. */
159 		if(key == MPG123_FEEDPOOL || key == MPG123_FEEDBUFFER)
160 		bc_poolsize(&mh->rdat.buffer, mh->p.feedpool, mh->p.feedbuffer);
161 #endif
162 	}
163 	return r;
164 }
165 
mpg123_param2(mpg123_handle * mh,int key,long val,double fval)166 int attribute_align_arg mpg123_param2(mpg123_handle *mh,  int key, long val, double fval)
167 {
168 	return mpg123_param(mh, key, val, fval);
169 }
170 
mpg123_par(mpg123_pars * mp,enum mpg123_parms key,long val,double fval)171 int attribute_align_arg mpg123_par(mpg123_pars *mp, enum mpg123_parms key, long val, double fval)
172 {
173 	int ret = MPG123_OK;
174 
175 	if(mp == NULL) return MPG123_BAD_PARS;
176 	switch(key)
177 	{
178 		case MPG123_VERBOSE:
179 			mp->verbose = val;
180 		break;
181 		case MPG123_FLAGS:
182 #ifndef GAPLESS
183 			if(val & MPG123_GAPLESS) ret = MPG123_NO_GAPLESS;
184 #endif
185 			if(ret == MPG123_OK) mp->flags = val;
186 			debug1("set flags to 0x%lx", (unsigned long) mp->flags);
187 		break;
188 		case MPG123_ADD_FLAGS:
189 #ifndef GAPLESS
190 			/* Enabling of gapless mode doesn't work when it's not there, but disabling (below) is no problem. */
191 			if(val & MPG123_GAPLESS) ret = MPG123_NO_GAPLESS;
192 			else
193 #endif
194 			mp->flags |= val;
195 			debug1("set flags to 0x%lx", (unsigned long) mp->flags);
196 		break;
197 		case MPG123_REMOVE_FLAGS:
198 			mp->flags &= ~val;
199 			debug1("set flags to 0x%lx", (unsigned long) mp->flags);
200 		break;
201 		case MPG123_FORCE_RATE: /* should this trigger something? */
202 #ifdef NO_NTOM
203 			if(val > 0)
204 			ret = MPG123_BAD_RATE;
205 #else
206 			if(val > 96000) ret = MPG123_BAD_RATE;
207 			else mp->force_rate = val < 0 ? 0 : val; /* >0 means enable, 0 disable */
208 #endif
209 		break;
210 		case MPG123_DOWN_SAMPLE:
211 #ifdef NO_DOWNSAMPLE
212 			if(val != 0) ret = MPG123_BAD_RATE;
213 #else
214 			if(val < 0 || val > 2) ret = MPG123_BAD_RATE;
215 			else mp->down_sample = (int)val;
216 #endif
217 		break;
218 		case MPG123_RVA:
219 			if(val < 0 || val > MPG123_RVA_MAX) ret = MPG123_BAD_RVA;
220 			else mp->rva = (int)val;
221 		break;
222 		case MPG123_DOWNSPEED:
223 			mp->halfspeed = val < 0 ? 0 : val;
224 		break;
225 		case MPG123_UPSPEED:
226 			mp->doublespeed = val < 0 ? 0 : val;
227 		break;
228 		case MPG123_ICY_INTERVAL:
229 #ifndef NO_ICY
230 			mp->icy_interval = val > 0 ? val : 0;
231 #else
232 			if(val > 0) ret = MPG123_BAD_PARAM;
233 #endif
234 		break;
235 		case MPG123_OUTSCALE:
236 			/* Choose the value that is non-zero, if any.
237 			   Downscaling integers to 1.0 . */
238 			mp->outscale = val == 0 ? fval : (double)val/SHORT_SCALE;
239 		break;
240 		case MPG123_TIMEOUT:
241 #ifdef TIMEOUT_READ
242 			mp->timeout = val >= 0 ? val : 0;
243 #else
244 			if(val > 0) ret = MPG123_NO_TIMEOUT;
245 #endif
246 		break;
247 		case MPG123_RESYNC_LIMIT:
248 			mp->resync_limit = val;
249 		break;
250 		case MPG123_INDEX_SIZE:
251 #ifdef FRAME_INDEX
252 			mp->index_size = val;
253 #else
254 			if(val) // It is only an eror if you want to enable the index.
255 				ret = MPG123_NO_INDEX;
256 #endif
257 		break;
258 		case MPG123_PREFRAMES:
259 			if(val >= 0) mp->preframes = val;
260 			else ret = MPG123_BAD_VALUE;
261 		break;
262 		case MPG123_FEEDPOOL:
263 #ifndef NO_FEEDER
264 			if(val >= 0) mp->feedpool = val;
265 			else ret = MPG123_BAD_VALUE;
266 #else
267 			ret = MPG123_MISSING_FEATURE;
268 #endif
269 		break;
270 		case MPG123_FEEDBUFFER:
271 #ifndef NO_FEEDER
272 			if(val > 0) mp->feedbuffer = val;
273 			else ret = MPG123_BAD_VALUE;
274 #else
275 			ret = MPG123_MISSING_FEATURE;
276 #endif
277 		break;
278 		case MPG123_FREEFORMAT_SIZE:
279 			mp->freeformat_framesize = val;
280 		break;
281 		default:
282 			ret = MPG123_BAD_PARAM;
283 	}
284 	return ret;
285 }
286 
mpg123_par2(mpg123_pars * mp,int key,long val,double fval)287 int attribute_align_arg mpg123_par2(mpg123_pars *mp, int key, long val, double fval)
288 {
289 	return mpg123_par(mp, key, val, fval);
290 }
291 
mpg123_getparam(mpg123_handle * mh,enum mpg123_parms key,long * val,double * fval)292 int attribute_align_arg mpg123_getparam(mpg123_handle *mh, enum mpg123_parms key, long *val, double *fval)
293 {
294 	int r;
295 
296 	if(mh == NULL) return MPG123_BAD_HANDLE;
297 	r = mpg123_getpar(&mh->p, key, val, fval);
298 	if(r != MPG123_OK){ mh->err = r; r = MPG123_ERR; }
299 	return r;
300 }
301 
mpg123_getparam2(mpg123_handle * mh,int key,long * val,double * fval)302 int attribute_align_arg mpg123_getparam2(mpg123_handle *mh, int key, long *val, double *fval)
303 {
304 	return mpg123_getparam(mh, key, val, fval);
305 }
306 
mpg123_getpar(mpg123_pars * mp,enum mpg123_parms key,long * val,double * fval)307 int attribute_align_arg mpg123_getpar(mpg123_pars *mp, enum mpg123_parms key, long *val, double *fval)
308 {
309 	int ret = 0;
310 
311 	if(mp == NULL) return MPG123_BAD_PARS;
312 	switch(key)
313 	{
314 		case MPG123_VERBOSE:
315 			if(val) *val = mp->verbose;
316 		break;
317 		case MPG123_FLAGS:
318 		case MPG123_ADD_FLAGS:
319 			if(val) *val = mp->flags;
320 		break;
321 		case MPG123_FORCE_RATE:
322 			if(val)
323 #ifdef NO_NTOM
324 			*val = 0;
325 #else
326 			*val = mp->force_rate;
327 #endif
328 		break;
329 		case MPG123_DOWN_SAMPLE:
330 			if(val) *val = mp->down_sample;
331 		break;
332 		case MPG123_RVA:
333 			if(val) *val = mp->rva;
334 		break;
335 		case MPG123_DOWNSPEED:
336 			if(val) *val = mp->halfspeed;
337 		break;
338 		case MPG123_UPSPEED:
339 			if(val) *val = mp->doublespeed;
340 		break;
341 		case MPG123_ICY_INTERVAL:
342 #ifndef NO_ICY
343 			if(val) *val = (long)mp->icy_interval;
344 #else
345 			if(val) *val = 0;
346 #endif
347 		break;
348 		case MPG123_OUTSCALE:
349 			if(fval) *fval = mp->outscale;
350 			if(val) *val = (long)(mp->outscale*SHORT_SCALE);
351 		break;
352 		case MPG123_RESYNC_LIMIT:
353 			if(val) *val = mp->resync_limit;
354 		break;
355 		case MPG123_INDEX_SIZE:
356 			if(val)
357 #ifdef FRAME_INDEX
358 			*val = mp->index_size;
359 #else
360 			*val = 0; /* graceful fallback: no index is index of zero size */
361 #endif
362 		break;
363 		case MPG123_PREFRAMES:
364 			*val = mp->preframes;
365 		break;
366 		case MPG123_FEEDPOOL:
367 #ifndef NO_FEEDER
368 			*val = mp->feedpool;
369 #else
370 			ret = MPG123_MISSING_FEATURE;
371 #endif
372 		break;
373 		case MPG123_FEEDBUFFER:
374 #ifndef NO_FEEDER
375 			*val = mp->feedbuffer;
376 #else
377 			ret = MPG123_MISSING_FEATURE;
378 #endif
379 		break;
380 		case MPG123_FREEFORMAT_SIZE:
381 			*val = mp->freeformat_framesize;
382 		break;
383 		default:
384 			ret = MPG123_BAD_PARAM;
385 	}
386 	return ret;
387 }
388 
mpg123_getpar2(mpg123_pars * mp,int key,long * val,double * fval)389 int attribute_align_arg mpg123_getpar2(mpg123_pars *mp, int key, long *val, double *fval)
390 {
391 	return mpg123_getpar(mp, key, val, fval);
392 }
393 
mpg123_getstate(mpg123_handle * mh,enum mpg123_state key,long * val,double * fval)394 int attribute_align_arg mpg123_getstate(mpg123_handle *mh, enum mpg123_state key, long *val, double *fval)
395 {
396 	int ret = MPG123_OK;
397 	long theval = 0;
398 	double thefval = 0.;
399 
400 	if(mh == NULL) return MPG123_BAD_HANDLE;
401 
402 	switch(key)
403 	{
404 		case MPG123_ACCURATE:
405 			theval = mh->state_flags & FRAME_ACCURATE;
406 		break;
407 		case MPG123_FRANKENSTEIN:
408 			theval = mh->state_flags & FRAME_FRANKENSTEIN;
409 		break;
410 		case MPG123_BUFFERFILL:
411 #ifndef NO_FEEDER
412 		{
413 			size_t sval = bc_fill(&mh->rdat.buffer);
414 			theval = (long)sval;
415 			if(theval < 0 || (size_t)theval != sval)
416 			{
417 				mh->err = MPG123_INT_OVERFLOW;
418 				ret = MPG123_ERR;
419 			}
420 		}
421 #else
422 			mh->err = MPG123_MISSING_FEATURE;
423 			ret = MPG123_ERR;
424 #endif
425 		break;
426 		case MPG123_FRESH_DECODER:
427 			theval = mh->state_flags & FRAME_FRESH_DECODER;
428 			mh->state_flags &= ~FRAME_FRESH_DECODER;
429 		break;
430 		case MPG123_ENC_DELAY:
431 			theval = mh->enc_delay;
432 		break;
433 		case MPG123_ENC_PADDING:
434 			theval = mh->enc_padding;
435 		break;
436 		case MPG123_DEC_DELAY:
437 			theval = mh->lay == 3 ? GAPLESS_DELAY : -1;
438 		break;
439 		default:
440 			mh->err = MPG123_BAD_KEY;
441 			ret = MPG123_ERR;
442 	}
443 
444 	if(val  != NULL) *val  = theval;
445 	if(fval != NULL) *fval = thefval;
446 
447 	return ret;
448 }
449 
mpg123_getstate2(mpg123_handle * mh,int key,long * val,double * fval)450 int attribute_align_arg mpg123_getstate2(mpg123_handle *mh, int key, long *val, double *fval)
451 {
452 	return mpg123_getstate(mh, key, val, fval);
453 }
454 
mpg123_eq(mpg123_handle * mh,enum mpg123_channels channel,int band,double val)455 int attribute_align_arg mpg123_eq(mpg123_handle *mh, enum mpg123_channels channel, int band, double val)
456 {
457 #ifndef NO_EQUALIZER
458 	if(mh == NULL) return MPG123_BAD_HANDLE;
459 	if(band < 0 || band > 31){ mh->err = MPG123_BAD_BAND; return MPG123_ERR; }
460 	switch(channel)
461 	{
462 		case MPG123_LEFT|MPG123_RIGHT:
463 			mh->equalizer[0][band] = mh->equalizer[1][band] = DOUBLE_TO_REAL(val);
464 		break;
465 		case MPG123_LEFT:  mh->equalizer[0][band] = DOUBLE_TO_REAL(val); break;
466 		case MPG123_RIGHT: mh->equalizer[1][band] = DOUBLE_TO_REAL(val); break;
467 		default:
468 			mh->err=MPG123_BAD_CHANNEL;
469 			return MPG123_ERR;
470 	}
471 	mh->have_eq_settings = TRUE;
472 #endif
473 	return MPG123_OK;
474 }
475 
mpg123_eq2(mpg123_handle * mh,int channel,int band,double val)476 int attribute_align_arg mpg123_eq2(mpg123_handle *mh, int channel, int band, double val)
477 {
478 	return mpg123_eq(mh, channel, band, val);
479 }
480 
mpg123_geteq(mpg123_handle * mh,enum mpg123_channels channel,int band)481 double attribute_align_arg mpg123_geteq(mpg123_handle *mh, enum mpg123_channels channel, int band)
482 {
483 	double ret = 0.;
484 #ifndef NO_EQUALIZER
485 
486 	/* Handle this gracefully. When there is no band, it has no volume. */
487 	if(mh != NULL && band > -1 && band < 32)
488 	switch(channel)
489 	{
490 		case MPG123_LEFT|MPG123_RIGHT:
491 			ret = 0.5*(REAL_TO_DOUBLE(mh->equalizer[0][band])+REAL_TO_DOUBLE(mh->equalizer[1][band]));
492 		break;
493 		case MPG123_LEFT:  ret = REAL_TO_DOUBLE(mh->equalizer[0][band]); break;
494 		case MPG123_RIGHT: ret = REAL_TO_DOUBLE(mh->equalizer[1][band]); break;
495 		/* Default case is already handled: ret = 0 */
496 	}
497 #endif
498 	return ret;
499 }
500 
mpg123_geteq2(mpg123_handle * mh,int channel,int band)501 double attribute_align_arg mpg123_geteq2(mpg123_handle *mh, int channel, int band)
502 {
503 	return mpg123_geteq(mh, channel, band);
504 }
505 
506 /* plain file access, no http! */
mpg123_open(mpg123_handle * mh,const char * path)507 int attribute_align_arg mpg123_open(mpg123_handle *mh, const char *path)
508 {
509 	if(mh == NULL) return MPG123_BAD_HANDLE;
510 
511 	mpg123_close(mh);
512 	return open_stream(mh, path, -1);
513 }
514 
515 // The convenience function mpg123_open_fixed() wraps over acual mpg123_open
516 // and hence needs to have the exact same code in lfs_wrap.c. The flesh is
517 // in open_fixed_pre() and open_fixed_post(), wich are only defined here.
open_fixed_pre(mpg123_handle * mh,int channels,int encoding)518 int open_fixed_pre(mpg123_handle *mh, int channels, int encoding)
519 {
520 	if(!mh)
521 		return MPG123_BAD_HANDLE;
522 	mh->p.flags |= MPG123_NO_FRANKENSTEIN;
523 	int err = mpg123_format_none(mh);
524 	if(err == MPG123_OK)
525 		err = mpg123_format2(mh, 0, channels, encoding);
526 	return err;
527 }
528 
open_fixed_post(mpg123_handle * mh,int channels,int encoding)529 int open_fixed_post(mpg123_handle *mh, int channels, int encoding)
530 {
531 	if(!mh)
532 		return MPG123_BAD_HANDLE;
533 	long rate;
534 	int err = mpg123_getformat(mh, &rate, &channels, &encoding);
535 	if(err == MPG123_OK)
536 		err = mpg123_format_none(mh);
537 	if(err == MPG123_OK)
538 		err = mpg123_format(mh, rate, channels, encoding);
539 	if(err == MPG123_OK)
540 	{
541 		if(mh->track_frames < 1 && (mh->rdat.flags & READER_SEEKABLE))
542 		{
543 			debug("open_fixed_post: scan because we can seek and do not know track_frames");
544 			err = mpg123_scan(mh);
545 		}
546 	}
547 	if(err != MPG123_OK)
548 		mpg123_close(mh);
549 	return err;
550 }
551 
mpg123_open_fixed(mpg123_handle * mh,const char * path,int channels,int encoding)552 int attribute_align_arg mpg123_open_fixed( mpg123_handle *mh, const char *path
553 ,	int channels, int encoding )
554 {
555 	int err = open_fixed_pre(mh, channels, encoding);
556 	if(err == MPG123_OK)
557 		err = mpg123_open(mh, path);
558 	if(err == MPG123_OK)
559 		err = open_fixed_post(mh, channels, encoding);
560 	return err;
561 }
562 
mpg123_open_fd(mpg123_handle * mh,int fd)563 int attribute_align_arg mpg123_open_fd(mpg123_handle *mh, int fd)
564 {
565 	if(mh == NULL) return MPG123_BAD_HANDLE;
566 
567 	mpg123_close(mh);
568 	return open_stream(mh, NULL, fd);
569 }
570 
mpg123_open_handle(mpg123_handle * mh,void * iohandle)571 int attribute_align_arg mpg123_open_handle(mpg123_handle *mh, void *iohandle)
572 {
573 	if(mh == NULL) return MPG123_BAD_HANDLE;
574 
575 	mpg123_close(mh);
576 	if(mh->rdat.r_read_handle == NULL)
577 	{
578 		mh->err = MPG123_BAD_CUSTOM_IO;
579 		return MPG123_ERR;
580 	}
581 	return open_stream_handle(mh, iohandle);
582 }
583 
mpg123_open_feed(mpg123_handle * mh)584 int attribute_align_arg mpg123_open_feed(mpg123_handle *mh)
585 {
586 	if(mh == NULL) return MPG123_BAD_HANDLE;
587 
588 	mpg123_close(mh);
589 	return open_feed(mh);
590 }
591 
mpg123_replace_reader(mpg123_handle * mh,ssize_t (* r_read)(int,void *,size_t),off_t (* r_lseek)(int,off_t,int))592 int attribute_align_arg mpg123_replace_reader( mpg123_handle *mh,
593                            ssize_t (*r_read) (int, void *, size_t),
594                            off_t   (*r_lseek)(int, off_t, int) )
595 {
596 	if(mh == NULL) return MPG123_BAD_HANDLE;
597 
598 	mpg123_close(mh);
599 	mh->rdat.r_read = r_read;
600 	mh->rdat.r_lseek = r_lseek;
601 	return MPG123_OK;
602 }
603 
mpg123_replace_reader_handle(mpg123_handle * mh,ssize_t (* r_read)(void *,void *,size_t),off_t (* r_lseek)(void *,off_t,int),void (* cleanup)(void *))604 int attribute_align_arg mpg123_replace_reader_handle( mpg123_handle *mh,
605                            ssize_t (*r_read) (void*, void *, size_t),
606                            off_t   (*r_lseek)(void*, off_t, int),
607                            void    (*cleanup)(void*)  )
608 {
609 	if(mh == NULL) return MPG123_BAD_HANDLE;
610 
611 	mpg123_close(mh);
612 	mh->rdat.r_read_handle = r_read;
613 	mh->rdat.r_lseek_handle = r_lseek;
614 	mh->rdat.cleanup_handle = cleanup;
615 	return MPG123_OK;
616 }
617 
618 /* Update decoding engine for
619    a) a new choice of decoder
620    b) a changed native format of the MPEG stream
621    ... calls are only valid after parsing some MPEG frame! */
decode_update(mpg123_handle * mh)622 int decode_update(mpg123_handle *mh)
623 {
624 	long native_rate;
625 	int b;
626 
627 	mh->state_flags &= ~FRAME_DECODER_LIVE;
628 	if(mh->num < 0)
629 	{
630 		if(!(mh->p.flags & MPG123_QUIET)) error("decode_update() has been called before reading the first MPEG frame! Internal programming error.");
631 
632 		mh->err = MPG123_BAD_DECODER_SETUP;
633 		return MPG123_ERR;
634 	}
635 
636 	mh->state_flags |= FRAME_FRESH_DECODER;
637 	native_rate = frame_freq(mh);
638 
639 	b = frame_output_format(mh); /* Select the new output format based on given constraints. */
640 	if(b < 0) return MPG123_ERR;
641 
642 	if(b == 1) mh->new_format = 1; /* Store for later... */
643 
644 	debug3("updating decoder structure with native rate %li and af.rate %li (new format: %i)", native_rate, mh->af.rate, mh->new_format);
645 	if(mh->af.rate == native_rate) mh->down_sample = 0;
646 	else if(mh->af.rate == native_rate>>1) mh->down_sample = 1;
647 	else if(mh->af.rate == native_rate>>2) mh->down_sample = 2;
648 	else mh->down_sample = 3; /* flexible (fixed) rate */
649 	switch(mh->down_sample)
650 	{
651 		case 0:
652 		case 1:
653 		case 2:
654 			mh->down_sample_sblimit = SBLIMIT>>(mh->down_sample);
655 			/* With downsampling I get less samples per frame */
656 			mh->outblock = outblock_bytes(mh, (mh->spf>>mh->down_sample));
657 		break;
658 #ifndef NO_NTOM
659 		case 3:
660 		{
661 			if(synth_ntom_set_step(mh) != 0) return -1;
662 			if(frame_freq(mh) > mh->af.rate)
663 			{
664 				mh->down_sample_sblimit = SBLIMIT * mh->af.rate;
665 				mh->down_sample_sblimit /= frame_freq(mh);
666 				if(mh->down_sample_sblimit < 1)
667 					mh->down_sample_sblimit = 1;
668 			}
669 			else mh->down_sample_sblimit = SBLIMIT;
670 			mh->outblock = outblock_bytes(mh,
671 			                 ( ( NTOM_MUL-1+mh->spf
672 			                   * (((size_t)NTOM_MUL*mh->af.rate)/frame_freq(mh))
673 			                 )/NTOM_MUL ));
674 		}
675 		break;
676 #endif
677 	}
678 
679 	if(!(mh->p.flags & MPG123_FORCE_MONO))
680 	{
681 		if(mh->af.channels == 1) mh->single = SINGLE_MIX;
682 		else mh->single = SINGLE_STEREO;
683 	}
684 	else mh->single = (mh->p.flags & MPG123_FORCE_MONO)-1;
685 	if(set_synth_functions(mh) != 0) return -1;;
686 
687 	/* The needed size of output buffer may have changed. */
688 	if(frame_outbuffer(mh) != MPG123_OK) return -1;
689 
690 	do_rva(mh);
691 	debug3("done updating decoder structure with native rate %li and af.rate %li and down_sample %i", frame_freq(mh), mh->af.rate, mh->down_sample);
692 
693 	mh->decoder_change = 0;
694 	mh->state_flags |= FRAME_DECODER_LIVE;
695 	return 0;
696 }
697 
mpg123_safe_buffer(void)698 size_t attribute_align_arg mpg123_safe_buffer(void)
699 {
700 	/* real is the largest possible output (it's 32bit float, 32bit int or 64bit double). */
701 	return sizeof(real)*2*1152*NTOM_MAX;
702 }
703 
mpg123_outblock(mpg123_handle * mh)704 size_t attribute_align_arg mpg123_outblock(mpg123_handle *mh)
705 {
706 	/* Try to be helpful and never return zero output block size. */
707 	if(mh != NULL && mh->outblock > 0) return mh->outblock;
708 	else return mpg123_safe_buffer();
709 }
710 
711 /* Read in the next frame we actually want for decoding.
712    This includes skipping/ignoring frames, in additon to skipping junk in the parser. */
get_next_frame(mpg123_handle * mh)713 static int get_next_frame(mpg123_handle *mh)
714 {
715 	int change = mh->decoder_change;
716 	/* Ensure we got proper decoder for ignoring frames.
717 	   Header can be changed from seeking around. But be careful: Only after at
718 	   least one frame got read, decoder update makes sense. */
719 	if(mh->header_change > 1 && mh->num >= 0)
720 	{
721 		change = 1;
722 		mh->header_change = 0;
723 		debug("starting with big header change");
724 		if(decode_update(mh) < 0)
725 		return MPG123_ERR;
726 	}
727 
728 	do
729 	{
730 		int b;
731 		/* Decode & discard some frame(s) before beginning. */
732 		if(mh->to_ignore && mh->num < mh->firstframe && mh->num >= mh->ignoreframe)
733 		{
734 			debug1("ignoring frame %li", (long)mh->num);
735 			/* Decoder structure must be current! decode_update has been called before... */
736 			(mh->do_layer)(mh); mh->buffer.fill = 0;
737 #ifndef NO_NTOM
738 			/* The ignored decoding may have failed. Make sure ntom stays consistent. */
739 			if(mh->down_sample == 3) ntom_set_ntom(mh, mh->num+1);
740 #endif
741 			mh->to_ignore = mh->to_decode = FALSE;
742 		}
743 		/* Read new frame data; possibly breaking out here for MPG123_NEED_MORE. */
744 		debug("read frame");
745 		mh->to_decode = FALSE;
746 		b = read_frame(mh); /* That sets to_decode only if a full frame was read. */
747 		debug4("read of frame %li returned %i (to_decode=%i) at sample %li", (long)mh->num, b, mh->to_decode, (long)mpg123_tell(mh));
748 		if(b == MPG123_NEED_MORE) return MPG123_NEED_MORE; /* need another call with data */
749 		else if(b <= 0)
750 		{
751 			/* More sophisticated error control? */
752 			if(b==0 || (mh->rdat.filelen >= 0 && mh->rdat.filepos == mh->rdat.filelen))
753 			{ /* We simply reached the end. */
754 				mh->track_frames = mh->num + 1;
755 				debug("What about updating/checking gapless sample count here?");
756 				return MPG123_DONE;
757 			}
758 			else return MPG123_ERR; /* Some real error. */
759 		}
760 		/* Now, there should be new data to decode ... and also possibly new stream properties */
761 		if(mh->header_change > 1 || mh->decoder_change)
762 		{
763 			debug("big header or decoder change");
764 			change = 1;
765 			mh->header_change = 0;
766 			/* Need to update decoder structure right away since frame might need to
767 			   be decoded on next loop iteration for properly ignoring its output. */
768 			if(decode_update(mh) < 0)
769 			return MPG123_ERR;
770 		}
771 		/* Now some accounting: Look at the numbers and decide if we want this frame. */
772 		++mh->playnum;
773 		/* Plain skipping without decoding, only when frame is not ignored on next cycle. */
774 		if(mh->num < mh->firstframe || (mh->p.doublespeed && (mh->playnum % mh->p.doublespeed)))
775 		{
776 			if(!(mh->to_ignore && mh->num < mh->firstframe && mh->num >= mh->ignoreframe))
777 			{
778 				frame_skip(mh);
779 				/* Should one fix NtoM here or not?
780 				   It is not work the trouble for doublespeed, but what with leading frames? */
781 			}
782 		}
783 		/* Or, we are finally done and have a new frame. */
784 		else break;
785 	} while(1);
786 
787 	/* If we reach this point, we got a new frame ready to be decoded.
788 	   All other situations resulted in returns from the loop. */
789 	if(change)
790 	{
791 		if(mh->fresh)
792 		{
793 #ifdef GAPLESS
794 			int b=0;
795 			/* Prepare offsets for gapless decoding. */
796 			debug1("preparing gapless stuff with native rate %li", frame_freq(mh));
797 			frame_gapless_realinit(mh);
798 			frame_set_frameseek(mh, mh->num);
799 #endif
800 			mh->fresh = 0;
801 #ifdef GAPLESS
802 			/* Could this possibly happen? With a real big gapless offset... */
803 			if(mh->num < mh->firstframe) b = get_next_frame(mh);
804 			if(b < 0) return b; /* Could be error, need for more, new format... */
805 #endif
806 		}
807 	}
808 	return MPG123_OK;
809 }
810 
811 /* Assumption: A buffer full of zero samples can be constructed by repetition of this byte.
812    Oh, and it handles some format conversion.
813    Only to be used by decode_the_frame() ... */
zero_byte(mpg123_handle * fr)814 static int zero_byte(mpg123_handle *fr)
815 {
816 #ifndef NO_8BIT
817 	return fr->af.encoding & MPG123_ENC_8 ? fr->conv16to8[0] : 0;
818 #else
819 	return 0; /* All normal signed formats have the zero here (even in byte form -- that may be an assumption for your funny machine...). */
820 #endif
821 }
822 
823 /*
824 	Not part of the api. This just decodes the frame and fills missing bits with zeroes.
825 	There can be frames that are broken and thus make do_layer() fail.
826 */
decode_the_frame(mpg123_handle * fr)827 static void decode_the_frame(mpg123_handle *fr)
828 {
829 	size_t needed_bytes = decoder_synth_bytes(fr, frame_expect_outsamples(fr));
830 	fr->clip += (fr->do_layer)(fr);
831 	/*fprintf(stderr, "frame %"OFF_P": got %"SIZE_P" / %"SIZE_P"\n", fr->num,(size_p)fr->buffer.fill, (size_p)needed_bytes);*/
832 	/* There could be less data than promised.
833 	   Also, then debugging, we look out for coding errors that could result in _more_ data than expected. */
834 #ifdef DEBUG
835 	if(fr->buffer.fill != needed_bytes)
836 	{
837 #endif
838 		if(fr->buffer.fill < needed_bytes)
839 		{
840 			if(VERBOSE2)
841 			fprintf(stderr, "Note: broken frame %li, filling up with %"SIZE_P" zeroes, from %"SIZE_P"\n", (long)fr->num, (size_p)(needed_bytes-fr->buffer.fill), (size_p)fr->buffer.fill);
842 
843 			/*
844 				One could do a loop with individual samples instead... but zero is zero
845 				Actually, that is wrong: zero is mostly a series of null bytes,
846 				but we have funny 8bit formats that have a different opinion on zero...
847 				Unsigned 16 or 32 bit formats are handled later.
848 			*/
849 			memset( fr->buffer.data + fr->buffer.fill, zero_byte(fr), needed_bytes - fr->buffer.fill );
850 
851 			fr->buffer.fill = needed_bytes;
852 #ifndef NO_NTOM
853 			/* ntom_val will be wrong when the decoding wasn't carried out completely */
854 			ntom_set_ntom(fr, fr->num+1);
855 #endif
856 		}
857 #ifdef DEBUG
858 		else
859 		{
860 			if(NOQUIET)
861 			error2("I got _more_ bytes than expected (%"SIZE_P" / %"SIZE_P"), that should not be possible!", (size_p)fr->buffer.fill, (size_p)needed_bytes);
862 		}
863 	}
864 #endif
865 	postprocess_buffer(fr);
866 }
867 
868 /*
869 	Decode the current frame into the frame structure's buffer, accessible at the location stored in <audio>, with <bytes> bytes available.
870 	<num> will contain the last decoded frame number. This function should be called after mpg123_framebyframe_next positioned the stream at a
871 	valid mp3 frame. The buffer contents will get lost on the next call to mpg123_framebyframe_next or mpg123_framebyframe_decode.
872 	returns
873 	MPG123_OK -- successfully decoded or ignored the frame, you get your output data or in case of ignored frames 0 bytes
874 	MPG123_DONE -- decoding finished, should not happen
875 	MPG123_ERR -- some error occured.
876 	MPG123_ERR_NULL -- audio or bytes are not pointing to valid storage addresses
877 	MPG123_BAD_HANDLE -- mh has not been initialized
878 	MPG123_NO_SPACE -- not enough space in buffer for safe decoding, should not happen
879 */
mpg123_framebyframe_decode(mpg123_handle * mh,off_t * num,unsigned char ** audio,size_t * bytes)880 int attribute_align_arg mpg123_framebyframe_decode(mpg123_handle *mh, off_t *num, unsigned char **audio, size_t *bytes)
881 {
882 	if(bytes == NULL) return MPG123_ERR_NULL;
883 	if(audio == NULL) return MPG123_ERR_NULL;
884 	if(mh == NULL)    return MPG123_BAD_HANDLE;
885 	if(mh->buffer.size < mh->outblock) return MPG123_NO_SPACE;
886 
887 	*audio = NULL;
888 	*bytes = 0;
889 	mh->buffer.fill = 0; /* always start fresh */
890 	if(!mh->to_decode) return MPG123_OK;
891 
892 	if(num != NULL) *num = mh->num;
893 	debug("decoding");
894 	if(!(mh->state_flags & FRAME_DECODER_LIVE))
895 		return MPG123_ERR;
896 	decode_the_frame(mh);
897 	mh->to_decode = mh->to_ignore = FALSE;
898 	mh->buffer.p = mh->buffer.data;
899 	FRAME_BUFFERCHECK(mh);
900 	*audio = mh->buffer.p;
901 	*bytes = mh->buffer.fill;
902 	return MPG123_OK;
903 }
904 
905 /*
906 	Find, read and parse the next mp3 frame while skipping junk and parsing id3 tags, lame headers, etc.
907 	Prepares everything for decoding using mpg123_framebyframe_decode.
908 	returns
909 	MPG123_OK -- new frame was read and parsed, call mpg123_framebyframe_decode to actually decode
910 	MPG123_NEW_FORMAT -- new frame was read, it results in changed output format, call mpg123_framebyframe_decode to actually decode
911 	MPG123_BAD_HANDLE -- mh has not been initialized
912 	MPG123_NEED_MORE  -- more input data is needed to advance to the next frame. supply more input data using mpg123_feed
913 */
mpg123_framebyframe_next(mpg123_handle * mh)914 int attribute_align_arg mpg123_framebyframe_next(mpg123_handle *mh)
915 {
916 	int b;
917 	if(mh == NULL) return MPG123_BAD_HANDLE;
918 
919 	mh->to_decode = mh->to_ignore = FALSE;
920 	mh->buffer.fill = 0;
921 
922 	b = get_next_frame(mh);
923 	if(b < 0) return b;
924 	debug1("got next frame, %i", mh->to_decode);
925 
926 	/* mpg123_framebyframe_decode will return MPG123_OK with 0 bytes decoded if mh->to_decode is 0 */
927 	if(!mh->to_decode)
928 		return MPG123_OK;
929 
930 	if(mh->new_format)
931 	{
932 		debug("notifiying new format");
933 		mh->new_format = 0;
934 		return MPG123_NEW_FORMAT;
935 	}
936 
937 	return MPG123_OK;
938 }
939 
940 /*
941 	Put _one_ decoded frame into the frame structure's buffer, accessible at the location stored in <audio>, with <bytes> bytes available.
942 	The buffer contents will be lost on next call to mpg123_decode_frame.
943 	MPG123_OK -- successfully decoded the frame, you get your output data
944 	MPg123_DONE -- This is it. End.
945 	MPG123_ERR -- some error occured...
946 	MPG123_NEW_FORMAT -- new frame was read, it results in changed output format -> will be decoded on next call
947 	MPG123_NEED_MORE  -- that should not happen as this function is intended for in-library stream reader but if you force it...
948 	MPG123_NO_SPACE   -- not enough space in buffer for safe decoding, also should not happen
949 
950 	num will be updated to the last decoded frame number (may possibly _not_ increase, p.ex. when format changed).
951 */
mpg123_decode_frame(mpg123_handle * mh,off_t * num,unsigned char ** audio,size_t * bytes)952 int attribute_align_arg mpg123_decode_frame(mpg123_handle *mh, off_t *num, unsigned char **audio, size_t *bytes)
953 {
954 	if(bytes != NULL) *bytes = 0;
955 	if(mh == NULL) return MPG123_BAD_HANDLE;
956 	if(mh->buffer.size < mh->outblock) return MPG123_NO_SPACE;
957 	mh->buffer.fill = 0; /* always start fresh */
958 	/* Be nice: Set these also for sensible values in case of error. */
959 	if(audio) *audio = NULL;
960 	if(bytes) *bytes = 0;
961 	while(TRUE)
962 	{
963 		/* decode if possible */
964 		if(mh->to_decode)
965 		{
966 			if(num != NULL) *num = mh->num;
967 			if(mh->new_format)
968 			{
969 				debug("notifiying new format");
970 				mh->new_format = 0;
971 				return MPG123_NEW_FORMAT;
972 			}
973 			debug("decoding");
974 
975 			if( (mh->decoder_change && decode_update(mh) < 0)
976 			||	!(mh->state_flags & FRAME_DECODER_LIVE) )
977 				return MPG123_ERR;
978 			decode_the_frame(mh);
979 
980 			mh->to_decode = mh->to_ignore = FALSE;
981 			mh->buffer.p = mh->buffer.data;
982 			FRAME_BUFFERCHECK(mh);
983 			if(audio != NULL) *audio = mh->buffer.p;
984 			if(bytes != NULL) *bytes = mh->buffer.fill;
985 
986 			return MPG123_OK;
987 		}
988 		else
989 		{
990 			int b = get_next_frame(mh);
991 			if(b < 0) return b;
992 			debug1("got next frame, %i", mh->to_decode);
993 		}
994 	}
995 }
996 
mpg123_read(mpg123_handle * mh,void * out,size_t size,size_t * done)997 int attribute_align_arg mpg123_read(mpg123_handle *mh, void *out, size_t size, size_t *done)
998 {
999 	return mpg123_decode(mh, NULL, 0, out, size, done);
1000 }
1001 
mpg123_feed(mpg123_handle * mh,const unsigned char * in,size_t size)1002 int attribute_align_arg mpg123_feed(mpg123_handle *mh, const unsigned char *in, size_t size)
1003 {
1004 	if(mh == NULL) return MPG123_BAD_HANDLE;
1005 #ifndef NO_FEEDER
1006 	if(size > 0)
1007 	{
1008 		if(in != NULL)
1009 		{
1010 			if(feed_more(mh, in, size) != 0) return MPG123_ERR;
1011 			else
1012 			{
1013 				/* The need for more data might have triggered an error.
1014 				   This one is outdated now with the new data. */
1015 				if(mh->err == MPG123_ERR_READER) mh->err = MPG123_OK;
1016 
1017 				return MPG123_OK;
1018 			}
1019 		}
1020 		else
1021 		{
1022 			mh->err = MPG123_NULL_BUFFER;
1023 			return MPG123_ERR;
1024 		}
1025 	}
1026 	return MPG123_OK;
1027 #else
1028 	mh->err = MPG123_MISSING_FEATURE;
1029 	return MPG123_ERR;
1030 #endif
1031 }
1032 
1033 /*
1034 	The old picture:
1035 	while(1) {
1036 		len = read(0,buf,16384);
1037 		if(len <= 0)
1038 			break;
1039 		ret = decodeMP3(&mp,buf,len,out,8192,&size);
1040 		while(ret == MP3_OK) {
1041 			write(1,out,size);
1042 			ret = decodeMP3(&mp,NULL,0,out,8192,&size);
1043 		}
1044 	}
1045 */
1046 
mpg123_decode(mpg123_handle * mh,const unsigned char * inmemory,size_t inmemsize,void * outmem,size_t outmemsize,size_t * done)1047 int attribute_align_arg mpg123_decode(mpg123_handle *mh, const unsigned char *inmemory, size_t inmemsize, void *outmem, size_t outmemsize, size_t *done)
1048 {
1049 	int ret = MPG123_OK;
1050 	size_t mdone = 0;
1051 	unsigned char *outmemory = outmem;
1052 
1053 	if(done != NULL) *done = 0;
1054 	if(mh == NULL) return MPG123_BAD_HANDLE;
1055 	if(inmemsize > 0 && mpg123_feed(mh, inmemory, inmemsize) != MPG123_OK)
1056 	{
1057 		ret = MPG123_ERR;
1058 		goto decodeend;
1059 	}
1060 	if(outmemory == NULL) outmemsize = 0; /* Not just give error, give chance to get a status message. */
1061 
1062 	while(ret == MPG123_OK)
1063 	{
1064 		debug4("decode loop, fill %i (%li vs. %li); to_decode: %i", (int)mh->buffer.fill, (long)mh->num, (long)mh->firstframe, mh->to_decode);
1065 		/* Decode a frame that has been read before.
1066 		   This only happens when buffer is empty! */
1067 		if(mh->to_decode)
1068 		{
1069 			if(mh->new_format)
1070 			{
1071 				debug("notifiying new format");
1072 				mh->new_format = 0;
1073 				ret = MPG123_NEW_FORMAT;
1074 				goto decodeend;
1075 			}
1076 			if(mh->buffer.size - mh->buffer.fill < mh->outblock)
1077 			{
1078 				ret = MPG123_NO_SPACE;
1079 				goto decodeend;
1080 			}
1081 			if( (mh->decoder_change && decode_update(mh) < 0)
1082 			||	! (mh->state_flags & FRAME_DECODER_LIVE) )
1083 			{
1084 				ret = MPG123_ERR;
1085 				goto decodeend;
1086 			}
1087 			decode_the_frame(mh);
1088 			mh->to_decode = mh->to_ignore = FALSE;
1089 			mh->buffer.p = mh->buffer.data;
1090 			debug2("decoded frame %li, got %li samples in buffer", (long)mh->num, (long)(mh->buffer.fill / (samples_to_bytes(mh, 1))));
1091 			FRAME_BUFFERCHECK(mh);
1092 		}
1093 		if(mh->buffer.fill) /* Copy (part of) the decoded data to the caller's buffer. */
1094 		{
1095 			/* get what is needed - or just what is there */
1096 			int a = mh->buffer.fill > (outmemsize - mdone) ? outmemsize - mdone : mh->buffer.fill;
1097 			debug4("buffer fill: %i; copying %i (%i - %li)", (int)mh->buffer.fill, a, (int)outmemsize, (long)mdone);
1098 			memcpy(outmemory, mh->buffer.p, a);
1099 			/* less data in frame buffer, less needed, output pointer increase, more data given... */
1100 			mh->buffer.fill -= a;
1101 			outmemory  += a;
1102 			mdone += a;
1103 			mh->buffer.p += a;
1104 			if(!(outmemsize > mdone)) goto decodeend;
1105 		}
1106 		else /* If we didn't have data, get a new frame. */
1107 		{
1108 			int b = get_next_frame(mh);
1109 			if(b < 0){ ret = b; goto decodeend; }
1110 		}
1111 	}
1112 decodeend:
1113 	if(done != NULL) *done = mdone;
1114 	return ret;
1115 }
1116 
mpg123_clip(mpg123_handle * mh)1117 long attribute_align_arg mpg123_clip(mpg123_handle *mh)
1118 {
1119 	long ret = 0;
1120 
1121 	if(mh != NULL)
1122 	{
1123 		ret = mh->clip;
1124 		mh->clip = 0;
1125 	}
1126 	return ret;
1127 }
1128 
1129 /* Simples: Track needs initializtion if no initial frame has been read yet. */
1130 #define track_need_init(mh) ((mh)->num < 0)
1131 
init_track(mpg123_handle * mh)1132 static int init_track(mpg123_handle *mh)
1133 {
1134 	if(track_need_init(mh))
1135 	{
1136 		/* Fresh track, need first frame for basic info. */
1137 		int b = get_next_frame(mh);
1138 		if(b < 0) return b;
1139 	}
1140 	return 0;
1141 }
1142 
1143 // Duplicating the code for the changed member types in struct mpg123_frameinfo2.
1144 #define MPG123_INFO_FUNC \
1145 { \
1146 	int b; \
1147  \
1148 	if(mh == NULL) return MPG123_BAD_HANDLE; \
1149 	if(mi == NULL) \
1150 	{ \
1151 		mh->err = MPG123_ERR_NULL; \
1152 		return MPG123_ERR; \
1153 	} \
1154 	b = init_track(mh); \
1155 	if(b < 0) return b; \
1156  \
1157 	mi->version = mh->mpeg25 ? MPG123_2_5 : (mh->lsf ? MPG123_2_0 : MPG123_1_0); \
1158 	mi->layer = mh->lay; \
1159 	mi->rate = frame_freq(mh); \
1160 	switch(mh->mode) \
1161 	{ \
1162 		case 0: mi->mode = MPG123_M_STEREO; break; \
1163 		case 1: mi->mode = MPG123_M_JOINT;  break; \
1164 		case 2: mi->mode = MPG123_M_DUAL;   break; \
1165 		case 3: mi->mode = MPG123_M_MONO;   break; \
1166 		default: mi->mode = 0; /* Nothing good to do here. */ \
1167 	} \
1168 	mi->mode_ext = mh->mode_ext; \
1169 	mi->framesize = mh->framesize+4; /* Include header. */ \
1170 	mi->flags = 0; \
1171 	if(mh->error_protection) mi->flags |= MPG123_CRC; \
1172 	if(mh->copyright)        mi->flags |= MPG123_COPYRIGHT; \
1173 	if(mh->extension)        mi->flags |= MPG123_PRIVATE; \
1174 	if(mh->original)         mi->flags |= MPG123_ORIGINAL; \
1175 	mi->emphasis = mh->emphasis; \
1176 	mi->bitrate  = frame_bitrate(mh); \
1177 	mi->abr_rate = mh->abr_rate; \
1178 	mi->vbr = mh->vbr; \
1179 	return MPG123_OK; \
1180 }
1181 
mpg123_info(mpg123_handle * mh,struct mpg123_frameinfo * mi)1182 int attribute_align_arg mpg123_info(mpg123_handle *mh, struct mpg123_frameinfo *mi)
1183 MPG123_INFO_FUNC
1184 
1185 int attribute_align_arg mpg123_info2(mpg123_handle *mh, struct mpg123_frameinfo2 *mi)
1186 MPG123_INFO_FUNC
1187 
1188 int attribute_align_arg mpg123_getformat2( mpg123_handle *mh
1189 ,	long *rate, int *channels, int *encoding, int clear_flag )
1190 {
1191 	int b;
1192 
1193 	if(mh == NULL) return MPG123_BAD_HANDLE;
1194 	b = init_track(mh);
1195 	if(b < 0) return b;
1196 
1197 	if(rate != NULL) *rate = mh->af.rate;
1198 	if(channels != NULL) *channels = mh->af.channels;
1199 	if(encoding != NULL) *encoding = mh->af.encoding;
1200 	if(clear_flag) mh->new_format = 0;
1201 	return MPG123_OK;
1202 }
1203 
mpg123_getformat(mpg123_handle * mh,long * rate,int * channels,int * encoding)1204 int attribute_align_arg mpg123_getformat(mpg123_handle *mh, long *rate, int *channels, int *encoding)
1205 {
1206 	return mpg123_getformat2(mh, rate, channels, encoding, 1);
1207 }
1208 
mpg123_timeframe(mpg123_handle * mh,double seconds)1209 off_t attribute_align_arg mpg123_timeframe(mpg123_handle *mh, double seconds)
1210 {
1211 	off_t b;
1212 
1213 	if(mh == NULL) return MPG123_ERR;
1214 	b = init_track(mh);
1215 	if(b<0) return b;
1216 	return (off_t)(seconds/mpg123_tpf(mh));
1217 }
1218 
1219 /*
1220 	Now, where are we? We need to know the last decoded frame... and what's left of it in buffer.
1221 	The current frame number can mean the last decoded frame or the to-be-decoded frame.
1222 	If mh->to_decode, then mh->num frames have been decoded, the frame mh->num now coming next.
1223 	If not, we have the possibility of mh->num+1 frames being decoded or nothing at all.
1224 	Then, there is firstframe...when we didn't reach it yet, then the next data will come from there.
1225 	mh->num starts with -1
1226 */
mpg123_tell(mpg123_handle * mh)1227 off_t attribute_align_arg mpg123_tell(mpg123_handle *mh)
1228 {
1229 	if(mh == NULL) return MPG123_ERR;
1230 	if(track_need_init(mh)) return 0;
1231 	/* Now we have all the info at hand. */
1232 	debug5("tell: %li/%i first %li buffer %lu; frame_outs=%li", (long)mh->num, mh->to_decode, (long)mh->firstframe, (unsigned long)mh->buffer.fill, (long)frame_outs(mh, mh->num));
1233 
1234 	{ /* Funny block to keep C89 happy. */
1235 		off_t pos = 0;
1236 		if((mh->num < mh->firstframe) || (mh->num == mh->firstframe && mh->to_decode))
1237 		{ /* We are at the beginning, expect output from firstframe on. */
1238 			pos = frame_outs(mh, mh->firstframe);
1239 #ifdef GAPLESS
1240 			pos += mh->firstoff;
1241 #endif
1242 		}
1243 		else if(mh->to_decode)
1244 		{ /* We start fresh with this frame. Buffer should be empty, but we make sure to count it in.  */
1245 			pos = frame_outs(mh, mh->num) - bytes_to_samples(mh, mh->buffer.fill);
1246 		}
1247 		else
1248 		{ /* We serve what we have in buffer and then the beginning of next frame... */
1249 			pos = frame_outs(mh, mh->num+1) - bytes_to_samples(mh, mh->buffer.fill);
1250 		}
1251 		/* Substract padding and delay from the beginning. */
1252 		pos = SAMPLE_ADJUST(mh,pos);
1253 		/* Negative sample offsets are not right, less than nothing is still nothing. */
1254 		return pos>0 ? pos : 0;
1255 	}
1256 }
1257 
mpg123_tellframe(mpg123_handle * mh)1258 off_t attribute_align_arg mpg123_tellframe(mpg123_handle *mh)
1259 {
1260 	if(mh == NULL) return MPG123_ERR;
1261 	if(mh->num < mh->firstframe) return mh->firstframe;
1262 	if(mh->to_decode) return mh->num;
1263 	/* Consider firstoff? */
1264 	return mh->buffer.fill ? mh->num : mh->num + 1;
1265 }
1266 
mpg123_tell_stream(mpg123_handle * mh)1267 off_t attribute_align_arg mpg123_tell_stream(mpg123_handle *mh)
1268 {
1269 	if(mh == NULL) return MPG123_ERR;
1270 	/* mh->rd is at least a bad_reader, so no worry. */
1271 	return mh->rd->tell(mh);
1272 }
1273 
do_the_seek(mpg123_handle * mh)1274 static int do_the_seek(mpg123_handle *mh)
1275 {
1276 	int b;
1277 	off_t fnum = SEEKFRAME(mh);
1278 	mh->buffer.fill = 0;
1279 
1280 	/* If we are inside the ignoreframe - firstframe window, we may get away without actual seeking. */
1281 	if(mh->num < mh->firstframe)
1282 	{
1283 		mh->to_decode = FALSE; /* In any case, don't decode the current frame, perhaps ignore instead. */
1284 		if(mh->num > fnum) return MPG123_OK;
1285 	}
1286 
1287 	/* If we are already there, we are fine either for decoding or for ignoring. */
1288 	if(mh->num == fnum && (mh->to_decode || fnum < mh->firstframe)) return MPG123_OK;
1289 	/* We have the frame before... just go ahead as normal. */
1290 	if(mh->num == fnum-1)
1291 	{
1292 		mh->to_decode = FALSE;
1293 		return MPG123_OK;
1294 	}
1295 
1296 	/* OK, real seeking follows... clear buffers and go for it. */
1297 	frame_buffers_reset(mh);
1298 #ifndef NO_NTOM
1299 	if(mh->down_sample == 3)
1300 	{
1301 		ntom_set_ntom(mh, fnum);
1302 		debug3("fixed ntom for frame %"OFF_P" to %lu, num=%"OFF_P, (off_p)fnum, mh->ntom_val[0], (off_p)mh->num);
1303 	}
1304 #endif
1305 	b = mh->rd->seek_frame(mh, fnum);
1306 	if(mh->header_change > 1)
1307 	{
1308 		if(decode_update(mh) < 0) return MPG123_ERR;
1309 		mh->header_change = 0;
1310 	}
1311 	debug1("seek_frame returned: %i", b);
1312 	if(b<0) return b;
1313 	/* Only mh->to_ignore is TRUE. */
1314 	if(mh->num < mh->firstframe) mh->to_decode = FALSE;
1315 
1316 	mh->playnum = mh->num;
1317 	return 0;
1318 }
1319 
mpg123_seek(mpg123_handle * mh,off_t sampleoff,int whence)1320 off_t attribute_align_arg mpg123_seek(mpg123_handle *mh, off_t sampleoff, int whence)
1321 {
1322 	int b;
1323 	off_t pos;
1324 
1325 	pos = mpg123_tell(mh); /* adjusted samples */
1326 	/* pos < 0 also can mean that simply a former seek failed at the lower levels.
1327 	  In that case, we only allow absolute seeks. */
1328 	if(pos < 0 && whence != SEEK_SET)
1329 	{ /* Unless we got the obvious error of NULL handle, this is a special seek failure. */
1330 		if(mh != NULL) mh->err = MPG123_NO_RELSEEK;
1331 		return MPG123_ERR;
1332 	}
1333 	if((b=init_track(mh)) < 0) return b;
1334 	switch(whence)
1335 	{
1336 		case SEEK_CUR: pos += sampleoff; break;
1337 		case SEEK_SET: pos  = sampleoff; break;
1338 		case SEEK_END:
1339 			/* When we do not know the end already, we can try to find it. */
1340 			if(mh->track_frames < 1 && (mh->rdat.flags & READER_SEEKABLE))
1341 			mpg123_scan(mh);
1342 			if(mh->track_frames > 0) pos = SAMPLE_ADJUST(mh,frame_outs(mh, mh->track_frames)) - sampleoff;
1343 #ifdef GAPLESS
1344 			else if(mh->end_os > 0) pos = SAMPLE_ADJUST(mh,mh->end_os) - sampleoff;
1345 #endif
1346 			else
1347 			{
1348 				mh->err = MPG123_NO_SEEK_FROM_END;
1349 				return MPG123_ERR;
1350 			}
1351 		break;
1352 		default: mh->err = MPG123_BAD_WHENCE; return MPG123_ERR;
1353 	}
1354 	if(pos < 0) pos = 0;
1355 	/* pos now holds the wanted sample offset in adjusted samples */
1356 	frame_set_seek(mh, SAMPLE_UNADJUST(mh,pos));
1357 	pos = do_the_seek(mh);
1358 	if(pos < 0) return pos;
1359 
1360 	return mpg123_tell(mh);
1361 }
1362 
1363 /*
1364 	A bit more tricky... libmpg123 does not do the seeking itself.
1365 	All it can do is to ignore frames until the wanted one is there.
1366 	The caller doesn't know where a specific frame starts and mpg123 also only knows the general region after it scanned the file.
1367 	Well, it is tricky...
1368 */
mpg123_feedseek(mpg123_handle * mh,off_t sampleoff,int whence,off_t * input_offset)1369 off_t attribute_align_arg mpg123_feedseek(mpg123_handle *mh, off_t sampleoff, int whence, off_t *input_offset)
1370 {
1371 	int b;
1372 	off_t pos;
1373 
1374 	pos = mpg123_tell(mh); /* adjusted samples */
1375 	debug3("seek from %li to %li (whence=%i)", (long)pos, (long)sampleoff, whence);
1376 	/* The special seek error handling does not apply here... there is no lowlevel I/O. */
1377 	if(pos < 0) return pos; /* mh == NULL is covered in mpg123_tell() */
1378 #ifndef NO_FEEDER
1379 	if(input_offset == NULL)
1380 	{
1381 		mh->err = MPG123_NULL_POINTER;
1382 		return MPG123_ERR;
1383 	}
1384 
1385 	if((b=init_track(mh)) < 0) return b; /* May need more to do anything at all. */
1386 
1387 	switch(whence)
1388 	{
1389 		case SEEK_CUR: pos += sampleoff; break;
1390 		case SEEK_SET: pos  = sampleoff; break;
1391 		case SEEK_END:
1392 			if(mh->track_frames > 0) pos = SAMPLE_ADJUST(mh,frame_outs(mh, mh->track_frames)) - sampleoff;
1393 #ifdef GAPLESS
1394 			else if(mh->end_os >= 0) pos = SAMPLE_ADJUST(mh,mh->end_os) - sampleoff;
1395 #endif
1396 			else
1397 			{
1398 				mh->err = MPG123_NO_SEEK_FROM_END;
1399 				return MPG123_ERR;
1400 			}
1401 		break;
1402 		default: mh->err = MPG123_BAD_WHENCE; return MPG123_ERR;
1403 	}
1404 	if(pos < 0) pos = 0;
1405 	frame_set_seek(mh, SAMPLE_UNADJUST(mh,pos));
1406 	pos = SEEKFRAME(mh);
1407 	mh->buffer.fill = 0;
1408 
1409 	/* Shortcuts without modifying input stream. */
1410 	*input_offset = mh->rdat.buffer.fileoff + mh->rdat.buffer.size;
1411 	if(mh->num < mh->firstframe) mh->to_decode = FALSE;
1412 	if(mh->num == pos && mh->to_decode) goto feedseekend;
1413 	if(mh->num == pos-1) goto feedseekend;
1414 	/* Whole way. */
1415 	*input_offset = feed_set_pos(mh, frame_index_find(mh, SEEKFRAME(mh), &pos));
1416 	mh->num = pos-1; /* The next read frame will have num = pos. */
1417 	if(*input_offset < 0) return MPG123_ERR;
1418 
1419 feedseekend:
1420 	return mpg123_tell(mh);
1421 #else
1422 	mh->err = MPG123_MISSING_FEATURE;
1423 	return MPG123_ERR;
1424 #endif
1425 }
1426 
mpg123_seek_frame(mpg123_handle * mh,off_t offset,int whence)1427 off_t attribute_align_arg mpg123_seek_frame(mpg123_handle *mh, off_t offset, int whence)
1428 {
1429 	int b;
1430 	off_t pos = 0;
1431 
1432 	if(mh == NULL) return MPG123_ERR;
1433 	if((b=init_track(mh)) < 0) return b;
1434 
1435 	/* Could play games here with to_decode... */
1436 	pos = mh->num;
1437 	switch(whence)
1438 	{
1439 		case SEEK_CUR: pos += offset; break;
1440 		case SEEK_SET: pos  = offset; break;
1441 		case SEEK_END:
1442 			if(mh->track_frames > 0) pos = mh->track_frames - offset;
1443 			else
1444 			{
1445 				mh->err = MPG123_NO_SEEK_FROM_END;
1446 				return MPG123_ERR;
1447 			}
1448 		break;
1449 		default:
1450 			mh->err = MPG123_BAD_WHENCE;
1451 			return MPG123_ERR;
1452 	}
1453 	if(pos < 0) pos = 0;
1454 	/* Not limiting the possible position on end for the chance that there might be more to the stream than announced via track_frames. */
1455 
1456 	frame_set_frameseek(mh, pos);
1457 	pos = do_the_seek(mh);
1458 	if(pos < 0) return pos;
1459 
1460 	return mpg123_tellframe(mh);
1461 }
1462 
mpg123_set_filesize(mpg123_handle * mh,off_t size)1463 int attribute_align_arg mpg123_set_filesize(mpg123_handle *mh, off_t size)
1464 {
1465 	if(mh == NULL) return MPG123_BAD_HANDLE;
1466 
1467 	mh->rdat.filelen = size;
1468 	return MPG123_OK;
1469 }
1470 
mpg123_framelength(mpg123_handle * mh)1471 off_t attribute_align_arg mpg123_framelength(mpg123_handle *mh)
1472 {
1473 	int b;
1474 	if(mh == NULL)
1475 		return MPG123_ERR;
1476 	b = init_track(mh);
1477 	if(b<0)
1478 		return b;
1479 	if(mh->track_frames > 0)
1480 		return mh->track_frames;
1481 	if(mh->rdat.filelen > 0)
1482 	{ /* A bad estimate. Ignoring tags 'n stuff. */
1483 		double bpf = mh->mean_framesize > 0.
1484 			? mh->mean_framesize
1485 			: compute_bpf(mh);
1486 		return (off_t)((double)(mh->rdat.filelen)/bpf+0.5);
1487 	}
1488 	/* Last resort: No view of the future, can at least count the frames that
1489 	   were already parsed. */
1490 	if(mh->num > -1)
1491 		return mh->num+1;
1492 	/* Giving up. */
1493 	return MPG123_ERR;
1494 }
1495 
mpg123_length(mpg123_handle * mh)1496 off_t attribute_align_arg mpg123_length(mpg123_handle *mh)
1497 {
1498 	int b;
1499 	off_t length;
1500 
1501 	if(mh == NULL) return MPG123_ERR;
1502 	b = init_track(mh);
1503 	if(b<0) return b;
1504 	if(mh->track_samples > -1) length = mh->track_samples;
1505 	else if(mh->track_frames > 0) length = mh->track_frames*mh->spf;
1506 	else if(mh->rdat.filelen > 0) /* Let the case of 0 length just fall through. */
1507 	{
1508 		/* A bad estimate. Ignoring tags 'n stuff. */
1509 		double bpf = mh->mean_framesize ? mh->mean_framesize : compute_bpf(mh);
1510 		length = (off_t)((double)(mh->rdat.filelen)/bpf*mh->spf);
1511 	}
1512 	else if(mh->rdat.filelen == 0) return mpg123_tell(mh); /* we could be in feeder mode */
1513 	else return MPG123_ERR; /* No length info there! */
1514 
1515 	debug1("mpg123_length: internal sample length: %"OFF_P, (off_p)length);
1516 
1517 	length = frame_ins2outs(mh, length);
1518 	debug1("mpg123_length: external sample length: %"OFF_P, (off_p)length);
1519 	length = SAMPLE_ADJUST(mh,length);
1520 	return length;
1521 }
1522 
1523 
mpg123_scan(mpg123_handle * mh)1524 int attribute_align_arg mpg123_scan(mpg123_handle *mh)
1525 {
1526 	int b;
1527 	off_t oldpos;
1528 	off_t track_frames = 0;
1529 	off_t track_samples = 0;
1530 
1531 	if(mh == NULL) return MPG123_BAD_HANDLE;
1532 	if(!(mh->rdat.flags & READER_SEEKABLE)){ mh->err = MPG123_NO_SEEK; return MPG123_ERR; }
1533 	/* Scan through the _whole_ file, since the current position is no count but computed assuming constant samples per frame. */
1534 	/* Also, we can just keep the current buffer and seek settings. Just operate on input frames here. */
1535 	debug("issuing scan");
1536 	b = init_track(mh); /* mh->num >= 0 !! */
1537 	if(b<0)
1538 	{
1539 		if(b == MPG123_DONE) return MPG123_OK;
1540 		else return MPG123_ERR; /* Must be error here, NEED_MORE is not for seekable streams. */
1541 	}
1542 	oldpos = mpg123_tell(mh);
1543 	b = mh->rd->seek_frame(mh, 0);
1544 	if(b<0 || mh->num != 0) return MPG123_ERR;
1545 	/* One frame must be there now. */
1546 	track_frames = 1;
1547 	track_samples = mh->spf; /* Internal samples. */
1548 	debug("TODO: We should disable gapless code when encountering inconsistent mh->spf!");
1549 	debug("      ... at least unset MPG123_ACCURATE.");
1550 	/* Do not increment mh->track_frames in the loop as tha would confuse Frankenstein detection. */
1551 	while(read_frame(mh) == 1)
1552 	{
1553 		++track_frames;
1554 		track_samples += mh->spf;
1555 	}
1556 	mh->track_frames = track_frames;
1557 	mh->track_samples = track_samples;
1558 	debug2("Scanning yielded %"OFF_P" track samples, %"OFF_P" frames.", (off_p)mh->track_samples, (off_p)mh->track_frames);
1559 #ifdef GAPLESS
1560 	/* Also, think about usefulness of that extra value track_samples ... it could be used for consistency checking. */
1561 	if(mh->p.flags & MPG123_GAPLESS) frame_gapless_update(mh, mh->track_samples);
1562 #endif
1563 	return mpg123_seek(mh, oldpos, SEEK_SET) >= 0 ? MPG123_OK : MPG123_ERR;
1564 }
1565 
mpg123_meta_check(mpg123_handle * mh)1566 int attribute_align_arg mpg123_meta_check(mpg123_handle *mh)
1567 {
1568 	if(mh != NULL) return mh->metaflags;
1569 	else return 0;
1570 }
1571 
mpg123_meta_free(mpg123_handle * mh)1572 void attribute_align_arg mpg123_meta_free(mpg123_handle *mh)
1573 {
1574 	if(mh == NULL) return;
1575 
1576 	reset_id3(mh);
1577 	reset_icy(&mh->icy);
1578 }
1579 
mpg123_id3(mpg123_handle * mh,mpg123_id3v1 ** v1,mpg123_id3v2 ** v2)1580 int attribute_align_arg mpg123_id3(mpg123_handle *mh, mpg123_id3v1 **v1, mpg123_id3v2 **v2)
1581 {
1582 	if(v1 != NULL) *v1 = NULL;
1583 	if(v2 != NULL) *v2 = NULL;
1584 	if(mh == NULL) return MPG123_BAD_HANDLE;
1585 
1586 	if(mh->metaflags & MPG123_ID3)
1587 	{
1588 		id3_link(mh);
1589 		if(v1 != NULL && mh->rdat.flags & READER_ID3TAG) *v1 = (mpg123_id3v1*) mh->id3buf;
1590 		if(v2 != NULL)
1591 #ifdef NO_ID3V2
1592 		*v2 = NULL;
1593 #else
1594 		*v2 = &mh->id3v2;
1595 #endif
1596 
1597 		mh->metaflags |= MPG123_ID3;
1598 		mh->metaflags &= ~MPG123_NEW_ID3;
1599 	}
1600 	return MPG123_OK;
1601 }
1602 
mpg123_id3_raw(mpg123_handle * mh,unsigned char ** v1,size_t * v1_size,unsigned char ** v2,size_t * v2_size)1603 int attribute_align_arg mpg123_id3_raw( mpg123_handle *mh
1604 ,	unsigned char **v1, size_t *v1_size
1605 ,	unsigned char **v2, size_t *v2_size )
1606 {
1607 	if(!mh)
1608 		return MPG123_ERR;
1609 	if(v1 != NULL)
1610 		*v1 = mh->id3buf[0] ? mh->id3buf : NULL;
1611 	if(v1_size != NULL)
1612 		*v1_size = mh->id3buf[0] ? 128 : 0;
1613 	if(v2 != NULL)
1614 		*v2 = mh->id3v2_raw;
1615 	if(v2_size != NULL)
1616 		*v2_size = mh->id3v2_size;
1617 	return MPG123_OK;
1618 }
1619 
mpg123_icy(mpg123_handle * mh,char ** icy_meta)1620 int attribute_align_arg mpg123_icy(mpg123_handle *mh, char **icy_meta)
1621 {
1622 	if(mh == NULL) return MPG123_BAD_HANDLE;
1623 #ifndef NO_ICY
1624 	if(icy_meta == NULL)
1625 	{
1626 		mh->err = MPG123_NULL_POINTER;
1627 		return MPG123_ERR;
1628 	}
1629 	*icy_meta = NULL;
1630 
1631 	if(mh->metaflags & MPG123_ICY)
1632 	{
1633 		*icy_meta = mh->icy.data;
1634 		mh->metaflags |= MPG123_ICY;
1635 		mh->metaflags &= ~MPG123_NEW_ICY;
1636 	}
1637 	return MPG123_OK;
1638 #else
1639 	mh->err = MPG123_MISSING_FEATURE;
1640 	return MPG123_ERR;
1641 #endif
1642 }
1643 
mpg123_icy2utf8(const char * icy_text)1644 char* attribute_align_arg mpg123_icy2utf8(const char* icy_text)
1645 {
1646 #ifndef NO_ICY
1647 	return icy2utf8(icy_text, 0);
1648 #else
1649 	return NULL;
1650 #endif
1651 }
1652 
1653 /* That one is always defined... it's not worth it to remove it for NO_ID3V2. */
mpg123_enc_from_id3(unsigned char id3_enc_byte)1654 enum mpg123_text_encoding attribute_align_arg mpg123_enc_from_id3(unsigned char id3_enc_byte)
1655 {
1656 	switch(id3_enc_byte)
1657 	{
1658 		case mpg123_id3_latin1:   return mpg123_text_latin1;
1659 		case mpg123_id3_utf16bom: return mpg123_text_utf16bom; /* ID3v2.3 has UCS-2 with BOM here. */
1660 		case mpg123_id3_utf16be:  return mpg123_text_utf16be;
1661 		case mpg123_id3_utf8:     return mpg123_text_utf8;
1662 		default: return mpg123_text_unknown;
1663 	}
1664 }
1665 
mpg123_enc_from_id3_2(unsigned char id3_enc_byte)1666 int attribute_align_arg mpg123_enc_from_id3_2(unsigned char id3_enc_byte)
1667 {
1668 	return mpg123_enc_from_id3(id3_enc_byte);
1669 }
1670 
1671 #ifndef NO_STRING
mpg123_store_utf8(mpg123_string * sb,enum mpg123_text_encoding enc,const unsigned char * source,size_t source_size)1672 int attribute_align_arg mpg123_store_utf8(mpg123_string *sb, enum mpg123_text_encoding enc, const unsigned char *source, size_t source_size)
1673 {
1674 	switch(enc)
1675 	{
1676 #ifndef NO_ID3V2
1677 		/* The encodings we get from ID3v2 tags. */
1678 		case mpg123_text_utf8:
1679 			id3_to_utf8(sb, mpg123_id3_utf8, source, source_size, 0);
1680 		break;
1681 		case mpg123_text_latin1:
1682 			id3_to_utf8(sb, mpg123_id3_latin1, source, source_size, 0);
1683 		break;
1684 		case mpg123_text_utf16bom:
1685 		case mpg123_text_utf16:
1686 			id3_to_utf8(sb, mpg123_id3_utf16bom, source, source_size, 0);
1687 		break;
1688 		/* Special because one cannot skip zero bytes here. */
1689 		case mpg123_text_utf16be:
1690 			id3_to_utf8(sb, mpg123_id3_utf16be, source, source_size, 0);
1691 		break;
1692 #endif
1693 #ifndef NO_ICY
1694 		/* ICY encoding... */
1695 		case mpg123_text_icy:
1696 		case mpg123_text_cp1252:
1697 		{
1698 			mpg123_free_string(sb);
1699 			/* Paranoia: Make sure that the string ends inside the buffer... */
1700 			if(source[source_size-1] == 0)
1701 			{
1702 				/* Convert from ICY encoding... with force applied or not. */
1703 				char *tmpstring = icy2utf8((const char*)source, enc == mpg123_text_cp1252 ? 1 : 0);
1704 				if(tmpstring != NULL)
1705 				{
1706 					mpg123_set_string(sb, tmpstring);
1707 					free(tmpstring);
1708 				}
1709 			}
1710 		}
1711 		break;
1712 #endif
1713 		default:
1714 			mpg123_free_string(sb);
1715 	}
1716 	/* At least a trailing null of some form should be there... */
1717 	return (sb->fill > 0) ? 1 : 0;
1718 }
1719 
mpg123_store_utf8_2(mpg123_string * sb,int enc,const unsigned char * source,size_t source_size)1720 int attribute_align_arg mpg123_store_utf8_2(mpg123_string *sb, int enc, const unsigned char *source, size_t source_size)
1721 {
1722 	return mpg123_store_utf8(sb, enc, source, source_size);
1723 }
1724 #endif
1725 
1726 
1727 
mpg123_index(mpg123_handle * mh,off_t ** offsets,off_t * step,size_t * fill)1728 int attribute_align_arg mpg123_index(mpg123_handle *mh, off_t **offsets, off_t *step, size_t *fill)
1729 {
1730 	if(mh == NULL) return MPG123_BAD_HANDLE;
1731 	if(offsets == NULL || step == NULL || fill == NULL)
1732 	{
1733 		mh->err = MPG123_BAD_INDEX_PAR;
1734 		return MPG123_ERR;
1735 	}
1736 #ifdef FRAME_INDEX
1737 	*offsets = mh->index.data;
1738 	*step    = mh->index.step;
1739 	*fill    = mh->index.fill;
1740 #else
1741 	*offsets = NULL;
1742 	*step    = 0;
1743 	*fill    = 0;
1744 #endif
1745 	return MPG123_OK;
1746 }
1747 
mpg123_set_index(mpg123_handle * mh,off_t * offsets,off_t step,size_t fill)1748 int attribute_align_arg mpg123_set_index(mpg123_handle *mh, off_t *offsets, off_t step, size_t fill)
1749 {
1750 	if(mh == NULL) return MPG123_BAD_HANDLE;
1751 #ifdef FRAME_INDEX
1752 	if(step == 0)
1753 	{
1754 		mh->err = MPG123_BAD_INDEX_PAR;
1755 		return MPG123_ERR;
1756 	}
1757 	if(fi_set(&mh->index, offsets, step, fill) == -1)
1758 	{
1759 		mh->err = MPG123_OUT_OF_MEM;
1760 		return MPG123_ERR;
1761 	}
1762 	return MPG123_OK;
1763 #else
1764 	mh->err = MPG123_MISSING_FEATURE;
1765 	return MPG123_ERR;
1766 #endif
1767 }
1768 
mpg123_close(mpg123_handle * mh)1769 int attribute_align_arg mpg123_close(mpg123_handle *mh)
1770 {
1771 	if(mh == NULL) return MPG123_BAD_HANDLE;
1772 
1773 	/* mh->rd is never NULL! */
1774 	if(mh->rd->close != NULL) mh->rd->close(mh);
1775 
1776 	if(mh->new_format)
1777 	{
1778 		debug("Hey, we are closing a track before the new format has been queried...");
1779 		invalidate_format(&mh->af);
1780 		mh->new_format = 0;
1781 	}
1782 	/* Always reset the frame buffers on close, so we cannot forget it in funky opening routines (wrappers, even). */
1783 	frame_reset(mh);
1784 	return MPG123_OK;
1785 }
1786 
mpg123_delete(mpg123_handle * mh)1787 void attribute_align_arg mpg123_delete(mpg123_handle *mh)
1788 {
1789 	if(mh != NULL)
1790 	{
1791 		mpg123_close(mh);
1792 		frame_exit(mh); /* free buffers in frame */
1793 		free(mh); /* free struct; cast? */
1794 	}
1795 }
1796 
mpg123_free(void * ptr)1797 void attribute_align_arg mpg123_free(void *ptr)
1798 {
1799 	free(ptr);
1800 }
1801 
1802 static const char *mpg123_error[] =
1803 {
1804 	"No error... (code 0)",
1805 	"Unable to set up output format! (code 1)",
1806 	"Invalid channel number specified. (code 2)",
1807 	"Invalid sample rate specified. (code 3)",
1808 	"Unable to allocate memory for 16 to 8 converter table! (code 4)",
1809 	"Bad parameter id! (code 5)",
1810 	"Bad buffer given -- invalid pointer or too small size. (code 6)",
1811 	"Out of memory -- some malloc() failed. (code 7)",
1812 	"You didn't initialize the library! (code 8)",
1813 	"Invalid decoder choice. (code 9)",
1814 	"Invalid mpg123 handle. (code 10)",
1815 	"Unable to initialize frame buffers (out of memory?)! (code 11)",
1816 	"Invalid RVA mode. (code 12)",
1817 	"This build doesn't support gapless decoding. (code 13)",
1818 	"Not enough buffer space. (code 14)",
1819 	"Incompatible numeric data types. (code 15)",
1820 	"Bad equalizer band. (code 16)",
1821 	"Null pointer given where valid storage address needed. (code 17)",
1822 	"Error reading the stream. (code 18)",
1823 	"Cannot seek from end (end is not known). (code 19)",
1824 	"Invalid 'whence' for seek function. (code 20)",
1825 	"Build does not support stream timeouts. (code 21)",
1826 	"File access error. (code 22)",
1827 	"Seek not supported by stream. (code 23)",
1828 	"No stream opened. (code 24)",
1829 	"Bad parameter handle. (code 25)",
1830 	"Invalid parameter addresses for index retrieval. (code 26)",
1831 	"Lost track in the bytestream and did not attempt resync. (code 27)",
1832 	"Failed to find valid MPEG data within limit on resync. (code 28)",
1833 	"No 8bit encoding possible. (code 29)",
1834 	"Stack alignment is not good. (code 30)",
1835 	"You gave me a NULL buffer? (code 31)",
1836 	"File position is screwed up, please do an absolute seek (code 32)",
1837 	"Inappropriate NULL-pointer provided.",
1838 	"Bad key value given.",
1839 	"There is no frame index (disabled in this build).",
1840 	"Frame index operation failed.",
1841 	"Decoder setup failed (invalid combination of settings?)",
1842 	"Feature not in this build."
1843 	,"Some bad value has been provided."
1844 	,"Low-level seeking has failed (call to lseek(), usually)."
1845 	,"Custom I/O obviously not prepared."
1846 	,"Overflow in LFS (large file support) conversion."
1847 	,"Overflow in integer conversion."
1848 	,"Bad IEEE 754 rounding. Re-build libmpg123 properly."
1849 };
1850 
mpg123_plain_strerror(int errcode)1851 const char* attribute_align_arg mpg123_plain_strerror(int errcode)
1852 {
1853 	if(errcode >= 0 && errcode < sizeof(mpg123_error)/sizeof(char*))
1854 	return mpg123_error[errcode];
1855 	else switch(errcode)
1856 	{
1857 		case MPG123_ERR:
1858 			return "A generic mpg123 error.";
1859 		case MPG123_DONE:
1860 			return "Message: I am done with this track.";
1861 		case MPG123_NEED_MORE:
1862 			return "Message: Feed me more input data!";
1863 		case MPG123_NEW_FORMAT:
1864 			return "Message: Prepare for a changed audio format (query the new one)!";
1865 		default:
1866 			return "I have no idea - an unknown error code!";
1867 	}
1868 }
1869 
mpg123_errcode(mpg123_handle * mh)1870 int attribute_align_arg mpg123_errcode(mpg123_handle *mh)
1871 {
1872 	if(mh != NULL) return mh->err;
1873 	return MPG123_BAD_HANDLE;
1874 }
1875 
mpg123_strerror(mpg123_handle * mh)1876 const char* attribute_align_arg mpg123_strerror(mpg123_handle *mh)
1877 {
1878 	return mpg123_plain_strerror(mpg123_errcode(mh));
1879 }
1880