Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1905 serge 1
/*
2
	libmpg123: MPEG Audio Decoder library
3
 
4
	copyright 1995-2009 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
#include "debug.h"
12
 
13
#ifdef GAPLESS
14
#define SAMPLE_ADJUST(x)   ((x) - ((mh->p.flags & MPG123_GAPLESS) ? mh->begin_os : 0))
15
#define SAMPLE_UNADJUST(x) ((x) + ((mh->p.flags & MPG123_GAPLESS) ? mh->begin_os : 0))
16
#else
17
#define SAMPLE_ADJUST(x)   (x)
18
#define SAMPLE_UNADJUST(x) (x)
19
#endif
20
 
21
#define SEEKFRAME(mh) ((mh)->ignoreframe < 0 ? 0 : (mh)->ignoreframe)
22
 
23
static int initialized = 0;
24
 
25
#define ALIGNCHECK(mh)
26
#define ALIGNCHECKK
27
/* On compilers that support data alignment but not the automatic stack realignment.
28
   We check for properly aligned stack before risking a crash because of badly compiled
29
   client program. */
30
#if (defined CCALIGN) && (defined NEED_ALIGNCHECK) && ((defined DEBUG) || (defined CHECK_ALIGN))
31
 
32
/* Common building block. */
33
#define ALIGNMAINPART \
34
	/* minimum size of 16 bytes, not all compilers would align a smaller piece of data */ \
35
	double ALIGNED(16) altest[2]; \
36
	debug2("testing alignment, with %lu %% 16 = %lu", \
37
		(unsigned long)altest, (unsigned long)((size_t)altest % 16)); \
38
	if((size_t)altest % 16 != 0)
39
 
40
#undef ALIGNCHECK
41
#define ALIGNCHECK(mh) \
42
	ALIGNMAINPART \
43
	{ \
44
		error("Stack variable is not aligned! Your combination of compiler/library is dangerous!"); \
45
		if(mh != NULL) mh->err = MPG123_BAD_ALIGN; \
46
\
47
		return MPG123_ERR; \
48
	}
49
#undef ALIGNCHECKK
50
#define ALIGNCHECKK \
51
	ALIGNMAINPART \
52
	{ \
53
		error("Stack variable is not aligned! Your combination of compiler/library is dangerous!"); \
54
		return MPG123_BAD_ALIGN; \
55
	}
56
 
57
#endif
58
 
59
#ifdef GAPLESS
60
/*
61
	Take the buffer after a frame decode (strictly: it is the data from frame fr->num!) and cut samples out.
62
	fr->buffer.fill may then be smaller than before...
63
*/
64
static void frame_buffercheck(mpg123_handle *fr)
65
{
66
	/* When we have no accurate position, gapless code does not make sense. */
67
	if(!fr->accurate) return;
68
 
69
	/* The first interesting frame: Skip some leading samples. */
70
	if(fr->firstoff && fr->num == fr->firstframe)
71
	{
72
		off_t byteoff = samples_to_bytes(fr, fr->firstoff);
73
		if((off_t)fr->buffer.fill > byteoff)
74
		{
75
			fr->buffer.fill -= byteoff;
76
			/* buffer.p != buffer.data only for own buffer */
77
			debug6("cutting %li samples/%li bytes on begin, own_buffer=%i at %p=%p, buf[1]=%i",
78
			        (long)fr->firstoff, (long)byteoff, fr->own_buffer, (void*)fr->buffer.p, (void*)fr->buffer.data, ((short*)fr->buffer.p)[2]);
79
			if(fr->own_buffer) fr->buffer.p = fr->buffer.data + byteoff;
80
			else memmove(fr->buffer.data, fr->buffer.data + byteoff, fr->buffer.fill);
81
			debug3("done cutting, buffer at %p =? %p, buf[1]=%i",
82
			        (void*)fr->buffer.p, (void*)fr->buffer.data, ((short*)fr->buffer.p)[2]);
83
		}
84
		else fr->buffer.fill = 0;
85
		fr->firstoff = 0; /* Only enter here once... when you seek, firstoff should be reset. */
86
	}
87
	/* The last interesting (planned) frame: Only use some leading samples. */
88
	if(fr->lastoff && fr->num == fr->lastframe)
89
	{
90
		off_t byteoff = samples_to_bytes(fr, fr->lastoff);
91
		if((off_t)fr->buffer.fill > byteoff)
92
		{
93
			fr->buffer.fill = byteoff;
94
		}
95
		fr->lastoff = 0; /* Only enter here once... when you seek, lastoff should be reset. */
96
	}
97
}
98
#endif
99
 
100
int attribute_align_arg mpg123_init(void)
101
{
102
	ALIGNCHECKK
103
	if((sizeof(short) != 2) || (sizeof(long) < 4)) return MPG123_BAD_TYPES;
104
 
105
	if(initialized) return MPG123_OK; /* no need to initialize twice */
106
 
107
#ifndef NO_LAYER12
108
	init_layer12(); /* inits also shared tables with layer1 */
109
#endif
110
#ifndef NO_LAYER3
111
	init_layer3();
112
#endif
113
	prepare_decode_tables();
114
	check_decoders();
115
	initialized = 1;
116
	return MPG123_OK;
117
}
118
 
119
void attribute_align_arg mpg123_exit(void)
120
{
121
	/* nothing yet, but something later perhaps */
122
}
123
 
124
/* create a new handle with specified decoder, decoder can be "", "auto" or NULL for auto-detection */
125
mpg123_handle attribute_align_arg *mpg123_new(const char* decoder, int *error)
126
{
127
	return mpg123_parnew(NULL, decoder, error);
128
}
129
 
130
/* ...the full routine with optional initial parameters to override defaults. */
131
mpg123_handle attribute_align_arg *mpg123_parnew(mpg123_pars *mp, const char* decoder, int *error)
132
{
133
	mpg123_handle *fr = NULL;
134
	int err = MPG123_OK;
135
#if (defined CCALIGN) && (defined NEED_ALIGNCHECK) && ((defined DEBUG) || (defined CHECK_ALIGN))
136
#ifdef CCALIGN
137
	double ALIGNED(16) altest[4];
138
	if(((size_t)altest) % 16 != 0)
139
	{
140
		error("Stack variable is not aligned! Your combination of compiler/library is dangerous!");
141
		*error = MPG123_BAD_ALIGN;
142
		return NULL;
143
	}
144
#endif
145
#endif
146
	if(initialized) fr = (mpg123_handle*) malloc(sizeof(mpg123_handle));
147
	else err = MPG123_NOT_INITIALIZED;
148
	if(fr != NULL)
149
	{
150
		frame_init_par(fr, mp);
151
		debug("cpu opt setting");
152
		if(frame_cpu_opt(fr, decoder) != 1)
153
		{
154
			err = MPG123_BAD_DECODER;
155
			frame_exit(fr);
156
			free(fr);
157
			fr = NULL;
158
		}
159
	}
160
	if(fr != NULL)
161
	{
162
		/* Cleanup that mess! ... use mpg123_decoder / decode_update! */
163
		if(frame_outbuffer(fr) != 0)
164
		{
165
			err = MPG123_NO_BUFFERS;
166
			frame_exit(fr);
167
			free(fr);
168
			fr = NULL;
169
		}
170
		else
171
		{
172
			/* I smell cleanup here... with get_next_frame() */
173
/*			if(decode_update(fr) != 0)
174
			{
175
				err = fr->err != MPG123_OK ? fr->err : MPG123_BAD_DECODER;
176
				frame_exit(fr);
177
				free(fr);
178
				fr = NULL;
179
			}
180
			else */
181
			fr->decoder_change = 1;
182
		}
183
	}
184
	else if(err == MPG123_OK) err = MPG123_OUT_OF_MEM;
185
 
186
	if(error != NULL) *error = err;
187
	return fr;
188
}
189
 
