-
Notifications
You must be signed in to change notification settings - Fork 0
/
player-mp3.c
1975 lines (1818 loc) · 52 KB
/
player-mp3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MP3/MPlayer plugin to VDR (C++)
*
* (C) 2001-2009 Stefan Huelswitt <[email protected]>
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <math.h>
#ifdef WITH_OSS
#include <sys/soundcard.h>
#endif
#include <mad.h>
#include <id3tag.h>
#include <vdr/player.h>
#include <vdr/ringbuffer.h>
#include <vdr/thread.h>
#include <vdr/tools.h>
#include "common.h"
#include "setup-mp3.h"
#include "player-mp3.h"
#include "data-mp3.h"
#include "decoder.h"
#include "decoder-core.h"
#ifndef NO_DEBUG
//#define DEBUG_MODE // debug playmode changes
#define DEBUG_BGR // debug backround scan thread
#define DEBUG_DELAY 300 // debug write/decode delays
//#define ACC_DUMP // dump limiter lookup table to /tmp/limiter
#endif
#if !defined(NO_DEBUG) && defined(DEBUG_MODE)
#define dm(x) { (x); }
#else
#define dm(x) ;
#endif
#if !defined(NO_DEBUG) && defined(DEBUG_BGR)
#define db(x) { (x); }
#else
#define db(x) ;
#endif
// ----------------------------------------------------------------
#define MP3BUFSIZE (1024*1024) // output ringbuffer size
#define OUT_BITS 16 // output 16 bit samples to DVB driver
#define OUT_FACT (OUT_BITS/8*2) // output factor is 16 bit & 2 channels -> 4 bytes
// cResample
#define MAX_NSAMPLES (1152*7) // max. buffer for resampled frame
// cNormalize
#define MIN_GAIN 0.03 // min. gain required to launch the normalizer
#define MAX_GAIN 3.0 // max. allowed gain
#define USE_FAST_LIMITER
#define LIM_ACC 12 // bit, accuracy for lookup table
#define F_LIM_MAX (mad_fixed_t)((1<<(MAD_F_FRACBITS+2))-1) // max. value covered by lookup table
#define LIM_SHIFT (MAD_F_FRACBITS-LIM_ACC) // shift value for table lookup
#define F_LIM_JMP (mad_fixed_t)(1<<LIM_SHIFT) // lookup table jump between values
// cLevel
#define POW_WIN 100 // window width for smoothing power values
#define EPSILON 0.00000000001 // anything less than EPSILON is considered zero
// --- cResample ------------------------------------------------------------
// The resample code has been adapted from the madplay project
// (resample.c) found in the libmad distribution
class cResample {
private:
mad_fixed_t ratio;
mad_fixed_t step;
mad_fixed_t last;
mad_fixed_t resampled[MAX_NSAMPLES];
public:
bool SetInputRate(unsigned int oldrate, unsigned int newrate);
unsigned int ResampleBlock(unsigned int nsamples, const mad_fixed_t *old);
const mad_fixed_t *Resampled(void) { return resampled; }
};
bool cResample::SetInputRate(unsigned int oldrate, unsigned int newrate)
{
if(oldrate<8000 || oldrate>newrate*6) { // out of range
esyslog("WARNING: samplerate %d out of range 8000-%d\n",oldrate,newrate*6);
return 0;
}
ratio=mad_f_tofixed((double)oldrate/(double)newrate);
step=0; last=0;
#ifdef DEBUG
static mad_fixed_t oldratio=0;
if(oldratio!=ratio) {
printf("mad: new resample ratio %f (from %d kHz to %d kHz)\n",mad_f_todouble(ratio),oldrate,newrate);
oldratio=ratio;
}
#endif
return ratio!=MAD_F_ONE;
}
unsigned int cResample::ResampleBlock(unsigned int nsamples, const mad_fixed_t *old)
{
// This resampling algorithm is based on a linear interpolation, which is
// not at all the best sounding but is relatively fast and efficient.
//
// A better algorithm would be one that implements a bandlimited
// interpolation.
mad_fixed_t *nsam=resampled;
const mad_fixed_t *end=old+nsamples;
const mad_fixed_t *begin=nsam;
if(step < 0) {
step = mad_f_fracpart(-step);
while (step < MAD_F_ONE) {
*nsam++ = step ? last+mad_f_mul(*old-last,step) : last;
step += ratio;
if(((step + 0x00000080L) & 0x0fffff00L) == 0)
step = (step + 0x00000080L) & ~0x0fffffffL;
}
step -= MAD_F_ONE;
}
while (end - old > 1 + mad_f_intpart(step)) {
old += mad_f_intpart(step);
step = mad_f_fracpart(step);
*nsam++ = step ? *old + mad_f_mul(old[1] - old[0], step) : *old;
step += ratio;
if (((step + 0x00000080L) & 0x0fffff00L) == 0)
step = (step + 0x00000080L) & ~0x0fffffffL;
}
if (end - old == 1 + mad_f_intpart(step)) {
last = end[-1];
step = -step;
}
else step -= mad_f_fromint(end - old);
return nsam-begin;
}
// --- cLevel ----------------------------------------------------------------
// The normalize algorithm and parts of the code has been adapted from the
// Normalize 0.7 project. (C) 1999-2002, Chris Vaill <[email protected]>
// A little background on how normalize computes the volume
// of a wav file, in case you want to know just how your
// files are being munged:
//
// The volumes calculated are RMS amplitudes, which corre
// spond (roughly) to perceived volume. Taking the RMS ampli
// tude of an entire file would not give us quite the measure
// we want, though, because a quiet song punctuated by short
// loud parts would average out to a quiet song, and the
// adjustment we would compute would make the loud parts
// excessively loud.
//
// What we want is to consider the maximum volume of the
// file, and normalize according to that. We break up the
// signal into 100 chunks per second, and get the signal
// power of each chunk, in order to get an estimation of
// "instantaneous power" over time. This "instantaneous
// power" signal varies too much to get a good measure of the
// original signal's maximum sustained power, so we run a
// smoothing algorithm over the power signal (specifically, a
// mean filter with a window width of 100 elements). The max
// imum point of the smoothed power signal turns out to be a
// good measure of the maximum sustained power of the file.
// We can then take the square root of the power to get maxi
// mum sustained RMS amplitude.
class cLevel {
private:
double maxpow;
mad_fixed_t peak;
struct Power {
// smooth
int npow, wpow;
double powsum, pows[POW_WIN];
// sum
unsigned int nsum;
double sum;
} power[2];
//
inline void AddPower(struct Power *p, double pow);
public:
void Init(void);
void GetPower(struct mad_pcm *pcm);
double GetLevel(void);
double GetPeak(void);
};
void cLevel::Init(void)
{
for(int l=0 ; l<2 ; l++) {
struct Power *p=&power[l];
p->sum=p->powsum=0.0; p->wpow=p->npow=p->nsum=0;
for(int i=POW_WIN-1 ; i>=0 ; i--) p->pows[i]=0.0;
}
maxpow=0.0; peak=0;
}
void cLevel::GetPower(struct mad_pcm *pcm)
{
for(int i=0 ; i<pcm->channels ; i++) {
struct Power *p=&power[i];
mad_fixed_t *data=pcm->samples[i];
for(int n=pcm->length ; n>0 ; n--) {
if(*data < -peak) peak = -*data;
if(*data > peak) peak = *data;
double s=mad_f_todouble(*data++);
p->sum+=(s*s);
if(++(p->nsum)>=pcm->samplerate/100) {
AddPower(p,p->sum/(double)p->nsum);
p->sum=0.0; p->nsum=0;
}
}
}
}
void cLevel::AddPower(struct Power *p, double pow)
{
p->powsum+=pow;
if(p->npow>=POW_WIN) {
if(p->powsum>maxpow) maxpow=p->powsum;
p->powsum-=p->pows[p->wpow];
}
else p->npow++;
p->pows[p->wpow]=pow;
p->wpow=(p->wpow+1) % POW_WIN;
}
double cLevel::GetLevel(void)
{
if(maxpow<EPSILON) {
// Either this whole file has zero power, or was too short to ever
// fill the smoothing buffer. In the latter case, we need to just
// get maxpow from whatever data we did collect.
if(power[0].powsum>maxpow) maxpow=power[0].powsum;
if(power[1].powsum>maxpow) maxpow=power[1].powsum;
}
double level=sqrt(maxpow/(double)POW_WIN); // adjust for the smoothing window size and root
d(printf("norm: new volumen level=%f peak=%f\n",level,mad_f_todouble(peak)))
return level;
}
double cLevel::GetPeak(void)
{
return mad_f_todouble(peak);
}
// --- cNormalize ------------------------------------------------------------
class cNormalize {
private:
mad_fixed_t gain;
double d_limlvl, one_limlvl;
mad_fixed_t limlvl;
bool dogain, dolimit;
#ifdef DEBUG
// stats
unsigned long limited, clipped, total;
mad_fixed_t peak;
#endif
// limiter
#ifdef USE_FAST_LIMITER
mad_fixed_t *table, tablestart;
int tablesize;
inline mad_fixed_t FastLimiter(mad_fixed_t x);
#endif
inline mad_fixed_t Limiter(mad_fixed_t x);
public:
cNormalize(void);
~cNormalize();
void Init(double Level, double Peak);
void Stats(void);
void AddGain(struct mad_pcm *pcm);
};
cNormalize::cNormalize(void)
{
d_limlvl=(double)MP3Setup.LimiterLevel/100.0;
one_limlvl=1-d_limlvl;
limlvl=mad_f_tofixed(d_limlvl);
d(printf("norm: lim_lev=%f lim_acc=%d\n",d_limlvl,LIM_ACC))
#ifdef USE_FAST_LIMITER
mad_fixed_t start=limlvl & ~(F_LIM_JMP-1);
tablestart=start;
tablesize=(unsigned int)(F_LIM_MAX-start)/F_LIM_JMP + 2;
table=new mad_fixed_t[tablesize];
if(table) {
d(printf("norm: table size=%d start=%08x jump=%08x\n",tablesize,start,F_LIM_JMP))
for(int i=0 ; i<tablesize ; i++) {
table[i]=Limiter(start);
start+=F_LIM_JMP;
}
tablesize--; // avoid a -1 in FastLimiter()
// do a quick accuracy check, just to be sure that FastLimiter() is working
// as expected :-)
#ifdef ACC_DUMP
FILE *out=fopen("/tmp/limiter","w");
#endif
mad_fixed_t maxdiff=0;
for(mad_fixed_t x=F_LIM_MAX ; x>=limlvl ; x-=mad_f_tofixed(1e-4)) {
mad_fixed_t diff=mad_f_abs(Limiter(x)-FastLimiter(x));
if(diff>maxdiff) maxdiff=diff;
#ifdef ACC_DUMP
fprintf(out,"%0.10f\t%0.10f\t%0.10f\t%0.10f\t%0.10f\n",
mad_f_todouble(x),mad_f_todouble(Limiter(x)),mad_f_todouble(FastLimiter(x)),mad_f_todouble(diff),mad_f_todouble(maxdiff));
if(ferror(out)) break;
#endif
}
#ifdef ACC_DUMP
fclose(out);
#endif
d(printf("norm: accuracy %.12f\n",mad_f_todouble(maxdiff)))
if(mad_f_todouble(maxdiff)>1e-6) {
esyslog("ERROR: accuracy check failed, normalizer disabled");
delete table; table=0;
}
}
else esyslog("ERROR: no memory for lookup table, normalizer disabled");
#endif // USE_FAST_LIMITER
}
cNormalize::~cNormalize()
{
#ifdef USE_FAST_LIMITER
delete[] table;
#endif
}
void cNormalize::Init(double Level, double Peak)
{
double Target=(double)MP3Setup.TargetLevel/100.0;
double dgain=Target/Level;
if(dgain>MAX_GAIN) dgain=MAX_GAIN;
gain=mad_f_tofixed(dgain);
// Check if we actually need to apply a gain
dogain=(Target>0.0 && fabs(1-dgain)>MIN_GAIN);
#ifdef USE_FAST_LIMITER
if(!table) dogain=false;
#endif
// Check if we actually need to do limiting:
// we have to if limiter is enabled, if gain>1 and if the peaks will clip.
dolimit=(d_limlvl<1.0 && dgain>1.0 && Peak*dgain>1.0);
#ifdef DEBUG
printf("norm: gain=%f dogain=%d dolimit=%d (target=%f level=%f peak=%f)\n",dgain,dogain,dolimit,Target,Level,Peak);
limited=clipped=total=0; peak=0;
#endif
}
void cNormalize::Stats(void)
{
#ifdef DEBUG
if(total)
printf("norm: stats tot=%ld lim=%ld/%.3f%% clip=%ld/%.3f%% peak=%.3f\n",
total,limited,(double)limited/total*100.0,clipped,(double)clipped/total*100.0,mad_f_todouble(peak));
#endif
}
mad_fixed_t cNormalize::Limiter(mad_fixed_t x)
{
// Limiter function:
//
// / x (for x <= lev)
// x' = |
// \ tanh((x - lev) / (1-lev)) * (1-lev) + lev (for x > lev)
//
// call only with x>=0. For negative samples, preserve sign outside this function
//
// With limiter level = 0, this is equivalent to a tanh() function;
// with limiter level = 1, this is equivalent to clipping.
if(x>limlvl) {
#ifdef DEBUG
if(x>MAD_F_ONE) clipped++;
limited++;
#endif
x=mad_f_tofixed(tanh((mad_f_todouble(x)-d_limlvl) / one_limlvl) * one_limlvl + d_limlvl);
}
return x;
}
#ifdef USE_FAST_LIMITER
mad_fixed_t cNormalize::FastLimiter(mad_fixed_t x)
{
// The fast algorithm is based on a linear interpolation between the
// the values in the lookup table. Relays heavly on libmads fixed point format.
if(x>limlvl) {
int i=(unsigned int)(x-tablestart)/F_LIM_JMP;
#ifdef DEBUG
if(x>MAD_F_ONE) clipped++;
limited++;
if(i>=tablesize) printf("norm: overflow x=%f x-ts=%f i=%d tsize=%d\n",
mad_f_todouble(x),mad_f_todouble(x-tablestart),i,tablesize);
#endif
mad_fixed_t r=x & (F_LIM_JMP-1);
x=MAD_F_ONE;
if(i<tablesize) {
mad_fixed_t *ptr=&table[i];
x=*ptr;
mad_fixed_t d=*(ptr+1)-x;
//x+=mad_f_mul(d,r)<<LIM_ACC; // this is not accurate as mad_f_mul() does >>MAD_F_FRACBITS
// which is senseless in the case of following <<LIM_ACC.
x+=((long long)d*(long long)r)>>LIM_SHIFT; // better, don't know if works on all machines
}
}
return x;
}
#endif
#ifdef USE_FAST_LIMITER
#define LIMITER_FUNC FastLimiter
#else
#define LIMITER_FUNC Limiter
#endif
void cNormalize::AddGain(struct mad_pcm *pcm)
{
if(dogain) {
for(int i=0 ; i<pcm->channels ; i++) {
mad_fixed_t *data=pcm->samples[i];
#ifdef DEBUG
total+=pcm->length;
#endif
if(dolimit) {
for(int n=pcm->length ; n>0 ; n--) {
mad_fixed_t s=mad_f_mul(*data,gain);
if(s<0) {
s=-s;
#ifdef DEBUG
if(s>peak) peak=s;
#endif
s=LIMITER_FUNC(s);
s=-s;
}
else {
#ifdef DEBUG
if(s>peak) peak=s;
#endif
s=LIMITER_FUNC(s);
}
*data++=s;
}
}
else {
for(int n=pcm->length ; n>0 ; n--) {
mad_fixed_t s=mad_f_mul(*data,gain);
#ifdef DEBUG
if(s>peak) peak=s;
else if(-s>peak) peak=-s;
#endif
if(s>MAD_F_ONE) s=MAD_F_ONE; // do clipping
if(s<-MAD_F_ONE) s=-MAD_F_ONE;
*data++=s;
}
}
}
}
}
// --- cScale ----------------------------------------------------------------
// The dither code has been adapted from the madplay project
// (audio.c) found in the libmad distribution
enum eAudioMode { amRoundBE, amDitherBE, amRoundLE, amDitherLE };
class cScale {
private:
enum { MIN=-MAD_F_ONE, MAX=MAD_F_ONE - 1 };
#ifdef DEBUG
// audio stats
unsigned long clipped_samples;
mad_fixed_t peak_clipping;
mad_fixed_t peak_sample;
#endif
// dither
struct dither {
mad_fixed_t error[3];
mad_fixed_t random;
} leftD, rightD;
//
inline mad_fixed_t Clip(mad_fixed_t sample, bool stats=true);
inline unsigned long Prng(unsigned long state);
signed long LinearRound(mad_fixed_t sample);
signed long LinearDither(mad_fixed_t sample, struct dither *dither);
public:
void Init(void);
void Stats(void);
unsigned int ScaleBlock(unsigned char *data, unsigned int size, unsigned int &nsamples, const mad_fixed_t * &left, const mad_fixed_t * &right, eAudioMode mode);
};
void cScale::Init(void)
{
#ifdef DEBUG
clipped_samples=0; peak_clipping=peak_sample=0;
#endif
memset(&leftD,0,sizeof(leftD));
memset(&rightD,0,sizeof(rightD));
}
void cScale::Stats(void)
{
#ifdef DEBUG
printf("mp3: scale stats clipped=%ld peak_clip=%f peak=%f\n",
clipped_samples,mad_f_todouble(peak_clipping),mad_f_todouble(peak_sample));
#endif
}
// gather signal statistics while clipping
mad_fixed_t cScale::Clip(mad_fixed_t sample, bool stats)
{
#ifndef DEBUG
if (sample > MAX) sample = MAX;
if (sample < MIN) sample = MIN;
#else
if(!stats) {
if (sample > MAX) sample = MAX;
if (sample < MIN) sample = MIN;
}
else {
if (sample >= peak_sample) {
if (sample > MAX) {
++clipped_samples;
if (sample - MAX > peak_clipping)
peak_clipping = sample - MAX;
sample = MAX;
}
peak_sample = sample;
}
else if (sample < -peak_sample) {
if (sample < MIN) {
++clipped_samples;
if (MIN - sample > peak_clipping)
peak_clipping = MIN - sample;
sample = MIN;
}
peak_sample = -sample;
}
}
#endif
return sample;
}
// generic linear sample quantize routine
signed long cScale::LinearRound(mad_fixed_t sample)
{
// round
sample += (1L << (MAD_F_FRACBITS - OUT_BITS));
// clip
sample=Clip(sample);
// quantize and scale
return sample >> (MAD_F_FRACBITS + 1 - OUT_BITS);
}
// 32-bit pseudo-random number generator
unsigned long cScale::Prng(unsigned long state)
{
return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
}
// generic linear sample quantize and dither routine
signed long cScale::LinearDither(mad_fixed_t sample, struct dither *dither)
{
// noise shape
sample += dither->error[0] - dither->error[1] + dither->error[2];
dither->error[2] = dither->error[1];
dither->error[1] = dither->error[0] / 2;
// bias
mad_fixed_t output = sample + (1L << (MAD_F_FRACBITS + 1 - OUT_BITS - 1));
const int scalebits = MAD_F_FRACBITS + 1 - OUT_BITS;
const mad_fixed_t mask = (1L << scalebits) - 1;
// dither
const mad_fixed_t random = Prng(dither->random);
output += (random & mask) - (dither->random & mask);
dither->random = random;
// clip
output=Clip(output);
sample=Clip(sample,false);
// quantize
output &= ~mask;
// error feedback
dither->error[0] = sample - output;
// scale
return output >> scalebits;
}
#define PUT_BE(data,sample) { *data++=(sample)>>8; *data++=(sample)>>0; }
#define PUT_LE(data,sample) { *data++=(sample)>>0; *data++=(sample)>>8; }
// write a block of signed 16-bit PCM samples
unsigned int cScale::ScaleBlock(unsigned char *data, unsigned int size, unsigned int &nsamples, const mad_fixed_t * &left, const mad_fixed_t * &right, eAudioMode mode)
{
unsigned int len=size/OUT_FACT;
if(len>nsamples) { len=nsamples; size=len*OUT_FACT; }
nsamples-=len;
switch(mode) {
case amRoundBE:
while(len--) {
signed int sample=LinearRound(*left++);
PUT_BE(data,sample);
if(right) sample=LinearRound(*right++);
PUT_BE(data,sample);
}
break;
case amDitherBE:
while(len--) {
signed int sample=LinearDither(*left++,&leftD);
PUT_BE(data,sample);
if(right) sample=LinearDither(*right++,&rightD);
PUT_BE(data,sample);
}
break;
case amRoundLE:
while(len--) {
signed int sample=LinearRound(*left++);
PUT_LE(data,sample);
if(right) sample=LinearRound(*right++);
PUT_LE(data,sample);
}
break;
case amDitherLE:
while(len--) {
signed int sample=LinearDither(*left++,&leftD);
PUT_LE(data,sample);
if(right) sample=LinearDither(*right++,&rightD);
PUT_LE(data,sample);
}
break;
}
return size;
}
// --- cShuffle ----------------------------------------------------------------
class cShuffle {
private:
int *shuffle, max;
unsigned int seed;
//
int Index(int pos);
public:
cShuffle(void);
~cShuffle();
void Shuffle(int num, int curr);
void Del(int pos);
void Flush(void);
int First(void);
int Next(int curr);
int Prev(int curr);
int Goto(int pos, int curr);
};
cShuffle::cShuffle(void)
{
shuffle=0; max=0;
seed=time(0);
}
cShuffle::~cShuffle(void)
{
Flush();
}
void cShuffle::Flush(void)
{
delete shuffle; shuffle=0;
max=0;
}
int cShuffle::Index(int pos)
{
if(pos>=0)
for(int i=0; i<max; i++) if(shuffle[i]==pos) return i;
return -1;
}
void cShuffle::Shuffle(int num, int curr)
{
int oldmax=0;
if(num!=max) {
int *ns=new int[num];
if(shuffle) {
if(num>max) {
memcpy(ns,shuffle,max*sizeof(int));
oldmax=max;
}
delete shuffle;
}
shuffle=ns; max=num;
}
if(!oldmax) curr=-1;
for(int i=oldmax ; i<max ; i++) shuffle[i]=i;
int in=Index(curr)+1; if(in<0) in=0;
if((max-in)>=2) {
for(int i=in ; i<max ; i++) {
int ran=(rand_r(&seed) % ((max-in)*4-4))/4; ran+=((ran+in) >= i);
int t=shuffle[i];
shuffle[i]=shuffle[ran+in];
shuffle[ran+in]=t;
}
}
#ifdef DEBUG
printf("shuffle: order (%d , %d -> %d) ",num,curr,in);
for(int i=0 ; i<max ; i++) printf("%d ",shuffle[i]);
printf("\n");
#endif
}
void cShuffle::Del(int pos)
{
int i=Index(pos);
if(i>=0) {
if(i+1<max) memmove(&shuffle[i],&shuffle[i+1],(max-i-1)*sizeof(int));
max--;
}
}
int cShuffle::First(void)
{
return shuffle[0];
}
int cShuffle::Next(int curr)
{
int i=Index(curr);
return (i>=0 && i+1<max) ? shuffle[i+1] : -1;
}
int cShuffle::Prev(int curr)
{
int i=Index(curr);
return (i>0) ? shuffle[i-1] : -1;
}
int cShuffle::Goto(int pos, int curr)
{
int i=Index(curr);
int g=Index(pos);
if(g>=0) {
if(g<i) {
for(int l=g; l<i; l++) shuffle[l]=shuffle[l+1];
shuffle[i]=pos;
}
else if(g>i) {
for(int l=g; l>i+1; l--) shuffle[l]=shuffle[l-1];
shuffle[i+1]=pos;
}
#ifdef DEBUG
printf("shuffle: goto order (%d -> %d , %d -> %d) ",pos,g,curr,i);
for(int i=0 ; i<max ; i++) printf("%d ",shuffle[i]);
printf("\n");
#endif
return pos;
}
return -1;
}
// --- cPlayManager ------------------------------------------------------------
#define SCANNED_ID3 1
#define SCANNED_LVL 2
cPlayManager *mgr=0;
cPlayManager::cPlayManager(void)
{
curr=0; currIndex=-1;
scan=0; stopscan=throttle=pass2=release=false;
play=0; playNew=eol=false;
shuffle=new cShuffle;
loopMode=(MP3Setup.InitLoopMode>0);
shuffleMode=(MP3Setup.InitShuffleMode>0);
}
cPlayManager::~cPlayManager()
{
Flush();
Release();
listMutex.Lock();
stopscan=true; bgCond.Broadcast();
listMutex.Unlock();
Cancel(2);
delete shuffle;
}
void cPlayManager::ThrottleWait(void)
{
while(!stopscan && !release && throttle) {
db(printf("mgr: background scan throttled\n"))
bgCond.Wait(listMutex);
db(printf("mgr: background scan throttle wakeup\n"))
}
}
void cPlayManager::Action(void)
{
db(printf("mgr: background scan thread started (pid=%d)\n", getpid()))
if(nice(5)<0);
listMutex.Lock();
while(!stopscan) {
for(scan=list.First(); !stopscan && !release && scan; scan=list.Next(scan)) {
ThrottleWait();
listMutex.Unlock();
if(!(scan->user & SCANNED_ID3)) {
db(printf("mgr: scanning (id3) %s\n",scan->Name()))
cSongInfo *si=scan->Info(true);
if(si && si->Level>0.0) scan->user|=SCANNED_LVL;
scan->user|=SCANNED_ID3;
}
listMutex.Lock();
}
if(MP3Setup.BgrScan>1) {
pass2=true;
for(scan=list.First(); !stopscan && !release && scan; scan=list.Next(scan)) {
if(scan==curr) continue;
ThrottleWait();
listMutex.Unlock();
if(!(scan->user & SCANNED_LVL)) {
cDecoder *dec=scan->Decoder();
if(dec) {
cSongInfo *si=scan->Info(false);
if(!dec->IsStream() && (!si || si->Level<=0.0) && dec->Start()) {
db(printf("mgr: scanning (lvl) %s\n",scan->Name()))
cLevel level;
level.Init();
bool go=true;
while(go && !release) {
if(throttle) {
listMutex.Lock(); ThrottleWait(); listMutex.Unlock();
continue;
}
struct Decode *ds=dec->Decode();
switch(ds->status) {
case dsPlay:
level.GetPower(ds->pcm);
break;
case dsSkip:
case dsSoftError:
break;
case dsEof:
{
double l=level.GetLevel();
if(l>0.0) {
cSongInfo *si=dec->SongInfo(false);
cFileInfo *fi=dec->FileInfo();
if(si && fi) {
si->Level=l;
si->Peak=level.GetPeak();
InfoCache.Cache(si,fi);
}
}
}
//fall through
case dsOK:
case dsError:
scan->user|=SCANNED_LVL;
go=false;
break;
}
}
}
else scan->user|=SCANNED_LVL;
dec->Stop();
}
}
listMutex.Lock();
}
pass2=false;
}
do {
scan=0; release=false; fgCond.Broadcast();
db(printf("mgr: background scan idle\n"))
bgCond.Wait(listMutex);
db(printf("mgr: background scan idle wakeup\n"))
} while(!stopscan && (release || throttle));
}
listMutex.Unlock();
db(printf("mgr: background scan thread ended (pid=%d)\n", getpid()))
}
void cPlayManager::Throttle(bool thr)
{
if(MP3Setup.BgrScan) {
if(!thr && throttle) {
db(printf("mgr: bgr-scan -> run (%llu)\n",cTimeMs::Now()))
listMutex.Lock();
throttle=false; bgCond.Broadcast();
listMutex.Unlock();
}
if(thr && !throttle) {
db(printf("mgr: bgr-scan -> throttle (%llu)\n",cTimeMs::Now()))
throttle=true;
}
}
}
void cPlayManager::ToggleShuffle(void)
{
shuffleMode=!shuffleMode;
d(printf("mgr: shuffle mode toggled : %d\n",shuffleMode))
if(shuffleMode && !eol) {
curr=0; currIndex=-1;
shuffle->Shuffle(maxIndex+1,-1);
Next();
}
}
void cPlayManager::ToggleLoop(void)
{
loopMode=!loopMode;
d(printf("mgr: loop mode toggled : %d\n",loopMode))
}
bool cPlayManager::Info(int num, cMP3PlayInfo *pi)
{
cSong *s;
int idx=num-1;
if(idx<0) { idx=currIndex; s=curr; }
else { s=list.Get(idx); }
memset(pi,0,sizeof(*pi));
pi->Num=idx+1;
pi->MaxNum=maxIndex+1;
pi->Loop=loopMode;
pi->Shuffle=shuffleMode;
bool res=false;
if(s) {
strn0cpy(pi->Title,s->Name(),sizeof(pi->Title));
strn0cpy(pi->Filename,s->FullPath(),sizeof(pi->Filename));
cSongInfo *si=s->Info(false);
if(si && si->HasInfo()) {
static const char *modestr[] = { "Mono","Dual","Joint-Stereo","Stereo" };
if(si->Title) strn0cpy(pi->Title,si->Title,sizeof(pi->Title));
if(si->Artist) strn0cpy(pi->Artist,si->Artist,sizeof(pi->Artist));
if(si->Album) strn0cpy(pi->Album,si->Album,sizeof(pi->Album));
strn0cpy(pi->SMode,modestr[si->ChMode],sizeof(pi->SMode));
pi->Year=si->Year;
pi->SampleFreq=si->SampleFreq;
pi->Bitrate=si->Bitrate;
pi->MaxBitrate=si->MaxBitrate;
res=true;
}
}
pi->Hash=MakeHashBuff((char *)pi,(char *)&pi->Loop-(char *)pi);
return res;
}
void cPlayManager::Add(cPlayList *pl)
{
cMutexLock lock(&listMutex);
bool real=false;
for(cSong *song=pl->First(); song; song=pl->cList<cSong>::Next(song)) {
cSong *ns=new cSong(song);
list.Add(ns);
real=true;
}
if(real) {
if(MP3Setup.BgrScan) { stopscan=false; if(!Active()) Start(); }
else stopscan=true;
bgCond.Broadcast();
maxIndex=list.Count()-1;
if(shuffleMode) shuffle->Shuffle(maxIndex+1,currIndex);
if(!curr) Next();
}
}
void cPlayManager::Flush(void)
{
cMutexLock lock(&listMutex);
Halt();
list.Clear();
shuffle->Flush();
}