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