190
int attribute_align_arg mpg123_decoder(mpg123_handle *mh, const char* decoder)
191
{
192
	enum optdec dt = dectype(decoder);
193
	ALIGNCHECK(mh);
194
	if(mh == NULL) return MPG123_ERR;
195
 
196
	if(dt == nodec)
197
	{
198
		mh->err = MPG123_BAD_DECODER;
199
		return MPG123_ERR;
200
	}
201
	if(dt == mh->cpu_opts.type) return MPG123_OK;
202
 
203
	/* Now really change. */
204
	/* frame_exit(mh);
205
	frame_init(mh); */
206
	debug("cpu opt setting");
207
	if(frame_cpu_opt(mh, decoder) != 1)
208
	{
209
		mh->err = MPG123_BAD_DECODER;
210
		frame_exit(mh);
211
		return MPG123_ERR;
212
	}
213
	/* New buffers for decoder are created in frame_buffers() */
214
	if((frame_outbuffer(mh) != 0))
215
	{
216
		mh->err = MPG123_NO_BUFFERS;
217
		frame_exit(mh);
218
		return MPG123_ERR;
219
	}
220
	/* I smell cleanup here... with get_next_frame() */
221
	decode_update(mh);
222
	mh->decoder_change = 1;
223
	return MPG123_OK;
224
}
225
 
226
int attribute_align_arg mpg123_param(mpg123_handle *mh, enum mpg123_parms key, long val, double fval)
227
{
228
	int r;
229
	ALIGNCHECK(mh);
230
	if(mh == NULL) return MPG123_ERR;
231
	r = mpg123_par(&mh->p, key, val, fval);
232
	if(r != MPG123_OK){ mh->err = r; r = MPG123_ERR; }
233
	else
234
	{ /* Special treatment for some settings. */
235
#ifdef FRAME_INDEX
236
		if(key == MPG123_INDEX_SIZE)
237
		{ /* Apply frame index size and grow property on the fly. */
238
			r = frame_index_setup(mh);
239
			if(r != MPG123_OK) mh->err = MPG123_INDEX_FAIL;
240
		}
241
#endif
242
	}
243
	return r;
244
}
245
 
246
int attribute_align_arg mpg123_par(mpg123_pars *mp, enum mpg123_parms key, long val, double fval)
247
{
248
	int ret = MPG123_OK;
249
	ALIGNCHECKK
250
	if(mp == NULL) return MPG123_BAD_PARS;
251
	switch(key)
252
	{
253
		case MPG123_VERBOSE:
254
			mp->verbose = val;
255
		break;
256
		case MPG123_FLAGS:
257
#ifndef GAPLESS
258
			if(val & MPG123_GAPLESS) ret = MPG123_NO_GAPLESS;
259
#endif
260
			if(ret == MPG123_OK) mp->flags = val;
261
			debug1("set flags to 0x%lx", (unsigned long) mp->flags);
262
		break;
263
		case MPG123_ADD_FLAGS:
264
#ifndef GAPLESS
265
			/* Enabling of gapless mode doesn't work when it's not there, but disabling (below) is no problem. */
266
			if(val & MPG123_GAPLESS) ret = MPG123_NO_GAPLESS;
267
			else
268
#endif
269
			mp->flags |= val;
270
			debug1("set flags to 0x%lx", (unsigned long) mp->flags);
271
		break;
272
		case MPG123_REMOVE_FLAGS:
273
			mp->flags &= ~val;
274
			debug1("set flags to 0x%lx", (unsigned long) mp->flags);
275
		break;
276
		case MPG123_FORCE_RATE: /* should this trigger something? */
277
#ifdef NO_NTOM
278
			if(val > 0)
279
			ret = MPG123_BAD_RATE;
280
#else
281
			if(val > 96000) ret = MPG123_BAD_RATE;
282
			else mp->force_rate = val < 0 ? 0 : val; /* >0 means enable, 0 disable */
283
#endif
284
		break;
285
		case MPG123_DOWN_SAMPLE:
286
#ifdef NO_DOWNSAMPLE
287
			if(val != 0) ret = MPG123_BAD_RATE;
288
#else
289
			if(val < 0 || val > 2) ret = MPG123_BAD_RATE;
290
			else mp->down_sample = (int)val;
291
#endif
292
		break;
293
		case MPG123_RVA:
294
			if(val < 0 || val > MPG123_RVA_MAX) ret = MPG123_BAD_RVA;
295
			else mp->rva = (int)val;
296
		break;
297
		case MPG123_DOWNSPEED:
298
			mp->halfspeed = val < 0 ? 0 : val;
299
		break;
300
		case MPG123_UPSPEED:
301
			mp->doublespeed = val < 0 ? 0 : val;
302
		break;
303
		case MPG123_ICY_INTERVAL:
304
#ifndef NO_ICY
305
			mp->icy_interval = val > 0 ? val : 0;
306
#else
307
			if(val > 0) ret = MPG123_BAD_PARAM;
308
#endif
309
		break;
310
		case MPG123_OUTSCALE:
311
			/* Choose the value that is non-zero, if any.
312
			   Downscaling integers to 1.0 . */
313
			mp->outscale = val == 0 ? fval : (double)val/SHORT_SCALE;
314
		break;
315
		case MPG123_TIMEOUT:
316
#ifndef WIN32
317
			mp->timeout = val >= 0 ? val : 0;
318
#else
319
			ret = MPG123_NO_TIMEOUT;
320
#endif
321
		break;
322
		case MPG123_RESYNC_LIMIT:
323
			mp->resync_limit = val;
324
		break;
325
		case MPG123_INDEX_SIZE:
326
#ifdef FRAME_INDEX
327
			mp->index_size = val;
328
#else
329
			ret = MPG123_NO_INDEX;
330
#endif
331
		break;
332
		case MPG123_PREFRAMES:
333
			if(val >= 0) mp->preframes = val;
334
			else ret = MPG123_BAD_VALUE;
335
		break;
336
		default:
337
			ret = MPG123_BAD_PARAM;
338
	}
339
	return ret;
340
}
341
 
342
int attribute_align_arg mpg123_getparam(mpg123_handle *mh, enum mpg123_parms key, long *val, double *fval)
343
{
344
	int r;
345
	ALIGNCHECK(mh);
346
	if(mh == NULL) return MPG123_ERR;
347
	r = mpg123_getpar(&mh->p, key, val, fval);
348
	if(r != MPG123_OK){ mh->err = r; r = MPG123_ERR; }
349
	return r;
350
}
351
 
352
int attribute_align_arg mpg123_getpar(mpg123_pars *mp, enum mpg123_parms key, long *val, double *fval)
353
{
354
	int ret = 0;
355
	ALIGNCHECKK
356
	if(mp == NULL) return MPG123_BAD_PARS;
357
	switch(key)
358
	{
359
		case MPG123_VERBOSE:
360
			if(val) *val = mp->verbose;
361
		break;
362
		case MPG123_FLAGS:
363
		case MPG123_ADD_FLAGS:
364
			if(val) *val = mp->flags;
365
		break;
366
		case MPG123_FORCE_RATE:
367
			if(val)
368
#ifdef NO_NTOM
369
			*val = 0;
370
#else
371
			*val = mp->force_rate;
372
#endif
373
		break;
374
		case MPG123_DOWN_SAMPLE:
375
			if(val) *val = mp->down_sample;
376
		break;
377
		case MPG123_RVA:
378
			if(val) *val = mp->rva;
379
		break;
380
		case MPG123_DOWNSPEED:
381
			if(val) *val = mp->halfspeed;
382
		break;
383
		case MPG123_UPSPEED:
384
			if(val) *val = mp->doublespeed;
385
		break;
386
		case MPG123_ICY_INTERVAL:
387
#ifndef NO_ICY
388
			if(val) *val = (long)mp->icy_interval;
389
#else
390
			if(val) *val = 0;
391
#endif
392
		break;
393
		case MPG123_OUTSCALE:
394
			if(fval) *fval = mp->outscale;
395
			if(val) *val = (long)(mp->outscale*SHORT_SCALE);
396
		break;
397
		case MPG123_RESYNC_LIMIT:
398
			if(val) *val = mp->resync_limit;
399
		break;
400
		case MPG123_INDEX_SIZE:
401
			if(val)
402
#ifdef FRAME_INDEX
403
			*val = mp->index_size;
404
#else
405
			*val = 0; /* graceful fallback: no index is index of zero size */
406
#endif
407
		break;
408
		case MPG123_PREFRAMES:
409
			*val = mp->preframes;
410
		break;
411
		default:
412
			ret = MPG123_BAD_PARAM;
413
	}
414
	return ret;
415
}
416
 
