1 /*
2 frame: Heap of routines dealing with the core mpg123 data structure.
3
4 copyright 2008-2021 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 initially written by Thomas Orgis
7 */
8
9 #define WANT_GETCPUFLAGS
10 #include "mpg123lib_intern.h"
11 #include "getcpuflags.h"
12 #include "debug.h"
13
14 static void frame_fixed_reset(mpg123_handle *fr);
15
16 /* that's doubled in decode_ntom.c */
17 #define NTOM_MUL (32768)
18
19 #define aligned_pointer(p, type, alignment) align_the_pointer(p, alignment)
align_the_pointer(void * base,unsigned int alignment)20 static void *align_the_pointer(void *base, unsigned int alignment)
21 {
22 /*
23 Work in unsigned integer realm, explicitly.
24 Tricking the compiler into integer operations like % by invoking base-NULL is dangerous: It results into ptrdiff_t, which gets negative on big addresses. Big screw up, that.
25 I try to do it "properly" here: Casting only to uintptr_t and no artihmethic with void*.
26 */
27 uintptr_t baseval = (uintptr_t)(char*)base;
28 uintptr_t aoff = baseval % alignment;
29
30 debug3("align_the_pointer: pointer %p is off by %u from %u",
31 base, (unsigned int)aoff, alignment);
32
33 if(aoff) return (char*)base+alignment-aoff;
34 else return base;
35 }
36
frame_default_pars(mpg123_pars * mp)37 static void frame_default_pars(mpg123_pars *mp)
38 {
39 mp->outscale = 1.0;
40 mp->flags = 0;
41 #ifdef GAPLESS
42 mp->flags |= MPG123_GAPLESS;
43 #endif
44 mp->flags |= MPG123_AUTO_RESAMPLE|MPG123_FLOAT_FALLBACK;
45 #ifndef NO_NTOM
46 mp->force_rate = 0;
47 #endif
48 mp->down_sample = 0;
49 mp->rva = 0;
50 mp->halfspeed = 0;
51 mp->doublespeed = 0;
52 mp->verbose = 0;
53 #ifndef NO_ICY
54 mp->icy_interval = 0;
55 #endif
56 mp->timeout = 0;
57 mp->resync_limit = 1024;
58 #ifdef FRAME_INDEX
59 mp->index_size = INDEX_SIZE;
60 #endif
61 mp->preframes = 4; /* That's good for layer 3 ISO compliance bitstream. */
62 mpg123_fmt_all(mp);
63 /* Default of keeping some 4K buffers at hand, should cover the "usual" use case (using 16K pipe buffers as role model). */
64 #ifndef NO_FEEDER
65 mp->feedpool = 5;
66 mp->feedbuffer = 4096;
67 #endif
68 mp->freeformat_framesize = -1;
69 }
70
frame_init(mpg123_handle * fr)71 void frame_init(mpg123_handle *fr)
72 {
73 frame_init_par(fr, NULL);
74 }
75
frame_init_par(mpg123_handle * fr,mpg123_pars * mp)76 void frame_init_par(mpg123_handle *fr, mpg123_pars *mp)
77 {
78 fr->own_buffer = TRUE;
79 fr->buffer.data = NULL;
80 fr->buffer.rdata = NULL;
81 fr->buffer.fill = 0;
82 fr->buffer.size = 0;
83 fr->rawbuffs = NULL;
84 fr->rawbuffss = 0;
85 fr->rawdecwin = NULL;
86 fr->rawdecwins = 0;
87 #ifdef REAL_IS_FIXED
88 fr->gainpow2 = NULL; // At least crash early if I get it wrong.
89 #endif
90 #ifndef NO_8BIT
91 fr->conv16to8_buf = NULL;
92 #endif
93 #ifdef OPT_DITHER
94 fr->dithernoise = NULL;
95 #endif
96 fr->layerscratch = NULL;
97 fr->xing_toc = NULL;
98 #ifdef OPT_CPU_FLAGS
99 wrap_getcpuflags(&(fr->cpu_flags));
100 #endif
101 fr->cpu_opts.type = defdec();
102 fr->cpu_opts.class = decclass(fr->cpu_opts.type);
103 #ifndef NO_NTOM
104 /* these two look unnecessary, check guarantee for synth_ntom_set_step (in control_generic, even)! */
105 fr->ntom_val[0] = NTOM_MUL>>1;
106 fr->ntom_val[1] = NTOM_MUL>>1;
107 fr->ntom_step = NTOM_MUL;
108 #endif
109 /* unnecessary: fr->buffer.size = fr->buffer.fill = 0; */
110 mpg123_reset_eq(fr);
111 init_icy(&fr->icy);
112 init_id3(fr);
113 /* frame_outbuffer is missing... */
114 /* frame_buffers is missing... that one needs cpu opt setting! */
115 /* after these... frame_reset is needed before starting full decode */
116 invalidate_format(&fr->af);
117 fr->rdat.r_read = NULL;
118 fr->rdat.r_lseek = NULL;
119 fr->rdat.iohandle = NULL;
120 fr->rdat.r_read_handle = NULL;
121 fr->rdat.r_lseek_handle = NULL;
122 fr->rdat.cleanup_handle = NULL;
123 fr->wrapperdata = NULL;
124 fr->wrapperclean = NULL;
125 fr->decoder_change = 1;
126 fr->err = MPG123_OK;
127 if(mp == NULL) frame_default_pars(&fr->p);
128 else memcpy(&fr->p, mp, sizeof(struct mpg123_pars_struct));
129
130 #ifndef NO_FEEDER
131 bc_prepare(&fr->rdat.buffer, fr->p.feedpool, fr->p.feedbuffer);
132 #endif
133
134 fr->down_sample = 0; /* Initialize to silence harmless errors when debugging. */
135 fr->id3v2_raw = NULL;
136 frame_fixed_reset(fr); /* Reset only the fixed data, dynamic buffers are not there yet! */
137 fr->synth = NULL;
138 fr->synth_mono = NULL;
139 fr->make_decode_tables = NULL;
140 #ifdef FRAME_INDEX
141 fi_init(&fr->index);
142 frame_index_setup(fr); /* Apply the size setting. */
143 #endif
144 #ifndef NO_MOREINFO
145 fr->pinfo = NULL;
146 #endif
147 }
148
149 #ifdef OPT_DITHER
150 /* Also, only allocate the memory for the table on demand.
151 In future, one could create special noise for different sampling frequencies(?). */
frame_dither_init(mpg123_handle * fr)152 int frame_dither_init(mpg123_handle *fr)
153 {
154 /* run-time dither noise table generation */
155 if(fr->dithernoise == NULL)
156 {
157 fr->dithernoise = malloc(sizeof(float)*DITHERSIZE);
158 if(fr->dithernoise == NULL) return 0;
159
160 dither_table_init(fr->dithernoise);
161 }
162 return 1;
163 }
164 #endif
165
mpg123_new_pars(int * error)166 mpg123_pars attribute_align_arg *mpg123_new_pars(int *error)
167 {
168 mpg123_pars *mp = malloc(sizeof(struct mpg123_pars_struct));
169 if(mp != NULL){ frame_default_pars(mp); if(error != NULL) *error = MPG123_OK; }
170 else if(error != NULL) *error = MPG123_OUT_OF_MEM;
171 return mp;
172 }
173
mpg123_delete_pars(mpg123_pars * mp)174 void attribute_align_arg mpg123_delete_pars(mpg123_pars* mp)
175 {
176 if(mp != NULL) free(mp);
177 }
178
mpg123_reset_eq(mpg123_handle * mh)179 int attribute_align_arg mpg123_reset_eq(mpg123_handle *mh)
180 {
181 if(mh == NULL) return MPG123_BAD_HANDLE;
182 #ifndef NO_EQUALIZER
183 int i;
184 mh->have_eq_settings = 0;
185 for(i=0; i < 32; ++i) mh->equalizer[0][i] = mh->equalizer[1][i] = DOUBLE_TO_REAL(1.0);
186 #endif
187 return MPG123_OK;
188 }
189
frame_outbuffer(mpg123_handle * fr)190 int frame_outbuffer(mpg123_handle *fr)
191 {
192 size_t size = fr->outblock;
193 if(!fr->own_buffer)
194 {
195 if(fr->buffer.size < size)
196 {
197 fr->err = MPG123_BAD_BUFFER;
198 if(NOQUIET)
199 merror( "have external buffer of size %"SIZE_P", need %"SIZE_P
200 , (size_p)fr->buffer.size, (size_p)size );
201 return MPG123_ERR;
202 }
203 }
204
205 debug1("need frame buffer of %"SIZE_P, (size_p)size);
206 if(fr->buffer.rdata != NULL && fr->buffer.size != size)
207 {
208 free(fr->buffer.rdata);
209 fr->buffer.rdata = NULL;
210 }
211 fr->buffer.size = size;
212 fr->buffer.data = NULL;
213 /* be generous: use 16 byte alignment */
214 if(fr->buffer.rdata == NULL) fr->buffer.rdata = (unsigned char*) malloc(fr->buffer.size+15);
215 if(fr->buffer.rdata == NULL)
216 {
217 fr->err = MPG123_OUT_OF_MEM;
218 return MPG123_ERR;
219 }
220 fr->buffer.data = aligned_pointer(fr->buffer.rdata, unsigned char*, 16);
221 fr->own_buffer = TRUE;
222 fr->buffer.fill = 0;
223 return MPG123_OK;
224 }
225
mpg123_replace_buffer(mpg123_handle * mh,void * data,size_t size)226 int attribute_align_arg mpg123_replace_buffer(mpg123_handle *mh, void *data, size_t size)
227 {
228 debug2("replace buffer with %p size %"SIZE_P, data, (size_p)size);
229 if(mh == NULL) return MPG123_BAD_HANDLE;
230 /* Will accept any size, the error comes later... */
231 if(data == NULL)
232 {
233 mh->err = MPG123_BAD_BUFFER;
234 return MPG123_ERR;
235 }
236 if(mh->buffer.rdata != NULL) free(mh->buffer.rdata);
237 mh->own_buffer = FALSE;
238 mh->buffer.rdata = NULL;
239 mh->buffer.data = data;
240 mh->buffer.size = size;
241 mh->buffer.fill = 0;
242 return MPG123_OK;
243 }
244
245 #ifdef FRAME_INDEX
frame_index_setup(mpg123_handle * fr)246 int frame_index_setup(mpg123_handle *fr)
247 {
248 int ret = MPG123_ERR;
249 if(fr->p.index_size >= 0)
250 { /* Simple fixed index. */
251 fr->index.grow_size = 0;
252 ret = fi_resize(&fr->index, (size_t)fr->p.index_size);
253 }
254 else
255 { /* A growing index. We give it a start, though. */
256 fr->index.grow_size = (size_t)(- fr->p.index_size);
257 if(fr->index.size < fr->index.grow_size)
258 ret = fi_resize(&fr->index, fr->index.grow_size);
259 else
260 ret = MPG123_OK; /* We have minimal size already... and since growing is OK... */
261 }
262 debug2("set up frame index of size %lu (ret=%i)", (unsigned long)fr->index.size, ret);
263 if(ret && NOQUIET)
264 error("frame index setup (initial resize) failed");
265 return ret;
266 }
267 #endif
268
frame_decode_buffers_reset(mpg123_handle * fr)269 static void frame_decode_buffers_reset(mpg123_handle *fr)
270 {
271 if(fr->rawbuffs) /* memset(NULL, 0, 0) not desired */
272 memset(fr->rawbuffs, 0, fr->rawbuffss);
273 }
274
frame_buffers(mpg123_handle * fr)275 int frame_buffers(mpg123_handle *fr)
276 {
277 int buffssize = 0;
278 debug1("frame %p buffer", (void*)fr);
279 /*
280 the used-to-be-static buffer of the synth functions, has some subtly different types/sizes
281
282 2to1, 4to1, ntom, generic, i386: real[2][2][0x110]
283 mmx, sse: short[2][2][0x110]
284 i586(_dither): 4352 bytes; int/long[2][2][0x110]
285 i486: int[2][2][17*FIR_BUFFER_SIZE]
286 altivec: static real __attribute__ ((aligned (16))) buffs[4][4][0x110]
287
288 Huh, altivec looks like fun. Well, let it be large... then, the 16 byte alignment seems to be implicit on MacOSX malloc anyway.
289 Let's make a reasonable attempt to allocate enough memory...
290 Keep in mind: biggest ones are i486 and altivec (mutually exclusive!), then follows i586 and normal real.
291 mmx/sse use short but also real for resampling.
292 Thus, minimum is 2*2*0x110*sizeof(real).
293 */
294 if(fr->cpu_opts.type == altivec) buffssize = 4*4*0x110*sizeof(real);
295 #ifdef OPT_I486
296 else if(fr->cpu_opts.type == ivier) buffssize = 2*2*17*FIR_BUFFER_SIZE*sizeof(int);
297 #endif
298 else if(fr->cpu_opts.type == ifuenf || fr->cpu_opts.type == ifuenf_dither || fr->cpu_opts.type == dreidnow)
299 buffssize = 2*2*0x110*4; /* don't rely on type real, we need 4352 bytes */
300
301 if(2*2*0x110*sizeof(real) > buffssize)
302 buffssize = 2*2*0x110*sizeof(real);
303 buffssize += 15; /* For 16-byte alignment (SSE likes that). */
304
305 if(fr->rawbuffs != NULL && fr->rawbuffss != buffssize)
306 {
307 free(fr->rawbuffs);
308 fr->rawbuffs = NULL;
309 }
310
311 if(fr->rawbuffs == NULL) fr->rawbuffs = (unsigned char*) malloc(buffssize);
312 if(fr->rawbuffs == NULL) return -1;
313 fr->rawbuffss = buffssize;
314 fr->short_buffs[0][0] = aligned_pointer(fr->rawbuffs,short,16);
315 fr->short_buffs[0][1] = fr->short_buffs[0][0] + 0x110;
316 fr->short_buffs[1][0] = fr->short_buffs[0][1] + 0x110;
317 fr->short_buffs[1][1] = fr->short_buffs[1][0] + 0x110;
318 fr->real_buffs[0][0] = aligned_pointer(fr->rawbuffs,real,16);
319 fr->real_buffs[0][1] = fr->real_buffs[0][0] + 0x110;
320 fr->real_buffs[1][0] = fr->real_buffs[0][1] + 0x110;
321 fr->real_buffs[1][1] = fr->real_buffs[1][0] + 0x110;
322 #ifdef OPT_I486
323 if(fr->cpu_opts.type == ivier)
324 {
325 fr->int_buffs[0][0] = (int*) fr->rawbuffs;
326 fr->int_buffs[0][1] = fr->int_buffs[0][0] + 17*FIR_BUFFER_SIZE;
327 fr->int_buffs[1][0] = fr->int_buffs[0][1] + 17*FIR_BUFFER_SIZE;
328 fr->int_buffs[1][1] = fr->int_buffs[1][0] + 17*FIR_BUFFER_SIZE;
329 }
330 #endif
331 #ifdef OPT_ALTIVEC
332 if(fr->cpu_opts.type == altivec)
333 {
334 int i,j;
335 fr->areal_buffs[0][0] = (real*) fr->rawbuffs;
336 for(i=0; i<4; ++i) for(j=0; j<4; ++j)
337 fr->areal_buffs[i][j] = fr->areal_buffs[0][0] + (i*4+j)*0x110;
338 }
339 #endif
340 /* now the different decwins... all of the same size, actually */
341 /* The MMX ones want 32byte alignment, which I'll try to ensure manually */
342 {
343 int decwin_size = (512+32)*sizeof(real);
344 #ifdef OPT_MMXORSSE
345 #ifdef OPT_MULTI
346 if(fr->cpu_opts.class == mmxsse)
347 {
348 #endif
349 /* decwin_mmx will share, decwins will be appended ... sizeof(float)==4 */
350 if(decwin_size < (512+32)*4) decwin_size = (512+32)*4;
351
352 /* the second window + alignment zone -- we align for 32 bytes for SSE as
353 requirement, 64 byte for matching cache line size (that matters!) */
354 decwin_size += (512+32)*4 + 63;
355 /* (512+32)*4/32 == 2176/32 == 68, so one decwin block retains alignment for 32 or 64 bytes */
356 #ifdef OPT_MULTI
357 }
358 #endif
359 #endif
360 #if defined(OPT_ALTIVEC) || defined(OPT_ARM)
361 /* sizeof(real) >= 4 ... yes, it could be 8, for example.
362 We got it intialized to at least (512+32)*sizeof(real).*/
363 decwin_size += 512*sizeof(real);
364 #endif
365 /* Hm, that's basically realloc() ... */
366 if(fr->rawdecwin != NULL && fr->rawdecwins != decwin_size)
367 {
368 free(fr->rawdecwin);
369 fr->rawdecwin = NULL;
370 }
371
372 if(fr->rawdecwin == NULL)
373 fr->rawdecwin = (unsigned char*) malloc(decwin_size);
374
375 if(fr->rawdecwin == NULL) return -1;
376
377 fr->rawdecwins = decwin_size;
378 fr->decwin = (real*) fr->rawdecwin;
379 #ifdef OPT_MMXORSSE
380 #ifdef OPT_MULTI
381 if(fr->cpu_opts.class == mmxsse)
382 {
383 #endif
384 /* align decwin, assign that to decwin_mmx, append decwins */
385 /* I need to add to decwin what is missing to the next full 64 byte -- also I want to make gcc -pedantic happy... */
386 fr->decwin = aligned_pointer(fr->rawdecwin,real,64);
387 debug1("aligned decwin: %p", (void*)fr->decwin);
388 fr->decwin_mmx = (float*)fr->decwin;
389 fr->decwins = fr->decwin_mmx+512+32;
390 #ifdef OPT_MULTI
391 }
392 else debug("no decwins/decwin_mmx for that class");
393 #endif
394 #endif
395 }
396
397 /* Layer scratch buffers are of compile-time fixed size, so allocate only once. */
398 if(fr->layerscratch == NULL)
399 {
400 /* Allocate specific layer1/2/3 buffers, so that we know they'll work for SSE. */
401 size_t scratchsize = 0;
402 real *scratcher;
403 #ifndef NO_LAYER1
404 scratchsize += sizeof(real) * 2 * SBLIMIT;
405 #endif
406 #ifndef NO_LAYER2
407 scratchsize += sizeof(real) * 2 * 4 * SBLIMIT;
408 #endif
409 #ifndef NO_LAYER3
410 scratchsize += sizeof(real) * 2 * SBLIMIT * SSLIMIT; /* hybrid_in */
411 scratchsize += sizeof(real) * 2 * SSLIMIT * SBLIMIT; /* hybrid_out */
412 #endif
413 /*
414 Now figure out correct alignment:
415 We need 16 byte minimum, smallest unit of the blocks is 2*SBLIMIT*sizeof(real), which is 64*4=256. Let's do 64bytes as heuristic for cache line (as proven useful in buffs above).
416 */
417 fr->layerscratch = malloc(scratchsize+63);
418 if(fr->layerscratch == NULL) return -1;
419
420 /* Get aligned part of the memory, then divide it up. */
421 scratcher = aligned_pointer(fr->layerscratch,real,64);
422 /* Those funky pointer casts silence compilers...
423 One might change the code at hand to really just use 1D arrays, but in practice, that would not make a (positive) difference. */
424 #ifndef NO_LAYER1
425 fr->layer1.fraction = (real(*)[SBLIMIT])scratcher;
426 scratcher += 2 * SBLIMIT;
427 #endif
428 #ifndef NO_LAYER2
429 fr->layer2.fraction = (real(*)[4][SBLIMIT])scratcher;
430 scratcher += 2 * 4 * SBLIMIT;
431 #endif
432 #ifndef NO_LAYER3
433 fr->layer3.hybrid_in = (real(*)[SBLIMIT][SSLIMIT])scratcher;
434 scratcher += 2 * SBLIMIT * SSLIMIT;
435 fr->layer3.hybrid_out = (real(*)[SSLIMIT][SBLIMIT])scratcher;
436 scratcher += 2 * SSLIMIT * SBLIMIT;
437 #endif
438 /* Note: These buffers don't need resetting here. */
439 }
440
441 /* Only reset the buffers we created just now. */
442 frame_decode_buffers_reset(fr);
443
444 debug1("frame %p buffer done", (void*)fr);
445 return 0;
446 }
447
frame_buffers_reset(mpg123_handle * fr)448 int frame_buffers_reset(mpg123_handle *fr)
449 {
450 fr->buffer.fill = 0; /* hm, reset buffer fill... did we do a flush? */
451 fr->bsnum = 0;
452 /* Wondering: could it be actually _wanted_ to retain buffer contents over different files? (special gapless / cut stuff) */
453 fr->bsbuf = fr->bsspace[1];
454 fr->bsbufold = fr->bsbuf;
455 fr->bitreservoir = 0;
456 frame_decode_buffers_reset(fr);
457 memset(fr->bsspace, 0, 2*(MAXFRAMESIZE+512));
458 memset(fr->ssave, 0, 34);
459 fr->hybrid_blc[0] = fr->hybrid_blc[1] = 0;
460 memset(fr->hybrid_block, 0, sizeof(real)*2*2*SBLIMIT*SSLIMIT);
461 return 0;
462 }
463
frame_icy_reset(mpg123_handle * fr)464 static void frame_icy_reset(mpg123_handle* fr)
465 {
466 #ifndef NO_ICY
467 if(fr->icy.data != NULL) free(fr->icy.data);
468 fr->icy.data = NULL;
469 fr->icy.interval = 0;
470 fr->icy.next = 0;
471 #endif
472 }
473
frame_free_toc(mpg123_handle * fr)474 static void frame_free_toc(mpg123_handle *fr)
475 {
476 if(fr->xing_toc != NULL){ free(fr->xing_toc); fr->xing_toc = NULL; }
477 }
478
479 /* Just copy the Xing TOC over... */
frame_fill_toc(mpg123_handle * fr,unsigned char * in)480 int frame_fill_toc(mpg123_handle *fr, unsigned char* in)
481 {
482 if(fr->xing_toc == NULL) fr->xing_toc = malloc(100);
483 if(fr->xing_toc != NULL)
484 {
485 memcpy(fr->xing_toc, in, 100);
486 #ifdef DEBUG
487 debug("Got a TOC! Showing the values...");
488 {
489 int i;
490 for(i=0; i<100; ++i)
491 debug2("entry %i = %i", i, fr->xing_toc[i]);
492 }
493 #endif
494 return TRUE;
495 }
496 return FALSE;
497 }
498
499 /* Prepare the handle for a new track.
500 Reset variables, buffers... */
frame_reset(mpg123_handle * fr)501 int frame_reset(mpg123_handle* fr)
502 {
503 frame_buffers_reset(fr);
504 frame_fixed_reset(fr);
505 frame_free_toc(fr);
506 #ifdef FRAME_INDEX
507 fi_reset(&fr->index);
508 #endif
509
510 return 0;
511 }
512
513 /* Reset everythign except dynamic memory. */
frame_fixed_reset(mpg123_handle * fr)514 static void frame_fixed_reset(mpg123_handle *fr)
515 {
516 frame_icy_reset(fr);
517 open_bad(fr);
518 fr->to_decode = FALSE;
519 fr->to_ignore = FALSE;
520 fr->metaflags = 0;
521 fr->outblock = 0; /* This will be set before decoding! */
522 fr->num = -1;
523 fr->input_offset = -1;
524 fr->playnum = -1;
525 fr->state_flags = FRAME_ACCURATE;
526 fr->silent_resync = 0;
527 fr->audio_start = 0;
528 fr->clip = 0;
529 fr->oldhead = 0;
530 fr->firsthead = 0;
531 fr->lay = 0;
532 fr->vbr = MPG123_CBR;
533 fr->abr_rate = 0;
534 fr->track_frames = 0;
535 fr->track_samples = -1;
536 fr->framesize=0;
537 fr->mean_frames = 0;
538 fr->mean_framesize = 0;
539 fr->freesize = 0;
540 fr->lastscale = -1;
541 fr->rva.level[0] = -1;
542 fr->rva.level[1] = -1;
543 fr->rva.gain[0] = 0;
544 fr->rva.gain[1] = 0;
545 fr->rva.peak[0] = 0;
546 fr->rva.peak[1] = 0;
547 fr->fsizeold = 0;
548 fr->firstframe = 0;
549 fr->ignoreframe = fr->firstframe-fr->p.preframes;
550 fr->header_change = 0;
551 fr->lastframe = -1;
552 fr->fresh = 1;
553 fr->new_format = 0;
554 #ifdef GAPLESS
555 frame_gapless_init(fr,-1,0,0);
556 fr->lastoff = 0;
557 fr->firstoff = 0;
558 #endif
559 #ifdef OPT_I486
560 fr->i486bo[0] = fr->i486bo[1] = FIR_SIZE-1;
561 #endif
562 fr->bo = 1; /* the usual bo */
563 #ifdef OPT_DITHER
564 fr->ditherindex = 0;
565 #endif
566 reset_id3(fr);
567 reset_icy(&fr->icy);
568 /* ICY stuff should go into icy.c, eh? */
569 #ifndef NO_ICY
570 fr->icy.interval = 0;
571 fr->icy.next = 0;
572 #endif
573 fr->halfphase = 0; /* here or indeed only on first-time init? */
574 fr->error_protection = 0;
575 fr->freeformat_framesize = fr->p.freeformat_framesize;
576 fr->enc_delay = -1;
577 fr->enc_padding = -1;
578 memset(fr->id3buf, 0, sizeof(fr->id3buf));
579 if(fr->id3v2_raw)
580 free(fr->id3v2_raw);
581 fr->id3v2_raw = NULL;
582 fr->id3v2_size = 0;
583 }
584
frame_free_buffers(mpg123_handle * fr)585 static void frame_free_buffers(mpg123_handle *fr)
586 {
587 if(fr->rawbuffs != NULL) free(fr->rawbuffs);
588 fr->rawbuffs = NULL;
589 fr->rawbuffss = 0;
590 if(fr->rawdecwin != NULL) free(fr->rawdecwin);
591 fr->rawdecwin = NULL;
592 fr->rawdecwins = 0;
593 #ifndef NO_8BIT
594 if(fr->conv16to8_buf != NULL) free(fr->conv16to8_buf);
595 fr->conv16to8_buf = NULL;
596 #endif
597 if(fr->layerscratch != NULL) free(fr->layerscratch);
598 }
599
frame_exit(mpg123_handle * fr)600 void frame_exit(mpg123_handle *fr)
601 {
602 if(fr->buffer.rdata != NULL)
603 {
604 debug1("freeing buffer at %p", (void*)fr->buffer.rdata);
605 free(fr->buffer.rdata);
606 }
607 fr->buffer.rdata = NULL;
608 frame_free_buffers(fr);
609 frame_free_toc(fr);
610 #ifdef FRAME_INDEX
611 fi_exit(&fr->index);
612 #endif
613 #ifdef OPT_DITHER
614 if(fr->dithernoise != NULL)
615 {
616 free(fr->dithernoise);
617 fr->dithernoise = NULL;
618 }
619 #endif
620 exit_id3(fr);
621 clear_icy(&fr->icy);
622 /* Clean up possible mess from LFS wrapper. */
623 if(fr->wrapperclean != NULL)
624 {
625 fr->wrapperclean(fr->wrapperdata);
626 fr->wrapperdata = NULL;
627 }
628 #ifndef NO_FEEDER
629 bc_cleanup(&fr->rdat.buffer);
630 #endif
631 }
632
mpg123_framedata(mpg123_handle * mh,unsigned long * header,unsigned char ** bodydata,size_t * bodybytes)633 int attribute_align_arg mpg123_framedata(mpg123_handle *mh, unsigned long *header, unsigned char **bodydata, size_t *bodybytes)
634 {
635 if(mh == NULL) return MPG123_BAD_HANDLE;
636 if(!mh->to_decode) return MPG123_ERR;
637
638 if(header != NULL) *header = mh->oldhead;
639 if(bodydata != NULL) *bodydata = mh->bsbuf;
640 if(bodybytes != NULL) *bodybytes = mh->framesize;
641
642 return MPG123_OK;
643 }
644
mpg123_set_moreinfo(mpg123_handle * mh,struct mpg123_moreinfo * mi)645 int attribute_align_arg mpg123_set_moreinfo( mpg123_handle *mh
646 , struct mpg123_moreinfo *mi)
647 {
648 #ifndef NO_MOREINFO
649 mh->pinfo = mi;
650 return MPG123_OK;
651 #else
652 mh->err = MPG123_MISSING_FEATURE;
653 return MPG123_ERR;
654 #endif
655 }
656
657 /*
658 Fuzzy frame offset searching (guessing).
659 When we don't have an accurate position, we may use an inaccurate one.
660 Possibilities:
661 - use approximate positions from Xing TOC (not yet parsed)
662 - guess wildly from mean framesize and offset of first frame / beginning of file.
663 */
664
frame_fuzzy_find(mpg123_handle * fr,off_t want_frame,off_t * get_frame)665 static off_t frame_fuzzy_find(mpg123_handle *fr, off_t want_frame, off_t* get_frame)
666 {
667 /* Default is to go to the beginning. */
668 off_t ret = fr->audio_start;
669 *get_frame = 0;
670
671 /* But we try to find something better. */
672 /* Xing VBR TOC works with relative positions, both in terms of audio frames and stream bytes.
673 Thus, it only works when whe know the length of things.
674 Oh... I assume the offsets are relative to the _total_ file length. */
675 if(fr->xing_toc != NULL && fr->track_frames > 0 && fr->rdat.filelen > 0)
676 {
677 /* One could round... */
678 int toc_entry = (int) ((double)want_frame*100./fr->track_frames);
679 /* It is an index in the 100-entry table. */
680 if(toc_entry < 0) toc_entry = 0;
681 if(toc_entry > 99) toc_entry = 99;
682
683 /* Now estimate back what frame we get. */
684 *get_frame = (off_t) ((double)toc_entry/100. * fr->track_frames);
685 fr->state_flags &= ~FRAME_ACCURATE;
686 fr->silent_resync = 1;
687 /* Question: Is the TOC for whole file size (with/without ID3) or the "real" audio data only?
688 ID3v1 info could also matter. */
689 ret = (off_t) ((double)fr->xing_toc[toc_entry]/256.* fr->rdat.filelen);
690 }
691 else if(fr->mean_framesize > 0)
692 { /* Just guess with mean framesize (may be exact with CBR files). */
693 /* Query filelen here or not? */
694 fr->state_flags &= ~FRAME_ACCURATE; /* Fuzzy! */
695 fr->silent_resync = 1;
696 *get_frame = want_frame;
697 ret = (off_t) (fr->audio_start+fr->mean_framesize*want_frame);
698 }
699 debug5("fuzzy: want %li of %li, get %li at %li B of %li B",
700 (long)want_frame, (long)fr->track_frames, (long)*get_frame, (long)ret, (long)(fr->rdat.filelen-fr->audio_start));
701 return ret;
702 }
703
704 /*
705 find the best frame in index just before the wanted one, seek to there
706 then step to just before wanted one with read_frame
707 do not care tabout the stuff that was in buffer but not played back
708 everything that left the decoder is counted as played
709
710 Decide if you want low latency reaction and accurate timing info or stable long-time playback with buffer!
711 */
712
frame_index_find(mpg123_handle * fr,off_t want_frame,off_t * get_frame)713 off_t frame_index_find(mpg123_handle *fr, off_t want_frame, off_t* get_frame)
714 {
715 /* default is file start if no index position */
716 off_t gopos = 0;
717 *get_frame = 0;
718 #ifdef FRAME_INDEX
719 /* Possibly use VBRI index, too? I'd need an example for this... */
720 if(fr->index.fill)
721 {
722 /* find in index */
723 size_t fi;
724 /* at index fi there is frame step*fi... */
725 fi = want_frame/fr->index.step;
726 if(fi >= fr->index.fill) /* If we are beyond the end of frame index...*/
727 {
728 /* When fuzzy seek is allowed, we have some limited tolerance for the frames we want to read rather then jump over. */
729 if(fr->p.flags & MPG123_FUZZY && want_frame - (fr->index.fill-1)*fr->index.step > 10)
730 {
731 gopos = frame_fuzzy_find(fr, want_frame, get_frame);
732 if(gopos > fr->audio_start) return gopos; /* Only in that case, we have a useful guess. */
733 /* Else... just continue, fuzzyness didn't help. */
734 }
735 /* Use the last available position, slowly advancing from that one. */
736 fi = fr->index.fill - 1;
737 }
738 /* We have index position, that yields frame and byte offsets. */
739 *get_frame = fi*fr->index.step;
740 gopos = fr->index.data[fi];
741 fr->state_flags |= FRAME_ACCURATE; /* When using the frame index, we are accurate. */
742 }
743 else
744 {
745 #endif
746 if(fr->p.flags & MPG123_FUZZY)
747 return frame_fuzzy_find(fr, want_frame, get_frame);
748 /* A bit hackish here... but we need to be fresh when looking for the first header again. */
749 fr->firsthead = 0;
750 fr->oldhead = 0;
751 #ifdef FRAME_INDEX
752 }
753 #endif
754 debug2("index: 0x%lx for frame %li", (unsigned long)gopos, (long) *get_frame);
755 return gopos;
756 }
757
frame_ins2outs(mpg123_handle * fr,off_t ins)758 off_t frame_ins2outs(mpg123_handle *fr, off_t ins)
759 {
760 off_t outs = 0;
761 switch(fr->down_sample)
762 {
763 case 0:
764 # ifndef NO_DOWNSAMPLE
765 case 1:
766 case 2:
767 # endif
768 outs = ins>>fr->down_sample;
769 break;
770 # ifndef NO_NTOM
771 case 3: outs = ntom_ins2outs(fr, ins); break;
772 # endif
773 default: if(NOQUIET)
774 merror( "Bad down_sample (%i) ... should not be possible!!"
775 , fr->down_sample );
776 }
777 return outs;
778 }
779
frame_outs(mpg123_handle * fr,off_t num)780 off_t frame_outs(mpg123_handle *fr, off_t num)
781 {
782 off_t outs = 0;
783 switch(fr->down_sample)
784 {
785 case 0:
786 # ifndef NO_DOWNSAMPLE
787 case 1:
788 case 2:
789 # endif
790 outs = (fr->spf>>fr->down_sample)*num;
791 break;
792 #ifndef NO_NTOM
793 case 3: outs = ntom_frmouts(fr, num); break;
794 #endif
795 default: if(NOQUIET)
796 merror( "Bad down_sample (%i) ... should not be possible!!"
797 , fr->down_sample );
798 }
799 return outs;
800 }
801
802 /* Compute the number of output samples we expect from this frame.
803 This is either simple spf() or a tad more elaborate for ntom. */
frame_expect_outsamples(mpg123_handle * fr)804 off_t frame_expect_outsamples(mpg123_handle *fr)
805 {
806 off_t outs = 0;
807 switch(fr->down_sample)
808 {
809 case 0:
810 # ifndef NO_DOWNSAMPLE
811 case 1:
812 case 2:
813 # endif
814 outs = fr->spf>>fr->down_sample;
815 break;
816 #ifndef NO_NTOM
817 case 3: outs = ntom_frame_outsamples(fr); break;
818 #endif
819 default: if(NOQUIET)
820 merror( "Bad down_sample (%i) ... should not be possible!!"
821 , fr->down_sample );
822 }
823 return outs;
824 }
825
frame_offset(mpg123_handle * fr,off_t outs)826 off_t frame_offset(mpg123_handle *fr, off_t outs)
827 {
828 off_t num = 0;
829 switch(fr->down_sample)
830 {
831 case 0:
832 # ifndef NO_DOWNSAMPLE
833 case 1:
834 case 2:
835 # endif
836 num = outs/(fr->spf>>fr->down_sample);
837 break;
838 #ifndef NO_NTOM
839 case 3: num = ntom_frameoff(fr, outs); break;
840 #endif
841 default: if(NOQUIET)
842 error("Bad down_sample ... should not be possible!!");
843 }
844 return num;
845 }
846
847 #ifdef GAPLESS
848 /* input in _input_ samples */
frame_gapless_init(mpg123_handle * fr,off_t framecount,off_t bskip,off_t eskip)849 void frame_gapless_init(mpg123_handle *fr, off_t framecount, off_t bskip, off_t eskip)
850 {
851 debug3("frame_gapless_init: given %"OFF_P" frames, skip %"OFF_P" and %"OFF_P, (off_p)framecount, (off_p)bskip, (off_p)eskip);
852 fr->gapless_frames = framecount;
853 if(fr->gapless_frames > 0 && bskip >=0 && eskip >= 0)
854 {
855 fr->begin_s = bskip+GAPLESS_DELAY;
856 fr->end_s = framecount*fr->spf-eskip+GAPLESS_DELAY;
857 }
858 else fr->begin_s = fr->end_s = 0;
859 /* These will get proper values later, from above plus resampling info. */
860 fr->begin_os = 0;
861 fr->end_os = 0;
862 fr->fullend_os = 0;
863 debug2("frame_gapless_init: from %"OFF_P" to %"OFF_P" samples", (off_p)fr->begin_s, (off_p)fr->end_s);
864 }
865
frame_gapless_realinit(mpg123_handle * fr)866 void frame_gapless_realinit(mpg123_handle *fr)
867 {
868 fr->begin_os = frame_ins2outs(fr, fr->begin_s);
869 fr->end_os = frame_ins2outs(fr, fr->end_s);
870 if(fr->gapless_frames > 0)
871 fr->fullend_os = frame_ins2outs(fr, fr->gapless_frames*fr->spf);
872 else fr->fullend_os = 0;
873
874 debug4("frame_gapless_realinit: from %"OFF_P" to %"OFF_P" samples (%"OFF_P", %"OFF_P")", (off_p)fr->begin_os, (off_p)fr->end_os, (off_p)fr->fullend_os, (off_p)fr->gapless_frames);
875 }
876
877 /* At least note when there is trouble... */
frame_gapless_update(mpg123_handle * fr,off_t total_samples)878 void frame_gapless_update(mpg123_handle *fr, off_t total_samples)
879 {
880 off_t gapless_samples = fr->gapless_frames*fr->spf;
881 if(fr->gapless_frames < 1) return;
882
883 debug2("gapless update with new sample count %"OFF_P" as opposed to known %"OFF_P, (off_p)total_samples, (off_p)gapless_samples);
884 if(NOQUIET && total_samples != gapless_samples)
885 fprintf(stderr, "\nWarning: Real sample count %"OFF_P" differs from given gapless sample count %"OFF_P". Frankenstein stream?\n"
886 , (off_p)total_samples, (off_p)gapless_samples);
887
888 if(gapless_samples > total_samples)
889 {
890 if(NOQUIET)
891 merror( "End sample count smaller than gapless end! (%"OFF_P
892 " < %"OFF_P"). Disabling gapless mode from now on."
893 , (off_p)total_samples, (off_p)fr->end_s );
894 /* This invalidates the current position... but what should I do? */
895 frame_gapless_init(fr, -1, 0, 0);
896 frame_gapless_realinit(fr);
897 fr->lastframe = -1;
898 fr->lastoff = 0;
899 }
900 }
901
902 #endif
903
904 /* Compute the needed frame to ignore from, for getting accurate/consistent output for intended firstframe. */
ignoreframe(mpg123_handle * fr)905 static off_t ignoreframe(mpg123_handle *fr)
906 {
907 off_t preshift = fr->p.preframes;
908 /* Layer 3 _really_ needs at least one frame before. */
909 if(fr->lay==3 && preshift < 1) preshift = 1;
910 /* Layer 1 & 2 reall do not need more than 2. */
911 if(fr->lay!=3 && preshift > 2) preshift = 2;
912
913 return fr->firstframe - preshift;
914 }
915
916 /* The frame seek... This is not simply the seek to fe*fr->spf samples in output because we think of _input_ frames here.
917 Seek to frame offset 1 may be just seek to 200 samples offset in output since the beginning of first frame is delay/padding.
918 Hm, is that right? OK for the padding stuff, but actually, should the decoder delay be better totally hidden or not?
919 With gapless, even the whole frame position could be advanced further than requested (since Homey don't play dat). */
frame_set_frameseek(mpg123_handle * fr,off_t fe)920 void frame_set_frameseek(mpg123_handle *fr, off_t fe)
921 {
922 fr->firstframe = fe;
923 #ifdef GAPLESS
924 if(fr->p.flags & MPG123_GAPLESS && fr->gapless_frames > 0)
925 {
926 /* Take care of the beginning... */
927 off_t beg_f = frame_offset(fr, fr->begin_os);
928 if(fe <= beg_f)
929 {
930 fr->firstframe = beg_f;
931 fr->firstoff = fr->begin_os - frame_outs(fr, beg_f);
932 }
933 else fr->firstoff = 0;
934 /* The end is set once for a track at least, on the frame_set_frameseek called in get_next_frame() */
935 if(fr->end_os > 0)
936 {
937 fr->lastframe = frame_offset(fr,fr->end_os);
938 fr->lastoff = fr->end_os - frame_outs(fr, fr->lastframe);
939 } else {fr->lastframe = -1; fr->lastoff = 0; }
940 } else { fr->firstoff = fr->lastoff = 0; fr->lastframe = -1; }
941 #endif
942 fr->ignoreframe = ignoreframe(fr);
943 #ifdef GAPLESS
944 debug5("frame_set_frameseek: begin at %li frames and %li samples, end at %li and %li; ignore from %li",
945 (long) fr->firstframe, (long) fr->firstoff,
946 (long) fr->lastframe, (long) fr->lastoff, (long) fr->ignoreframe);
947 #else
948 debug3("frame_set_frameseek: begin at %li frames, end at %li; ignore from %li",
949 (long) fr->firstframe, (long) fr->lastframe, (long) fr->ignoreframe);
950 #endif
951 }
952
frame_skip(mpg123_handle * fr)953 void frame_skip(mpg123_handle *fr)
954 {
955 #ifndef NO_LAYER3
956 if(fr->lay == 3) set_pointer(fr, 1, 512);
957 #endif
958 }
959
960 /* Sample accurate seek prepare for decoder. */
961 /* This gets unadjusted output samples and takes resampling into account */
frame_set_seek(mpg123_handle * fr,off_t sp)962 void frame_set_seek(mpg123_handle *fr, off_t sp)
963 {
964 fr->firstframe = frame_offset(fr, sp);
965 debug1("frame_set_seek: from %"OFF_P, fr->num);
966 #ifndef NO_NTOM
967 if(fr->down_sample == 3) ntom_set_ntom(fr, fr->firstframe);
968 #endif
969 fr->ignoreframe = ignoreframe(fr);
970 #ifdef GAPLESS /* The sample offset is used for non-gapless mode, too! */
971 fr->firstoff = sp - frame_outs(fr, fr->firstframe);
972 debug5("frame_set_seek: begin at %li frames and %li samples, end at %li and %li; ignore from %li",
973 (long) fr->firstframe, (long) fr->firstoff,
974 (long) fr->lastframe, (long) fr->lastoff, (long) fr->ignoreframe);
975 #else
976 debug3("frame_set_seek: begin at %li frames, end at %li; ignore from %li",
977 (long) fr->firstframe, (long) fr->lastframe, (long) fr->ignoreframe);
978 #endif
979 }
980
mpg123_volume_change(mpg123_handle * mh,double change)981 int attribute_align_arg mpg123_volume_change(mpg123_handle *mh, double change)
982 {
983 if(mh == NULL) return MPG123_ERR;
984 return mpg123_volume(mh, change + (double) mh->p.outscale);
985 }
986
mpg123_volume(mpg123_handle * mh,double vol)987 int attribute_align_arg mpg123_volume(mpg123_handle *mh, double vol)
988 {
989 if(mh == NULL) return MPG123_ERR;
990
991 if(vol >= 0) mh->p.outscale = vol;
992 else mh->p.outscale = 0.;
993
994 do_rva(mh);
995 return MPG123_OK;
996 }
997
get_rva(mpg123_handle * fr,double * peak,double * gain)998 static int get_rva(mpg123_handle *fr, double *peak, double *gain)
999 {
1000 double p = -1;
1001 double g = 0;
1002 int ret = 0;
1003 if(fr->p.rva)
1004 {
1005 int rt = 0;
1006 /* Should one assume a zero RVA as no RVA? */
1007 if(fr->p.rva == 2 && fr->rva.level[1] != -1) rt = 1;
1008 if(fr->rva.level[rt] != -1)
1009 {
1010 p = fr->rva.peak[rt];
1011 g = fr->rva.gain[rt];
1012 ret = 1; /* Success. */
1013 }
1014 }
1015 if(peak != NULL) *peak = p;
1016 if(gain != NULL) *gain = g;
1017 return ret;
1018 }
1019
1020 /* adjust the volume, taking both fr->outscale and rva values into account */
do_rva(mpg123_handle * fr)1021 void do_rva(mpg123_handle *fr)
1022 {
1023 double peak = 0;
1024 double gain = 0;
1025 double newscale;
1026 double rvafact = 1;
1027 if(get_rva(fr, &peak, &gain))
1028 {
1029 if(NOQUIET && fr->p.verbose > 1) fprintf(stderr, "Note: doing RVA with gain %f\n", gain);
1030 rvafact = pow(10,gain/20);
1031 }
1032
1033 newscale = fr->p.outscale*rvafact;
1034
1035 /* if peak is unknown (== 0) this check won't hurt */
1036 if((peak*newscale) > 1.0)
1037 {
1038 newscale = 1.0/peak;
1039 warning2("limiting scale value to %f to prevent clipping with indicated peak factor of %f", newscale, peak);
1040 }
1041 /* first rva setting is forced with fr->lastscale < 0 */
1042 if(newscale != fr->lastscale || fr->decoder_change)
1043 {
1044 debug3("changing scale value from %f to %f (peak estimated to %f)", fr->lastscale != -1 ? fr->lastscale : fr->p.outscale, newscale, (double) (newscale*peak));
1045 fr->lastscale = newscale;
1046 /* It may be too early, actually. */
1047 if(fr->make_decode_tables != NULL) fr->make_decode_tables(fr); /* the actual work */
1048 }
1049 }
1050
1051
mpg123_getvolume(mpg123_handle * mh,double * base,double * really,double * rva_db)1052 int attribute_align_arg mpg123_getvolume(mpg123_handle *mh, double *base, double *really, double *rva_db)
1053 {
1054 if(mh == NULL) return MPG123_ERR;
1055 if(base) *base = mh->p.outscale;
1056 if(really) *really = mh->lastscale;
1057 get_rva(mh, NULL, rva_db);
1058 return MPG123_OK;
1059 }
1060
mpg123_framepos(mpg123_handle * mh)1061 off_t attribute_align_arg mpg123_framepos(mpg123_handle *mh)
1062 {
1063 if(mh == NULL) return MPG123_ERR;
1064
1065 return mh->input_offset;
1066 }
1067