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