417
int attribute_align_arg mpg123_getstate(mpg123_handle *mh, enum mpg123_state key, long *val, double *fval)
418
{
419
	int ret = MPG123_OK;
420
	long theval = 0;
421
	double thefval = 0.;
422
	ALIGNCHECK(mh);
423
	if(mh == NULL) return MPG123_ERR;
424
 
425
	switch(key)
426
	{
427
		case MPG123_ACCURATE:
428
			theval = mh->accurate;
429
		break;
430
		default:
431
			mh->err = MPG123_BAD_KEY;
432
			ret = MPG123_ERR;
433
	}
434
 
435
	if(val  != NULL) *val  = theval;
436
	if(fval != NULL) *fval = thefval;
437
 
438
	return ret;
439
}
440
 
441
int attribute_align_arg mpg123_eq(mpg123_handle *mh, enum mpg123_channels channel, int band, double val)
442
{
443
	ALIGNCHECK(mh);
444
	if(mh == NULL) return MPG123_ERR;
445
	if(band < 0 || band > 31){ mh->err = MPG123_BAD_BAND; return MPG123_ERR; }
446
	switch(channel)
447
	{
448
		case MPG123_LEFT|MPG123_RIGHT:
449
			mh->equalizer[0][band] = mh->equalizer[1][band] = DOUBLE_TO_REAL(val);
450
		break;
451
		case MPG123_LEFT:  mh->equalizer[0][band] = DOUBLE_TO_REAL(val); break;
452
		case MPG123_RIGHT: mh->equalizer[1][band] = DOUBLE_TO_REAL(val); break;
453
		default:
454
			mh->err=MPG123_BAD_CHANNEL;
455
			return MPG123_ERR;
456
	}
457
	mh->have_eq_settings = TRUE;
458
	return MPG123_OK;
459
}
460
 
461
double attribute_align_arg mpg123_geteq(mpg123_handle *mh, enum mpg123_channels channel, int band)
462
{
463
	double ret = 0.;
464
	ALIGNCHECK(mh);
465
	if(mh == NULL) return MPG123_ERR;
466
 
467
	/* Handle this gracefully. When there is no band, it has no volume. */
468
	if(band > -1 && band < 32)
469
	switch(channel)
470
	{
471
		case MPG123_LEFT|MPG123_RIGHT:
472
			ret = 0.5*(REAL_TO_DOUBLE(mh->equalizer[0][band])+REAL_TO_DOUBLE(mh->equalizer[1][band]));
473
		break;
474
		case MPG123_LEFT:  ret = REAL_TO_DOUBLE(mh->equalizer[0][band]); break;
475
		case MPG123_RIGHT: ret = REAL_TO_DOUBLE(mh->equalizer[1][band]); break;
476
		/* Default case is already handled: ret = 0 */
477
	}
478
 
479
	return ret;
480
}
481
 
482
 
483
/* plain file access, no http! */
484
int attribute_align_arg mpg123_open(mpg123_handle *mh, const char *path)
485
{
486
	ALIGNCHECK(mh);
487
	if(mh == NULL) return MPG123_ERR;
488
 
489
	mpg123_close(mh);
490
	frame_reset(mh);
491
	return open_stream(mh, path, -1);
492
}
493
 
494
int attribute_align_arg mpg123_open_fd(mpg123_handle *mh, int fd)
495
{
496
	ALIGNCHECK(mh);
497
	if(mh == NULL) return MPG123_ERR;
498
 
499
	mpg123_close(mh);
500
	frame_reset(mh);
501
	return open_stream(mh, NULL, fd);
502
}
503
 
504
int attribute_align_arg mpg123_open_feed(mpg123_handle *mh)
505
{
506
	ALIGNCHECK(mh);
507
	if(mh == NULL) return MPG123_ERR;
508
 
509
	mpg123_close(mh);
510
	frame_reset(mh);
511
	return open_feed(mh);
512
}
513
 
514
int attribute_align_arg mpg123_replace_reader( mpg123_handle *mh,
515
                           ssize_t (*r_read) (int, void *, size_t),
516
                           off_t   (*r_lseek)(int, off_t, int) )
517
{
518
	ALIGNCHECK(mh);
519
	if(mh == NULL) return MPG123_ERR;
520
	mh->rdat.r_read = r_read;
521
	mh->rdat.r_lseek = r_lseek;
522
	return MPG123_OK;
523
}
524
 
525
 
526
int decode_update(mpg123_handle *mh)
527
{
528
	long native_rate;
529
	int b;
530
	ALIGNCHECK(mh);
531
	native_rate = frame_freq(mh);
532
 
533
	b = frame_output_format(mh); /* Select the new output format based on given constraints. */
534
	if(b < 0) return MPG123_ERR;
535
 
536
	if(b == 1) mh->new_format = 1; /* Store for later... */
537
 
538
	debug3("updating decoder structure with native rate %li and af.rate %li (new format: %i)", native_rate, mh->af.rate, mh->new_format);
539
	if(mh->af.rate == native_rate) mh->down_sample = 0;
540
	else if(mh->af.rate == native_rate>>1) mh->down_sample = 1;
541
	else if(mh->af.rate == native_rate>>2) mh->down_sample = 2;
542
	else mh->down_sample = 3; /* flexible (fixed) rate */
543
	switch(mh->down_sample)
544
	{
545
		case 0:
546
		case 1:
547
		case 2:
548
			mh->down_sample_sblimit = SBLIMIT>>(mh->down_sample);
549
			/* With downsampling I get less samples per frame */
550
			mh->outblock = samples_to_bytes(mh, (spf(mh)>>mh->down_sample));
551
		break;
552
#ifndef NO_NTOM
553
		case 3:
554
		{
555
			if(synth_ntom_set_step(mh) != 0) return -1;
556
			if(frame_freq(mh) > mh->af.rate)
557
			{
558
				mh->down_sample_sblimit = SBLIMIT * mh->af.rate;
559
				mh->down_sample_sblimit /= frame_freq(mh);
560
			}
561
			else mh->down_sample_sblimit = SBLIMIT;
562
			mh->outblock = mh->af.encsize * mh->af.channels *
563
			               ( ( NTOM_MUL-1+spf(mh)
564
			                   * (((size_t)NTOM_MUL*mh->af.rate)/frame_freq(mh))
565
			                 )/NTOM_MUL );
566
		}
567
		break;
568
#endif
569
	}
570
 
571
	if(!(mh->p.flags & MPG123_FORCE_MONO))
572
	{
573
		if(mh->af.channels == 1) mh->single = SINGLE_MIX;
574
		else mh->single = SINGLE_STEREO;
575
	}
576
	else mh->single = (mh->p.flags & MPG123_FORCE_MONO)-1;
577
	if(set_synth_functions(mh) != 0) return -1;;
578
 
579
	do_rva(mh);
580
	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);
581
 
582
	return 0;
583
}
584
 
585
size_t attribute_align_arg mpg123_safe_buffer()
586
{
587
	/* real is the largest possible output (it's 32bit float, 32bit int or 64bit double). */
588
	return sizeof(real)*2*1152*NTOM_MAX;
589
}
590
 
591
size_t attribute_align_arg mpg123_outblock(mpg123_handle *mh)
592
{
593
	if(mh != NULL) return mh->outblock;
594
	else return mpg123_safe_buffer();
595
}
596
 
597
static int get_next_frame(mpg123_handle *mh)
598
{
599
	int change = mh->decoder_change;
600
	do
601
	{
602
		int b;
603
		/* Decode & discard some frame(s) before beginning. */
604
		if(mh->to_ignore && mh->num < mh->firstframe && mh->num >= mh->ignoreframe)
605
		{
606
			debug1("ignoring frame %li", (long)mh->num);
607
			/* Decoder structure must be current! decode_update has been called before... */
608
			(mh->do_layer)(mh); mh->buffer.fill = 0;
609
#ifndef NO_NTOM
610
			/* The ignored decoding may have failed. Make sure ntom stays consistent. */
611
			if(mh->down_sample == 3) ntom_set_ntom(mh, mh->num+1);
612
#endif
613
			mh->to_ignore = mh->to_decode = FALSE;
614
		}
615
		/* Read new frame data; possibly breaking out here for MPG123_NEED_MORE. */
616
		debug("read frame");
617
		mh->to_decode = FALSE;
618
		b = read_frame(mh); /* That sets to_decode only if a full frame was read. */
619
		debug4("read of frame %li returned %i (to_decode=%i) at sample %li", (long)mh->num, b, mh->to_decode, (long)mpg123_tell(mh));
620
		if(b == MPG123_NEED_MORE) return MPG123_NEED_MORE; /* need another call with data */
621
		else if(b <= 0)
622
		{
623
			/* More sophisticated error control? */
624
			if(b==0 || mh->rdat.filepos == mh->rdat.filelen)
625
			{ /* We simply reached the end. */
626
				mh->track_frames = mh->num + 1;
627
				debug("What about updating/checking gapless sample count here?");
628
				return MPG123_DONE;
629
			}
630
			else return MPG123_ERR; /* Some real error. */
631
		}
632
		/* Now, there should be new data to decode ... and also possibly new stream properties */
633
		if(mh->header_change > 1)
634
		{
635
			debug("big header change");
636
			change = 1;
637
		}
638
		/* Now some accounting: Look at the numbers and decide if we want this frame. */
639
		++mh->playnum;
640
		/* Plain skipping without decoding, only when frame is not ignored on next cycle. */
641
		if(mh->num < mh->firstframe || (mh->p.doublespeed && (mh->playnum % mh->p.doublespeed)))
642
		{
643
			if(!(mh->to_ignore && mh->num < mh->firstframe && mh->num >= mh->ignoreframe))
644
			{
645
				frame_skip(mh);
646
				/* Should one fix NtoM here or not?
647
				   It is not work the trouble for doublespeed, but what with leading frames? */
648
			}
649
		}
650
		/* Or, we are finally done and have a new frame. */
651
		else break;
652
	} while(1);
653
	/* When we start actually using the CRC, this could move into the loop... */
654
	/* A question of semantics ... should I fold start_frame and frame_number into firstframe/lastframe? */
655
	if(mh->lastframe >= 0 && mh->num > mh->lastframe)
656
	{
657
		mh->to_decode = mh->to_ignore = FALSE;
658
		return MPG123_DONE;
659
	}
660
	if(change)
661
	{
662
		if(decode_update(mh) < 0)  /* dito... */
663
		return MPG123_ERR;
664
 
665
debug1("new format: %i", mh->new_format);
666
 
667
		mh->decoder_change = 0;
668
#ifdef GAPLESS
669
		if(mh->fresh)
670
		{
671
			int b=0;
672
			/* Prepare offsets for gapless decoding. */
673
			debug1("preparing gapless stuff with native rate %li", frame_freq(mh));
674
			frame_gapless_realinit(mh);
675
			frame_set_frameseek(mh, mh->num);
676
			mh->fresh = 0;
677
			/* Could this possibly happen? With a real big gapless offset... */
678
			if(mh->num < mh->firstframe) b = get_next_frame(mh);
679
			if(b < 0) return b; /* Could be error, need for more, new format... */
680
		}
681
#endif
682
	}
683
	return MPG123_OK;
684
}
685
 
686
/* Assumption: A buffer full of zero samples can be constructed by repetition of this byte.
687
   Only to be used by decode_the_frame() ... */
688
static int zero_byte(mpg123_handle *fr)
689
{
690
#ifndef NO_8BIT
691
	return fr->af.encoding & MPG123_ENC_8 ? fr->conv16to8[0] : 0;
692
#else
693
	return 0; /* All normal signed formats have the zero here (even in byte form -- that may be an assumption for your funny machine...). */
694
#endif
695
}
696
 
697
/*
698
	Not part of the api. This just decodes the frame and fills missing bits with zeroes.
699
	There can be frames that are broken and thus make do_layer() fail.
700
*/
701
void decode_the_frame(mpg123_handle *fr)
702
{
703
	size_t needed_bytes = samples_to_bytes(fr, frame_outs(fr, fr->num+1)-frame_outs(fr, fr->num));
704
	fr->clip += (fr->do_layer)(fr);
705
	/*fprintf(stderr, "frame %"OFF_P": got %"SIZE_P" / %"SIZE_P"\n", fr->num,(size_p)fr->buffer.fill, (size_p)needed_bytes);*/
706
	/* There could be less data than promised.
707
	   Also, then debugging, we look out for coding errors that could result in _more_ data than expected. */
708
#ifdef DEBUG
709
	if(fr->buffer.fill != needed_bytes)
710
	{
711
#endif
712
		if(fr->buffer.fill < needed_bytes)
713
		{
714
			if(VERBOSE2)
715
			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);
716
 
717
			/*
718
				One could do a loop with individual samples instead... but zero is zero
719
				Actually, that is wrong: zero is mostly a series of null bytes,
720
				but we have funny 8bit formats that have a different opinion on zero...
721
				Unsigned 16 or 32 bit formats are handled later.
722
			*/
723
			memset( fr->buffer.data + fr->buffer.fill, zero_byte(fr), needed_bytes - fr->buffer.fill );
724
 
725
			fr->buffer.fill = needed_bytes;
726
#ifndef NO_NTOM
727
			/* ntom_val will be wrong when the decoding wasn't carried out completely */
728
			ntom_set_ntom(fr, fr->num+1);
729
#endif
730
		}
731
#ifdef DEBUG
732
		else
733
		{
734
			if(NOQUIET)
735
			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);
736
		}
737
	}
738
#endif
739
	/* Handle unsigned output formats via reshifting after decode here. */
740
#ifndef NO_32BIT
741
	if(fr->af.encoding == MPG123_ENC_UNSIGNED_32)
742
	{ /* 32bit signed -> unsigned */
743
		size_t i;
744
		int32_t *ssamples;
745
		uint32_t *usamples;
746
		ssamples = (int32_t*)fr->buffer.data;
747
		usamples = (uint32_t*)fr->buffer.data;
748
		debug("converting output to unsigned 32 bit integer");
749
		for(i=0; ibuffer.fill/sizeof(int32_t); ++i)
750
		{
751
			/* Different strategy since we don't have a larger type at hand.
752
				 Also watch out for silly +-1 fun because integer constants are signed in C90! */
753
			if(ssamples[i] >= 0)
754
			usamples[i] = (uint32_t)ssamples[i] + 2147483647+1;
755
			/* The smalles value goes zero. */
756
			else if(ssamples[i] == ((int32_t)-2147483647-1))
757
			usamples[i] = 0;
758
			/* Now -value is in the positive range of signed int ... so it's a possible value at all. */
759
			else
760
			usamples[i] = (uint32_t)2147483647+1 - (uint32_t)(-ssamples[i]);
761
		}
762
	}
763
#endif
764
#ifndef NO_16BIT
765
	if(fr->af.encoding == MPG123_ENC_UNSIGNED_16)
766
	{
767
		size_t i;
768
		short *ssamples;
769
		unsigned short *usamples;
770
		ssamples = (short*)fr->buffer.data;
771
		usamples = (unsigned short*)fr->buffer.data;
772
		debug("converting output to unsigned 16 bit integer");
773
		for(i=0; ibuffer.fill/sizeof(short); ++i)
774
		{
775
			long tmp = (long)ssamples[i]+32768;
776
			usamples[i] = (unsigned short)tmp;
777
		}
778
	}
779
#endif
780
}
781
 
782
/*
783
	Put _one_ decoded frame into the frame structure's buffer, accessible at the location stored in 
784
	The buffer contents will be lost on next call to mpg123_decode_frame.
785
	MPG123_OK -- successfully decoded the frame, you get your output data
786
	MPg123_DONE -- This is it. End.
787
	MPG123_ERR -- some error occured...
788
	MPG123_NEW_FORMAT -- new frame was read, it results in changed output format -> will be decoded on next call
789
	MPG123_NEED_MORE  -- that should not happen as this function is intended for in-library stream reader but if you force it...
790
	MPG123_NO_SPACE   -- not enough space in buffer for safe decoding, also should not happen
791
 
792
	num will be updated to the last decoded frame number (may possibly _not_ increase, p.ex. when format changed).
793
*/
794
int attribute_align_arg mpg123_decode_frame(mpg123_handle *mh, off_t *num, unsigned char **audio, size_t *bytes)
795
{
796
	ALIGNCHECK(mh);
797
	if(bytes != NULL) *bytes = 0;
798
	if(mh == NULL) return MPG123_ERR;
799
	if(mh->buffer.size < mh->outblock) return MPG123_NO_SPACE;
800
	mh->buffer.fill = 0; /* always start fresh */
801
	while(TRUE)
802
	{
803
		/* decode if possible */
804
		if(mh->to_decode)
805
		{
806
			if(mh->new_format)
807
			{
808
				debug("notifiying new format");
809
				mh->new_format = 0;
810
				return MPG123_NEW_FORMAT;
811
			}
812
			if(num != NULL) *num = mh->num;
813
			debug("decoding");
814
 
815
			decode_the_frame(mh);
816
 
817
			mh->to_decode = mh->to_ignore = FALSE;
818
			mh->buffer.p = mh->buffer.data;
819
#ifdef GAPLESS
820
			/* This checks for individual samples to skip, for gapless mode or sample-accurate seek. */
821
			frame_buffercheck(mh);
822
#endif
823
			if(audio != NULL) *audio = mh->buffer.p;
824
			if(bytes != NULL) *bytes = mh->buffer.fill;
825
 
826
			return MPG123_OK;
827
		}
828
		else
829
		{
830
			int b = get_next_frame(mh);
831
			if(b < 0) return b;
832
			debug1("got next frame, %i", mh->to_decode);
833
		}
834
	}
835
}
836
 
837
int attribute_align_arg mpg123_read(mpg123_handle *mh, unsigned char *out, size_t size, size_t *done)
838
{
839
	return mpg123_decode(mh, NULL, 0, out, size, done);
840
}
841
 
842
int attribute_align_arg mpg123_feed(mpg123_handle *mh, const unsigned char *in, size_t size)
843
{
844
	if(mh == NULL) return MPG123_ERR;
845
	if(size > 0)
846
	{
847
		if(in != NULL)
848
		{
849
			if(feed_more(mh, in, size) != 0) return MPG123_ERR;
850
			else return MPG123_OK;
851
		}
852
		else
853
		{
854
			mh->err = MPG123_NULL_BUFFER;
855
			return MPG123_ERR;
856
		}
857
	}
858
	return MPG123_OK;
859
}
860
 
861
/*
862
	The old picture:
863
	while(1) {
864
		len = read(0,buf,16384);
865
		if(len <= 0)
866
			break;
867
		ret = decodeMP3(&mp,buf,len,out,8192,&size);
868
		while(ret == MP3_OK) {
869
			write(1,out,size);
870
			ret = decodeMP3(&mp,NULL,0,out,8192,&size);
871
		}
872
	}
873
*/
874
 
875
int attribute_align_arg mpg123_decode(mpg123_handle *mh, const unsigned char *inmemory, size_t inmemsize, unsigned char *outmemory, size_t outmemsize, size_t *done)
876
{
877
	int ret = MPG123_OK;
878
	size_t mdone = 0;
879
	ALIGNCHECK(mh);
880
	if(done != NULL) *done = 0;
881
	if(mh == NULL) return MPG123_ERR;
882
	if(inmemsize > 0 && mpg123_feed(mh, inmemory, inmemsize) != MPG123_OK)
883
	{
884
		ret = MPG123_ERR;
885
		goto decodeend;
886
	}
887
	if(outmemory == NULL) outmemsize = 0; /* Not just give error, give chance to get a status message. */
888
 
889
	while(ret == MPG123_OK)
890
	{
891
		debug4("decode loop, fill %i (%li vs. %li); to_decode: %i", (int)mh->buffer.fill, (long)mh->num, (long)mh->firstframe, mh->to_decode);
892
		/* Decode a frame that has been read before.
893
		   This only happens when buffer is empty! */
894
		if(mh->to_decode)
895
		{
896
			if(mh->new_format)
897
			{
898
				debug("notifiying new format");
899
				mh->new_format = 0;
900
				return MPG123_NEW_FORMAT;
901
			}
902
			if(mh->buffer.size - mh->buffer.fill < mh->outblock)
903
			{
904
				ret = MPG123_NO_SPACE;
905
				goto decodeend;
906
			}
907
			decode_the_frame(mh);
908
			mh->to_decode = mh->to_ignore = FALSE;
909
			mh->buffer.p = mh->buffer.data;
910
			debug2("decoded frame %li, got %li samples in buffer", (long)mh->num, (long)(mh->buffer.fill / (samples_to_bytes(mh, 1))));
911
#ifdef GAPLESS
912
			frame_buffercheck(mh); /* Seek & gapless. */
913
#endif
914
		}
915
		if(mh->buffer.fill) /* Copy (part of) the decoded data to the caller's buffer. */
916
		{
917
			/* get what is needed - or just what is there */
918
			int a = mh->buffer.fill > (outmemsize - mdone) ? outmemsize - mdone : mh->buffer.fill;
919
			debug4("buffer fill: %i; copying %i (%i - %li)", (int)mh->buffer.fill, a, (int)outmemsize, (long)mdone);
920
			memcpy(outmemory, mh->buffer.p, a);
921
			/* less data in frame buffer, less needed, output pointer increase, more data given... */
922
			mh->buffer.fill -= a;
923
			outmemory  += a;
924
			mdone += a;
925
			mh->buffer.p += a;
926
			if(!(outmemsize > mdone)) goto decodeend;
927
		}
928
		else /* If we didn't have data, get a new frame. */
929
		{
930
			int b = get_next_frame(mh);
931
			if(b < 0){ ret = b; goto decodeend; }
932
		}
933
	}
934
decodeend:
935
	if(done != NULL) *done = mdone;
936
	return ret;
937
}
938
 
939
long attribute_align_arg mpg123_clip(mpg123_handle *mh)
940
{
941
	long ret = 0;
942
	ALIGNCHECK(mh);
943
	if(mh != NULL)
944
	{
945
		ret = mh->clip;
946
		mh->clip = 0;
947
	}
948
	return ret;
949
}
950
 
951
#define track_need_init(mh) (!(mh)->to_decode && (mh)->fresh)
952
 
953
static int init_track(mpg123_handle *mh)
954
{
955
	if(track_need_init(mh))
956
	{
957
		/* Fresh track, need first frame for basic info. */
958
		int b = get_next_frame(mh);
959
		if(b < 0) return b;
960
	}
961
	return 0;
962
}
963
 
964
int attribute_align_arg mpg123_getformat(mpg123_handle *mh, long *rate, int *channels, int *encoding)
965
{
966
	ALIGNCHECK(mh);
967
	if(mh == NULL) return MPG123_ERR;
968
	if(init_track(mh) == MPG123_ERR) return MPG123_ERR;
969
 
970
	if(rate != NULL) *rate = mh->af.rate;
971
	if(channels != NULL) *channels = mh->af.channels;
972
	if(encoding != NULL) *encoding = mh->af.encoding;
973
	mh->new_format = 0;
974
	return MPG123_OK;
975
}
976
 
977
off_t attribute_align_arg mpg123_timeframe(mpg123_handle *mh, double seconds)
978
{
979
	off_t b;
980
	ALIGNCHECK(mh);
981
	if(mh == NULL) return MPG123_ERR;
982
	b = init_track(mh);
983
	if(b<0) return b;
984
	return (off_t)(seconds/mpg123_tpf(mh));
985
}
986
 
987
/*
988
	Now, where are we? We need to know the last decoded frame... and what's left of it in buffer.
989
	The current frame number can mean the last decoded frame or the to-be-decoded frame.
990
	If mh->to_decode, then mh->num frames have been decoded, the frame mh->num now coming next.
991
	If not, we have the possibility of mh->num+1 frames being decoded or nothing at all.
992
	Then, there is firstframe...when we didn't reach it yet, then the next data will come from there.
993
	mh->num starts with -1
994
*/
995
off_t attribute_align_arg mpg123_tell(mpg123_handle *mh)
996
{
997
	ALIGNCHECK(mh);
998
	if(mh == NULL) return MPG123_ERR;
999
	if(track_need_init(mh)) return 0;
1000
	/* Now we have all the info at hand. */
1001
	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));
1002
 
1003
	{ /* Funny block to keep C89 happy. */
1004
		off_t pos = 0;
1005
		if((mh->num < mh->firstframe) || (mh->num == mh->firstframe && mh->to_decode))
1006
		{ /* We are at the beginning, expect output from firstframe on. */
1007
			pos = frame_outs(mh, mh->firstframe);
1008
#ifdef GAPLESS
1009
			pos += mh->firstoff;
1010
#endif
1011
		}
1012
		else if(mh->to_decode)
1013
		{ /* We start fresh with this frame. Buffer should be empty, but we make sure to count it in.  */
1014
			pos = frame_outs(mh, mh->num) - bytes_to_samples(mh, mh->buffer.fill);
1015
		}
1016
		else
1017
		{ /* We serve what we have in buffer and then the beginning of next frame... */
1018
			pos = frame_outs(mh, mh->num+1) - bytes_to_samples(mh, mh->buffer.fill);
1019
		}
1020
		/* Substract padding and delay from the beginning. */
1021
		pos = SAMPLE_ADJUST(pos);
1022
		/* Negative sample offsets are not right, less than nothing is still nothing. */
1023
		return pos>0 ? pos : 0;
1024
	}
1025
}
1026
 
1027
off_t attribute_align_arg mpg123_tellframe(mpg123_handle *mh)
1028
{
1029
	ALIGNCHECK(mh);
1030
	if(mh == NULL) return MPG123_ERR;
1031
	if(mh->num < mh->firstframe) return mh->firstframe;
1032
	if(mh->to_decode) return mh->num;
1033
	/* Consider firstoff? */
1034
	return mh->buffer.fill ? mh->num : mh->num + 1;
1035
}
1036
 
1037
off_t attribute_align_arg mpg123_tell_stream(mpg123_handle *mh)
1038
{
1039
	ALIGNCHECK(mh);
1040
	if(mh == NULL) return MPG123_ERR;
1041
	/* mh->rd is at least a bad_reader, so no worry. */
1042
	return mh->rd->tell(mh);
1043
}
1044
 
1045
static int do_the_seek(mpg123_handle *mh)
1046
{
1047
	int b;
1048
	off_t fnum = SEEKFRAME(mh);
1049
	mh->buffer.fill = 0;
1050
 
1051
	/* If we are inside the ignoreframe - firstframe window, we may get away without actual seeking. */
1052
	if(mh->num < mh->firstframe)
1053
	{
1054
		mh->to_decode = FALSE; /* In any case, don't decode the current frame, perhaps ignore instead. */
1055
		if(mh->num > fnum) return MPG123_OK;
1056
	}
1057
 
1058
	/* If we are already there, we are fine either for decoding or for ignoring. */
1059
	if(mh->num == fnum && (mh->to_decode || fnum < mh->firstframe)) return MPG123_OK;
1060
	/* We have the frame before... just go ahead as normal. */
1061
	if(mh->num == fnum-1)
1062
	{
1063
		mh->to_decode = FALSE;
1064
		return MPG123_OK;
1065
	}
1066
 
1067
	/* OK, real seeking follows... clear buffers and go for it. */
1068
	frame_buffers_reset(mh);
1069
#ifndef NO_NTOM
1070
	if(mh->down_sample == 3)
1071
	{
1072
		ntom_set_ntom(mh, fnum);
1073
		debug3("fixed ntom for frame %"OFF_P" to %lu, num=%"OFF_P, fnum, mh->ntom_val[0], mh->num);
1074
	}
1075
#endif
1076
	b = mh->rd->seek_frame(mh, fnum);
1077
	debug1("seek_frame returned: %i", b);
1078
	if(b<0) return b;
1079
	/* Only mh->to_ignore is TRUE. */
1080
	if(mh->num < mh->firstframe) mh->to_decode = FALSE;
1081
 
1082
	mh->playnum = mh->num;
1083
	return 0;
1084
}
1085
 
1086
off_t attribute_align_arg mpg123_seek(mpg123_handle *mh, off_t sampleoff, int whence)
1087
{
1088
	int b;
1089
	off_t pos;
1090
	ALIGNCHECK(mh);
1091
	pos = mpg123_tell(mh); /* adjusted samples */
1092
	/* pos < 0 also can mean that simply a former seek failed at the lower levels.
1093
	  In that case, we only allow absolute seeks. */
1094
	if(pos < 0 && whence != SEEK_SET)
1095
	{ /* Unless we got the obvious error of NULL handle, this is a special seek failure. */
1096
		if(mh != NULL) mh->err = MPG123_NO_RELSEEK;
1097
		return MPG123_ERR;
1098
	}
1099
	if((b=init_track(mh)) < 0) return b;
1100
	switch(whence)
1101
	{
1102
		case SEEK_CUR: pos += sampleoff; break;
1103
		case SEEK_SET: pos  = sampleoff; break;
1104
		case SEEK_END:
1105
			/* When we do not know the end already, we can try to find it. */
1106
			if(mh->track_frames < 1 && (mh->rdat.flags & READER_SEEKABLE))
1107
			mpg123_scan(mh);
1108
#ifdef GAPLESS
1109
			if(mh->end_os > 0) pos = SAMPLE_ADJUST(mh->end_os) - sampleoff;
1110
#else
1111
			if(mh->track_frames > 0) pos = SAMPLE_ADJUST(frame_outs(mh, mh->track_frames)) - sampleoff;
1112
#endif
1113
			else
1114
			{
1115
				mh->err = MPG123_NO_SEEK_FROM_END;
1116
				return MPG123_ERR;
1117
			}
1118
		break;
1119
		default: mh->err = MPG123_BAD_WHENCE; return MPG123_ERR;
1120
	}
1121
	if(pos < 0) pos = 0;
1122
	/* pos now holds the wanted sample offset in adjusted samples */
1123
	frame_set_seek(mh, SAMPLE_UNADJUST(pos));
1124
	pos = do_the_seek(mh);
1125
	if(pos < 0) return pos;
1126
 
1127
	return mpg123_tell(mh);
1128
}
1129
 
1130
/*
1131
	A bit more tricky... libmpg123 does not do the seeking itself.
1132
	All it can do is to ignore frames until the wanted one is there.
1133
	The caller doesn't know where a specific frame starts and mpg123 also only knows the general region after it scanned the file.
1134
	Well, it is tricky...
1135
*/
1136
off_t attribute_align_arg mpg123_feedseek(mpg123_handle *mh, off_t sampleoff, int whence, off_t *input_offset)
1137
{
1138
	int b;
1139
	off_t pos;
1140
	ALIGNCHECK(mh);
1141
	pos = mpg123_tell(mh); /* adjusted samples */
1142
	debug3("seek from %li to %li (whence=%i)", (long)pos, (long)sampleoff, whence);
1143
	/* The special seek error handling does not apply here... there is no lowlevel I/O. */
1144
	if(pos < 0) return pos; /* mh == NULL is covered in mpg123_tell() */
1145
	if(input_offset == NULL)
1146
	{
1147
		mh->err = MPG123_NULL_POINTER;
1148
		return MPG123_ERR;
1149
	}
1150
 
1151
	if((b=init_track(mh)) < 0) return b; /* May need more to do anything at all. */
1152
 
1153
	switch(whence)
1154
	{
1155
		case SEEK_CUR: pos += sampleoff; break;
1156
		case SEEK_SET: pos  = sampleoff; break;
1157
		case SEEK_END:
1158
#ifdef GAPLESS
1159
			if(mh->end_os >= 0) pos = SAMPLE_ADJUST(mh->end_os) - sampleoff;
1160
#else
1161
			if(mh->track_frames > 0) pos = SAMPLE_ADJUST(frame_outs(mh, mh->track_frames)) - sampleoff;
1162
#endif
1163
			else
1164
			{
1165
				mh->err = MPG123_NO_SEEK_FROM_END;
1166
				return MPG123_ERR;
1167
			}
1168
		break;
1169
		default: mh->err = MPG123_BAD_WHENCE; return MPG123_ERR;
1170
	}
1171
	if(pos < 0) pos = 0;
1172
	frame_set_seek(mh, SAMPLE_UNADJUST(pos));
1173
	pos = SEEKFRAME(mh);
1174
	mh->buffer.fill = 0;
1175
 
1176
	/* Shortcuts without modifying input stream. */
1177
	*input_offset = mh->rdat.buffer.fileoff + mh->rdat.buffer.size;
1178
	if(mh->num < mh->firstframe) mh->to_decode = FALSE;
1179
	if(mh->num == pos && mh->to_decode) goto feedseekend;
1180
	if(mh->num == pos-1) goto feedseekend;
1181
	/* Whole way. */
1182
	*input_offset = feed_set_pos(mh, frame_index_find(mh, SEEKFRAME(mh), &pos));
1183
	mh->num = pos-1; /* The next read frame will have num = pos. */
1184
	if(*input_offset < 0) return MPG123_ERR;
1185
 
1186
feedseekend:
1187
	return mpg123_tell(mh);
1188
}
1189
 
1190
off_t attribute_align_arg mpg123_seek_frame(mpg123_handle *mh, off_t offset, int whence)
1191
{
1192
	int b;
1193
	off_t pos = 0;
1194
	ALIGNCHECK(mh);
1195
	if(mh == NULL) return MPG123_ERR;
1196
	if((b=init_track(mh)) < 0) return b;
1197
 
1198
	/* Could play games here with to_decode... */
1199
	pos = mh->num;
1200
	switch(whence)
1201
	{
1202
		case SEEK_CUR: pos += offset; break;
1203
		case SEEK_SET: pos  = offset; break;
1204
		case SEEK_END:
1205
			if(mh->track_frames > 0) pos = mh->track_frames - offset;
1206
			else
1207
			{
1208
				mh->err = MPG123_NO_SEEK_FROM_END;
1209
				return MPG123_ERR;
1210
			}
1211
		break;
1212
		default:
1213
			mh->err = MPG123_BAD_WHENCE;
1214
			return MPG123_ERR;
1215
	}
1216
	if(pos < 0) pos = 0;
1217
	/* Hm, do we need to seek right past the end? */
1218
	else if(mh->track_frames > 0 && pos >= mh->track_frames) pos = mh->track_frames;
1219
 
1220
	frame_set_frameseek(mh, pos);
1221
	pos = do_the_seek(mh);
1222
	if(pos < 0) return pos;
1223
 
1224
	return mpg123_tellframe(mh);
1225
}
1226
 
1227
int attribute_align_arg mpg123_set_filesize(mpg123_handle *mh, off_t size)
1228
{
1229
	ALIGNCHECK(mh);
1230
	if(mh == NULL) return MPG123_ERR;
1231
 
1232
	mh->rdat.filelen = size;
1233
	return MPG123_OK;
1234
}
1235
 
1236
off_t attribute_align_arg mpg123_length(mpg123_handle *mh)
1237
{
1238
	int b;
1239
	off_t length;
1240
	ALIGNCHECK(mh);
1241
	if(mh == NULL) return MPG123_ERR;
1242
	b = init_track(mh);
1243
	if(b<0) return b;
1244
	if(mh->track_samples > -1) length = mh->track_samples;
1245
	else if(mh->track_frames > 0) length = mh->track_frames*spf(mh);
1246
	else if(mh->rdat.filelen > 0) /* Let the case of 0 length just fall through. */
1247
	{
1248
		/* A bad estimate. Ignoring tags 'n stuff. */
1249
		double bpf = mh->mean_framesize ? mh->mean_framesize : compute_bpf(mh);
1250
		length = (off_t)((double)(mh->rdat.filelen)/bpf*spf(mh));
1251
	}
1252
	else if(mh->rdat.filelen == 0) return mpg123_tell(mh); /* we could be in feeder mode */
1253
	else return MPG123_ERR; /* No length info there! */
1254
 
1255
	length = frame_ins2outs(mh, length);
1256
#ifdef GAPLESS
1257
	if(mh->end_os > 0 && length > mh->end_os) length = mh->end_os;
1258
	length -= mh->begin_os;
1259
#endif
1260
	return length;
1261
}
1262
 
1263
int attribute_align_arg mpg123_scan(mpg123_handle *mh)
1264
{
1265
	int b;
1266
	off_t backframe;
1267
	int to_decode, to_ignore;
1268
	ALIGNCHECK(mh);
1269
	if(mh == NULL) return MPG123_ERR;
1270
	if(!(mh->rdat.flags & READER_SEEKABLE)){ mh->err = MPG123_NO_SEEK; return MPG123_ERR; }
1271
	/* Scan through the _whole_ file, since the current position is no count but computed assuming constant samples per frame. */
1272
	/* Also, we can just keep the current buffer and seek settings. Just operate on input frames here. */
1273
	debug("issuing scan");
1274
	b = init_track(mh); /* mh->num >= 0 !! */
1275
	if(b<0)
1276
	{
1277
		if(b == MPG123_DONE) return MPG123_OK;
1278
		else return MPG123_ERR; /* Must be error here, NEED_MORE is not for seekable streams. */
1279
	}
1280
	backframe = mh->num;
1281
	to_decode = mh->to_decode;
1282
	to_ignore = mh->to_ignore;
1283
	b = mh->rd->seek_frame(mh, 0);
1284
	if(b<0 || mh->num != 0) return MPG123_ERR;
1285
	/* One frame must be there now. */
1286
	mh->track_frames = 1;
1287
	mh->track_samples = spf(mh); /* Internal samples. */
1288
	while(read_frame(mh) == 1)
1289
	{
1290
		++mh->track_frames;
1291
		mh->track_samples += spf(mh);
1292
	}
1293
#ifdef GAPLESS
1294
	/* Also, think about usefulness of that extra value track_samples ... it could be used for consistency checking. */
1295
	frame_gapless_update(mh, mh->track_samples);
1296
#endif
1297
	b = mh->rd->seek_frame(mh, backframe);
1298
	if(b<0 || mh->num != backframe) return MPG123_ERR;
1299
	mh->to_decode = to_decode;
1300
	mh->to_ignore = to_ignore;
1301
	return MPG123_OK;
1302
}
1303
 
1304
int attribute_align_arg mpg123_meta_check(mpg123_handle *mh)
1305
{
1306
	if(mh != NULL) return mh->metaflags;
1307
	else return 0;
1308
}
1309
 
1310
int attribute_align_arg mpg123_id3(mpg123_handle *mh, mpg123_id3v1 **v1, mpg123_id3v2 **v2)
1311
{
1312
	ALIGNCHECK(mh);
1313
	if(v1 != NULL) *v1 = NULL;
1314
	if(v2 != NULL) *v2 = NULL;
1315
	if(mh == NULL) return MPG123_ERR;
1316
 
1317
	if(mh->metaflags & MPG123_ID3)
1318
	{
1319
		id3_link(mh);
1320
		if(v1 != NULL && mh->rdat.flags & READER_ID3TAG) *v1 = (mpg123_id3v1*) mh->id3buf;
1321
		if(v2 != NULL)
1322
#ifdef NO_ID3V2
1323
		*v2 = NULL;
1324
#else
1325
		*v2 = &mh->id3v2;
1326
#endif
1327
 
1328
		mh->metaflags |= MPG123_ID3;
1329
		mh->metaflags &= ~MPG123_NEW_ID3;
1330
	}
1331
	return MPG123_OK;
1332
}
1333
 
1334
int attribute_align_arg mpg123_icy(mpg123_handle *mh, char **icy_meta)
1335
{
1336
	ALIGNCHECK(mh);
1337
	if(mh == NULL) return MPG123_ERR;
1338
#ifndef NO_ICY
1339
	if(icy_meta == NULL)
1340
	{
1341
		mh->err = MPG123_NULL_POINTER;
1342
		return MPG123_ERR;
1343
	}
1344
	*icy_meta = NULL;
1345
 
1346
	if(mh->metaflags & MPG123_ICY)
1347
	{
1348
		*icy_meta = mh->icy.data;
1349
		mh->metaflags |= MPG123_ICY;
1350
		mh->metaflags &= ~MPG123_NEW_ICY;
1351
	}
1352
	return MPG123_OK;
1353
#else
1354
	mh->err = MPG123_MISSING_FEATURE;
1355
	return MPG123_ERR;
1356
#endif
1357
}
1358
 
1359
/*
1360
	Simple utility functions that do not possibly call code with extra alignment requirements do not use the ALIGNCHECK.
1361
	I am aware of the chance that the compiler could have introduced such code outside assembly functions, but such a modern compiler (gcc) can also honour attribute_align_arg.
1362
*/
1363
 
1364
char* attribute_align_arg mpg123_icy2utf8(const char* icy_text)
1365
{
1366
#ifndef NO_ICY
1367
	return icy2utf8(icy_text, 0);
1368
#else
1369
	return NULL;
1370
#endif
1371
}
1372
 
1373
/* That one is always defined... it's not worth it to remove it for NO_ID3V2. */
1374
enum mpg123_text_encoding attribute_align_arg mpg123_enc_from_id3(unsigned char id3_enc_byte)
1375
{
1376
	switch(id3_enc_byte)
1377
	{
1378
		case mpg123_id3_latin1:   return mpg123_text_latin1;
1379
		case mpg123_id3_utf16bom: return mpg123_text_utf16bom; /* ID3v2.3 has UCS-2 with BOM here. */
1380
		case mpg123_id3_utf16be:  return mpg123_text_utf16be;
1381
		case mpg123_id3_utf8:     return mpg123_text_utf8;
1382
		default: return mpg123_text_unknown;
1383
	}
1384
}
1385
 
1386
#ifndef NO_STRING
1387
int mpg123_store_utf8(mpg123_string *sb, enum mpg123_text_encoding enc, const unsigned char *source, size_t source_size)
1388
{
1389
	switch(enc)
1390
	{
1391
#ifndef NO_ID3V2
1392
		/* The encodings we get from ID3v2 tags. */
1393
		case mpg123_text_utf8:
1394
			id3_to_utf8(sb, mpg123_id3_utf8, source, source_size, 0);
1395
		break;
1396
		case mpg123_text_latin1:
1397
			id3_to_utf8(sb, mpg123_id3_latin1, source, source_size, 0);
1398
		break;
1399
		case mpg123_text_utf16bom:
1400
		case mpg123_text_utf16:
1401
			id3_to_utf8(sb, mpg123_id3_utf16bom, source, source_size, 0);
1402
		break;
1403
		/* Special because one cannot skip zero bytes here. */
1404
		case mpg123_text_utf16be:
1405
			id3_to_utf8(sb, mpg123_id3_utf16be, source, source_size, 0);
1406
		break;
1407
#endif
1408
#ifndef NO_ICY
1409
		/* ICY encoding... */
1410
		case mpg123_text_icy:
1411
		case mpg123_text_cp1252:
1412
		{
1413
			mpg123_free_string(sb);
1414
			/* Paranoia: Make sure that the string ends inside the buffer... */
1415
			if(source[source_size-1] == 0)
1416
			{
1417
				/* Convert from ICY encoding... with force applied or not. */
1418
				char *tmpstring = icy2utf8((const char*)source, enc == mpg123_text_cp1252 ? 1 : 0);
1419
				if(tmpstring != NULL)
1420
				{
1421
					mpg123_set_string(sb, tmpstring);
1422
					free(tmpstring);
1423
				}
1424
			}
1425
		}
1426
		break;
1427
#endif
1428
		default:
1429
			mpg123_free_string(sb);
1430
	}
1431
	/* At least a trailing null of some form should be there... */
1432
	return (sb->fill > 0) ? 1 : 0;
1433
}
1434
#endif
1435
 
1436
int attribute_align_arg mpg123_index(mpg123_handle *mh, off_t **offsets, off_t *step, size_t *fill)
1437
{
1438
	ALIGNCHECK(mh);
1439
	if(mh == NULL) return MPG123_ERR;
1440
	if(offsets == NULL || step == NULL || fill == NULL)
1441
	{
1442
		mh->err = MPG123_BAD_INDEX_PAR;
1443
		return MPG123_ERR;
1444
	}
1445
#ifdef FRAME_INDEX
1446
	*offsets = mh->index.data;
1447
	*step    = mh->index.step;
1448
	*fill    = mh->index.fill;
1449
#else
1450
	*offsets = NULL;
1451
	*step    = 0;
1452
	*fill    = 0;
1453
#endif
1454
	return MPG123_OK;
1455
}
1456
 
1457
int attribute_align_arg mpg123_close(mpg123_handle *mh)
1458
{
1459
	ALIGNCHECK(mh);
1460
	if(mh == NULL) return MPG123_ERR;
1461
	if(mh->rd != NULL && mh->rd->close != NULL) mh->rd->close(mh);
1462
	mh->rd = NULL;
1463
	if(mh->new_format)
1464
	{
1465
		debug("Hey, we are closing a track before the new format has been queried...");
1466
		invalidate_format(&mh->af);
1467
		mh->new_format = 0;
1468
	}
1469
	return MPG123_OK;
1470
}
1471
 
1472
void attribute_align_arg mpg123_delete(mpg123_handle *mh)
1473
{
1474
	if(mh != NULL)
1475
	{
1476
		mpg123_close(mh);
1477
		frame_exit(mh); /* free buffers in frame */
1478
		free(mh); /* free struct; cast? */
1479
	}
1480
}
1481
 
1482
static const char *mpg123_error[] =
1483
{
1484
	"No error... (code 0)",
1485
	"Unable to set up output format! (code 1)",
1486
	"Invalid channel number specified. (code 2)",
1487
	"Invalid sample rate specified. (code 3)",
1488
	"Unable to allocate memory for 16 to 8 converter table! (code 4)",
1489
	"Bad parameter id! (code 5)",
1490
	"Bad buffer given -- invalid pointer or too small size. (code 6)",
1491
	"Out of memory -- some malloc() failed. (code 7)",
1492
	"You didn't initialize the library! (code 8)",
1493
	"Invalid decoder choice. (code 9)",
1494
	"Invalid mpg123 handle. (code 10)",
1495
	"Unable to initialize frame buffers (out of memory?)! (code 11)",
1496
	"Invalid RVA mode. (code 12)",
1497
	"This build doesn't support gapless decoding. (code 13)",
1498
	"Not enough buffer space. (code 14)",
1499
	"Incompatible numeric data types. (code 15)",
1500
	"Bad equalizer band. (code 16)",
1501
	"Null pointer given where valid storage address needed. (code 17)",
1502
	"Error reading the stream. (code 18)",
1503
	"Cannot seek from end (end is not known). (code 19)",
1504
	"Invalid 'whence' for seek function. (code 20)",
1505
	"Build does not support stream timeouts. (code 21)",
1506
	"File access error. (code 22)",
1507
	"Seek not supported by stream. (code 23)",
1508
	"No stream opened. (code 24)",
1509
	"Bad parameter handle. (code 25)",
1510
	"Invalid parameter addresses for index retrieval. (code 26)",
1511
	"Lost track in the bytestream and did not attempt resync. (code 27)",
1512
	"Failed to find valid MPEG data within limit on resync. (code 28)",
1513
	"No 8bit encoding possible. (code 29)",
1514
	"Stack alignment is not good. (code 30)",
1515
	"You gave me a NULL buffer? (code 31)",
1516
	"File position is screwed up, please do an absolute seek (code 32)",
1517
	"Inappropriate NULL-pointer provided.",
1518
	"Bad key value given.",
1519
	"There is no frame index (disabled in this build).",
1520
	"Frame index operation failed.",
1521
	"Decoder setup failed (invalid combination of settings?)",
1522
	"Feature not in this build."
1523
	,"Some bad value has been provided."
1524
	,"Low-level seeking has failed (call to lseek(), usually)."
1525
};
1526
 
1527
const char* attribute_align_arg mpg123_plain_strerror(int errcode)
1528
{
1529
	if(errcode >= 0 && errcode < sizeof(mpg123_error)/sizeof(char*))
1530
	return mpg123_error[errcode];
1531
	else switch(errcode)
1532
	{
1533
		case MPG123_ERR:
1534
			return "A generic mpg123 error.";
1535
		case MPG123_DONE:
1536
			return "Message: I am done with this track.";
1537
		case MPG123_NEED_MORE:
1538
			return "Message: Feed me more input data!";
1539
		case MPG123_NEW_FORMAT:
1540
			return "Message: Prepare for a changed audio format (query the new one)!";
1541
		default:
1542
			return "I have no idea - an unknown error code!";
1543
	}
1544
}
1545
 
1546
int attribute_align_arg mpg123_errcode(mpg123_handle *mh)
1547
{
1548
	if(mh != NULL) return mh->err;
1549
	return MPG123_BAD_HANDLE;
1550
}
1551
 
1552
const char* attribute_align_arg mpg123_strerror(mpg123_handle *mh)
1553
{
1554
	return mpg123_plain_strerror(mpg123_errcode(mh));
1555
}