-
Notifications
You must be signed in to change notification settings - Fork 11
/
audio.c
2230 lines (2006 loc) · 58.1 KB
/
audio.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
/// Copyright (C) 2009 - 2014 by Johns. All Rights Reserved.
/// Copyright (C) 2018 by pesintta, rofafor.
///
/// SPDX-License-Identifier: AGPL-3.0-only
///
/// This module contains all audio output functions.
///
/// ALSA PCM/Mixer api is supported.
/// @see http://www.alsa-project.org/alsa-doc/alsa-lib
///
/// @note alsa async playback is broken, don't use it!
///
///
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <math.h>
#include <sched.h>
#include <alsa/asoundlib.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <pthread.h>
#include "iatomic.h" // portable atomic_t
#include "ringbuffer.h"
#include "misc.h"
#include "audio.h"
//----------------------------------------------------------------------------
// Declarations
//----------------------------------------------------------------------------
/**
** Audio output module structure and typedef.
*/
typedef struct _audio_module_
{
const char *Name; ///< audio output module name
int (*const Thread) (void); ///< module thread handler
void (*const FlushBuffers) (void); ///< flush sample buffers
int64_t(*const GetDelay) (void); ///< get current audio delay
void (*const SetVolume) (int); ///< set output volume
int (*const Setup) (int *, int *, int); ///< setup channels, samplerate
void (*const Play) (void); ///< play audio
void (*const Pause) (void); ///< pause audio
void (*const Init) (void); ///< initialize audio output module
void (*const Exit) (void); ///< cleanup audio output module
} AudioModule;
static const AudioModule NoopModule; ///< forward definition of noop module
//----------------------------------------------------------------------------
// Variables
//----------------------------------------------------------------------------
char AudioAlsaDriverBroken; ///< disable broken driver message
char AudioAlsaNoCloseOpen; ///< disable alsa close/open fix
char AudioAlsaCloseOpenDelay; ///< enable alsa close/open delay fix
static const char *AudioModuleName; ///< which audio module to use
/// Selected audio module.
static const AudioModule *AudioUsedModule = &NoopModule;
static const char *AudioPCMDevice; ///< PCM device name
static const char *AudioPassthroughDevice; ///< Passthrough device name
static const char *AudioMixerDevice; ///< mixer device name
static const char *AudioMixerChannel; ///< mixer channel name
static char AudioDoingInit; ///> flag in init, reduce error
static volatile char AudioRunning; ///< thread running / stopped
static volatile char AudioPaused; ///< audio paused
static volatile char AudioVideoIsReady; ///< video ready start early
static int AudioSkip; ///< skip audio to sync to video
static const int AudioBytesProSample = 2; ///< number of bytes per sample
static int AudioBufferTime = 336; ///< audio buffer time in ms
static pthread_t AudioThread; ///< audio play thread
static pthread_mutex_t AudioMutex; ///< audio condition mutex
pthread_mutex_t PTS_mutex; ///< PTS mutex
pthread_mutex_t ReadAdvance_mutex; ///< PTS mutex
static pthread_cond_t AudioStartCond; ///< condition variable
static char AudioThreadStop; ///< stop audio thread
static char AudioSoftVolume; ///< flag use soft volume
static char AudioNormalize; ///< flag use volume normalize
static char AudioCompression; ///< flag use compress volume
static char AudioMute; ///< flag muted
static int AudioAmplifier; ///< software volume factor
static int AudioNormalizeFactor; ///< current normalize factor
static const int AudioMinNormalize = 100; ///< min. normalize factor
static int AudioMaxNormalize; ///< max. normalize factor
static int AudioCompressionFactor; ///< current compression factor
static int AudioMaxCompression; ///< max. compression factor
static int AudioStereoDescent; ///< volume descent for stereo
static int AudioVolume; ///< current volume (0 .. 1000)
extern int VideoAudioDelay; ///< import audio/video delay
extern volatile char SoftIsPlayingVideo; ///< stream contains video data
/// default ring buffer size ~2s 8ch 16bit (3 * 5 * 7 * 8)
static const unsigned AudioRingBufferSize = 3 * 5 * 7 * 8 * 2 * 1000;
#define AUDIO_MIN_BUFFER_FREE (3072 * 8 * 8)
static int AudioChannelsInHw[9]; ///< table which channels are supported
enum _audio_rates
{ ///< sample rates enumeration
// HW: 32000 44100 48000 88200 96000 176400 192000
//Audio32000, ///< 32.0Khz
Audio44100, ///< 44.1Khz
Audio48000, ///< 48.0Khz
//Audio88200, ///< 88.2Khz
//Audio96000, ///< 96.0Khz
//Audio176400, ///< 176.4Khz
Audio192000, ///< 192.0Khz
AudioRatesMax ///< max index
};
/// table which rates are supported
static int AudioRatesInHw[AudioRatesMax];
/// input to hardware channel matrix
static int AudioChannelMatrix[AudioRatesMax][9];
/// rates tables (must be sorted by frequency)
static const unsigned AudioRatesTable[AudioRatesMax] = {
44100, 48000, 192000
};
//----------------------------------------------------------------------------
// filter
//----------------------------------------------------------------------------
static const int AudioNormSamples = 4096; ///< number of samples
#define AudioNormMaxIndex 128 ///< number of average values
/// average of n last sample blocks
static uint32_t AudioNormAverage[AudioNormMaxIndex];
static int AudioNormIndex; ///< index into average table
static int AudioNormReady; ///< index counter
static int AudioNormCounter; ///< sample counter
/**
** Audio normalizer.
**
** @param samples sample buffer
** @param count number of bytes in sample buffer
*/
static void AudioNormalizer(int16_t * samples, int count)
{
int i;
int l;
int factor;
int16_t *data;
// average samples
l = count / AudioBytesProSample;
data = samples;
do {
uint32_t avg;
int n = l;
if (AudioNormCounter + n > AudioNormSamples) {
n = AudioNormSamples - AudioNormCounter;
}
avg = AudioNormAverage[AudioNormIndex];
for (i = 0; i < n; ++i) {
int t;
t = data[i];
avg += (t * t) / AudioNormSamples;
}
AudioNormAverage[AudioNormIndex] = avg;
AudioNormCounter += n;
if (AudioNormCounter >= AudioNormSamples) {
if (AudioNormReady < AudioNormMaxIndex) {
AudioNormReady++;
} else {
avg = 0;
for (i = 0; i < AudioNormMaxIndex; ++i) {
avg += AudioNormAverage[i] / AudioNormMaxIndex;
}
// calculate normalize factor
if (avg > 0) {
factor = ((INT16_MAX / 8) * 1000U) / (uint32_t) sqrt(avg);
// smooth normalize
AudioNormalizeFactor = (AudioNormalizeFactor * 500 + factor * 500) / 1000;
if (AudioNormalizeFactor < AudioMinNormalize) {
AudioNormalizeFactor = AudioMinNormalize;
}
if (AudioNormalizeFactor > AudioMaxNormalize) {
AudioNormalizeFactor = AudioMaxNormalize;
}
} else {
factor = 1000;
}
Debug6("audio/normalize: avg %8d, fac=%6.3f, norm=%6.3f", avg, factor / 1000.0,
AudioNormalizeFactor / 1000.0);
}
AudioNormIndex = (AudioNormIndex + 1) % AudioNormMaxIndex;
AudioNormCounter = 0;
AudioNormAverage[AudioNormIndex] = 0U;
}
data += n;
l -= n;
} while (l > 0);
// apply normalize factor
for (i = 0; i < count / AudioBytesProSample; ++i) {
int t;
t = (samples[i] * AudioNormalizeFactor) / 1000;
if (t < INT16_MIN) {
t = INT16_MIN;
} else if (t > INT16_MAX) {
t = INT16_MAX;
}
samples[i] = t;
}
}
/**
** Reset normalizer.
*/
static void AudioResetNormalizer(void)
{
int i;
AudioNormCounter = 0;
AudioNormReady = 0;
for (i = 0; i < AudioNormMaxIndex; ++i) {
AudioNormAverage[i] = 0U;
}
AudioNormalizeFactor = 1000;
}
/**
** Audio compression.
**
** @param samples sample buffer
** @param count number of bytes in sample buffer
*/
static void AudioCompressor(int16_t * samples, int count)
{
// find loudest sample
int max_sample = 0;
for (int i = 0; i < count / AudioBytesProSample; ++i) {
int t = abs(samples[i]);
if (t > max_sample) {
max_sample = t;
}
}
// calculate compression factor
if (max_sample > 0) {
int factor = (INT16_MAX * 1000) / max_sample;
// smooth compression (FIXME: make configurable?)
AudioCompressionFactor = (AudioCompressionFactor * 950 + factor * 50) / 1000;
if (AudioCompressionFactor > factor) {
AudioCompressionFactor = factor; // no clipping
}
if (AudioCompressionFactor > AudioMaxCompression) {
AudioCompressionFactor = AudioMaxCompression;
}
Debug6("audio/compress: max %5d, fac=%6.3f, com=%6.3f", max_sample, factor / 1000.0,
AudioCompressionFactor / 1000.0);
// apply compression factor
for (int i = 0; i < count / AudioBytesProSample; ++i) {
int t;
t = (samples[i] * AudioCompressionFactor) / 1000;
if (t < INT16_MIN) {
t = INT16_MIN;
} else if (t > INT16_MAX) {
t = INT16_MAX;
}
samples[i] = t;
}
}
}
/**
** Reset compressor.
*/
static void AudioResetCompressor(void)
{
AudioCompressionFactor = 2000;
if (AudioCompressionFactor > AudioMaxCompression) {
AudioCompressionFactor = AudioMaxCompression;
}
}
/**
** Audio software amplifier.
**
** @param samples sample buffer
** @param count number of bytes in sample buffer
**
** @todo FIXME: this does hard clipping
*/
static void AudioSoftAmplifier(int16_t * samples, int count)
{
int i;
// silence
if (AudioMute || !AudioAmplifier) {
memset(samples, 0, count);
return;
}
for (i = 0; i < count / AudioBytesProSample; ++i) {
int t;
t = (samples[i] * AudioAmplifier) / 1000;
if (t < INT16_MIN) {
t = INT16_MIN;
} else if (t > INT16_MAX) {
t = INT16_MAX;
}
samples[i] = t;
}
}
/**
** Upmix mono to stereo.
**
** @param in input sample buffer
** @param frames number of frames in sample buffer
** @param out output sample buffer
*/
static void AudioMono2Stereo(const int16_t * in, int frames, int16_t * out)
{
int i;
for (i = 0; i < frames; ++i) {
int t;
t = in[i];
out[i * 2 + 0] = t;
out[i * 2 + 1] = t;
}
}
/**
** Downmix stereo to mono.
**
** @param in input sample buffer
** @param frames number of frames in sample buffer
** @param out output sample buffer
*/
static void AudioStereo2Mono(const int16_t * in, int frames, int16_t * out)
{
int i;
for (i = 0; i < frames; i += 2) {
out[i / 2] = (in[i + 0] + in[i + 1]) / 2;
}
}
/**
** Downmix surround to stereo.
**
** ffmpeg L R C Ls Rs -> alsa L R Ls Rs C
** ffmpeg L R C LFE Ls Rs -> alsa L R Ls Rs C LFE
** ffmpeg L R C LFE Ls Rs Rl Rr -> alsa L R Ls Rs C LFE Rl Rr
**
** @param in input sample buffer
** @param in_chan nr. of input channels
** @param frames number of frames in sample buffer
** @param out output sample buffer
*/
static void AudioSurround2Stereo(const int16_t * in, int in_chan, int frames, int16_t * out)
{
while (frames--) {
int l;
int r;
switch (in_chan) {
case 3: // stereo or surround? =>stereo
l = in[0] * 600; // L
r = in[1] * 600; // R
l += in[2] * 400; // C
r += in[2] * 400;
break;
case 4: // quad or surround? =>quad
l = in[0] * 600; // L
r = in[1] * 600; // R
l += in[2] * 400; // Ls
r += in[3] * 400; // Rs
break;
case 5: // 5.0
l = in[0] * 500; // L
r = in[1] * 500; // R
l += in[2] * 200; // Ls
r += in[3] * 200; // Rs
l += in[4] * 300; // C
r += in[4] * 300;
break;
case 6: // 5.1
l = in[0] * 400; // L
r = in[1] * 400; // R
l += in[2] * 200; // Ls
r += in[3] * 200; // Rs
l += in[4] * 300; // C
r += in[4] * 300;
l += in[5] * 100; // LFE
r += in[5] * 100;
break;
case 7: // 7.0
l = in[0] * 400; // L
r = in[1] * 400; // R
l += in[2] * 200; // Ls
r += in[3] * 200; // Rs
l += in[4] * 300; // C
r += in[4] * 300;
l += in[5] * 100; // RL
r += in[6] * 100; // RR
break;
case 8: // 7.1
l = in[0] * 400; // L
r = in[1] * 400; // R
l += in[2] * 150; // Ls
r += in[3] * 150; // Rs
l += in[4] * 250; // C
r += in[4] * 250;
l += in[5] * 100; // LFE
r += in[5] * 100;
l += in[6] * 100; // RL
r += in[7] * 100; // RR
break;
default:
abort();
}
in += in_chan;
out[0] = l / 1000;
out[1] = r / 1000;
out += 2;
}
}
/**
** Upmix @a in_chan channels to @a out_chan.
**
** @param in input sample buffer
** @param in_chan nr. of input channels
** @param frames number of frames in sample buffer
** @param out output sample buffer
** @param out_chan nr. of output channels
*/
static void AudioUpmix(const int16_t * in, int in_chan, int frames, int16_t * out, int out_chan)
{
while (frames--) {
int i;
for (i = 0; i < in_chan; ++i) { // copy existing channels
*out++ = *in++;
}
for (; i < out_chan; ++i) { // silents missing channels
*out++ = 0;
}
}
}
/**
** Resample ffmpeg sample format to hardware format.
**
** FIXME: use libswresample for this and move it to codec.
** FIXME: ffmpeg to alsa conversion is already done in codec.c.
**
** ffmpeg L R C Ls Rs -> alsa L R Ls Rs C
** ffmpeg L R C LFE Ls Rs -> alsa L R Ls Rs C LFE
** ffmpeg L R C LFE Ls Rs Rl Rr -> alsa L R Ls Rs C LFE Rl Rr
**
** @param in input sample buffer
** @param in_chan nr. of input channels
** @param frames number of frames in sample buffer
** @param out output sample buffer
** @param out_chan nr. of output channels
*/
static void AudioResample(const int16_t * in, int in_chan, int frames, int16_t * out, int out_chan)
{
switch (in_chan * 8 + out_chan) {
case 1 * 8 + 1:
case 2 * 8 + 2:
case 3 * 8 + 3:
case 4 * 8 + 4:
case 5 * 8 + 5:
case 6 * 8 + 6:
case 7 * 8 + 7:
case 8 * 8 + 8: // input = output channels
memcpy(out, in, frames * in_chan * AudioBytesProSample);
break;
case 2 * 8 + 1:
AudioStereo2Mono(in, frames, out);
break;
case 1 * 8 + 2:
AudioMono2Stereo(in, frames, out);
break;
case 3 * 8 + 2:
case 4 * 8 + 2:
case 5 * 8 + 2:
case 6 * 8 + 2:
case 7 * 8 + 2:
case 8 * 8 + 2:
AudioSurround2Stereo(in, in_chan, frames, out);
break;
case 5 * 8 + 6:
case 3 * 8 + 8:
case 5 * 8 + 8:
case 6 * 8 + 8:
AudioUpmix(in, in_chan, frames, out, out_chan);
break;
default:
Error("audio: unsupported %d -> %d channels resample", in_chan, out_chan);
// play silence
memset(out, 0, frames * out_chan * AudioBytesProSample);
break;
}
}
//----------------------------------------------------------------------------
// ring buffer
//----------------------------------------------------------------------------
#define AUDIO_RING_MAX 8 ///< number of audio ring buffers
/**
** Audio ring buffer.
*/
typedef struct _audio_ring_ring_
{
char FlushBuffers; ///< flag: flush buffers
char Passthrough; ///< flag: use pass-through (AC-3, ...)
int16_t PacketSize; ///< packet size
unsigned HwSampleRate; ///< hardware sample rate in Hz
unsigned HwChannels; ///< hardware number of channels
unsigned InSampleRate; ///< input sample rate in Hz
unsigned InChannels; ///< input number of channels
int64_t PTS; ///< pts clock
RingBuffer *RingBuffer; ///< sample ring buffer
} AudioRingRing;
/// ring of audio ring buffers
static AudioRingRing AudioRing[AUDIO_RING_MAX];
static int AudioRingWrite; ///< audio ring write pointer
static int AudioRingRead; ///< audio ring read pointer
static atomic_t AudioRingFilled; ///< how many of the ring is used
static unsigned AudioStartThreshold; ///< start play, if filled
/**
** Add sample-rate, number of channels change to ring.
**
** @param sample_rate sample-rate frequency
** @param channels number of channels
** @param passthrough use /pass-through (AC-3, ...) device
**
** @retval -1 error
** @retval 0 okay
**
** @note this function shouldn't fail. Checks are done during AudoInit.
*/
static int AudioRingAdd(unsigned sample_rate, int channels, int passthrough)
{
unsigned u;
// search supported sample-rates
for (u = 0; u < AudioRatesMax; ++u) {
if (AudioRatesTable[u] == sample_rate) {
goto found;
}
if (AudioRatesTable[u] > sample_rate) {
break;
}
}
Error("audio: %dHz sample-rate unsupported", sample_rate);
return -1; // unsupported sample-rate
found:
if (!AudioChannelMatrix[u][channels]) {
Error("audio: %d channels unsupported", channels);
return -1; // unsupported nr. of channels
}
if (atomic_read(&AudioRingFilled) == AUDIO_RING_MAX) { // no free slot
// FIXME: can wait for ring buffer empty
Error("audio: out of ring buffers");
return -1;
}
AudioRingWrite = (AudioRingWrite + 1) % AUDIO_RING_MAX;
AudioRing[AudioRingWrite].FlushBuffers = 0;
AudioRing[AudioRingWrite].Passthrough = passthrough;
AudioRing[AudioRingWrite].PacketSize = 0;
AudioRing[AudioRingWrite].InSampleRate = sample_rate;
AudioRing[AudioRingWrite].InChannels = channels;
AudioRing[AudioRingWrite].HwSampleRate = sample_rate;
AudioRing[AudioRingWrite].HwChannels = AudioChannelMatrix[u][channels];
AudioRing[AudioRingWrite].PTS = INT64_C(0x8000000000000000);
RingBufferReset(AudioRing[AudioRingWrite].RingBuffer);
Debug5("audio: %d ring buffer prepared", atomic_read(&AudioRingFilled) + 1);
atomic_inc(&AudioRingFilled);
if (AudioThread) {
// tell thread, that there is something todo
AudioRunning = 1;
pthread_cond_signal(&AudioStartCond);
}
return 0;
}
/**
** Setup audio ring.
*/
static void AudioRingInit(void)
{
int i;
for (i = 0; i < AUDIO_RING_MAX; ++i) {
// ~2s 8ch 16bit
AudioRing[i].RingBuffer = RingBufferNew(AudioRingBufferSize);
}
atomic_set(&AudioRingFilled, 0);
}
/**
** Cleanup audio ring.
*/
static void AudioRingExit(void)
{
int i;
for (i = 0; i < AUDIO_RING_MAX; ++i) {
if (AudioRing[i].RingBuffer) {
RingBufferDel(AudioRing[i].RingBuffer);
AudioRing[i].RingBuffer = NULL;
}
AudioRing[i].HwSampleRate = 0; // checked for valid setup
AudioRing[i].InSampleRate = 0;
}
AudioRingRead = 0;
AudioRingWrite = 0;
}
//============================================================================
// A L S A
//============================================================================
//----------------------------------------------------------------------------
// Alsa variables
//----------------------------------------------------------------------------
static snd_pcm_t *AlsaPCMHandle; ///< alsa pcm handle
static char AlsaCanPause; ///< hw supports pause
static int AlsaUseMmap; ///< use mmap
static snd_mixer_t *AlsaMixer; ///< alsa mixer handle
static snd_mixer_elem_t *AlsaMixerElem; ///< alsa pcm mixer element
static int AlsaRatio; ///< internal -> mixer ratio * 1000
//----------------------------------------------------------------------------
// alsa pcm
//----------------------------------------------------------------------------
/**
** Play samples from ringbuffer.
**
** Fill the kernel buffer, as much as possible.
**
** @retval 0 ok
** @retval 1 ring buffer empty
** @retval -1 underrun error
*/
static int AlsaPlayRingbuffer(void)
{
int first;
first = 1;
for (;;) { // loop for ring buffer wrap
int avail;
int n;
int err;
int frames;
const void *p;
// how many bytes can be written?
n = snd_pcm_avail_update(AlsaPCMHandle);
if (n < 0) {
if (n == -EAGAIN) {
continue;
}
Error("audio/alsa: avail underrun error? '%s'", snd_strerror(n));
err = snd_pcm_recover(AlsaPCMHandle, n, 0);
if (err >= 0) {
continue;
}
Error("audio/alsa: snd_pcm_avail_update(): %s", snd_strerror(n));
return -1;
}
avail = snd_pcm_frames_to_bytes(AlsaPCMHandle, n);
if (avail < 256) { // too much overhead
if (first) {
// happens with broken alsa drivers
if (AudioThread) {
if (!AudioAlsaDriverBroken) {
Error("audio/alsa: broken driver %d state '%s'", avail,
snd_pcm_state_name(snd_pcm_state(AlsaPCMHandle)));
}
// try to recover
if (snd_pcm_state(AlsaPCMHandle)
== SND_PCM_STATE_PREPARED) {
if ((err = snd_pcm_start(AlsaPCMHandle)) < 0) {
Error("audio/alsa: snd_pcm_start(): %s", snd_strerror(err));
}
}
usleep(5 * 1000);
}
}
Debug6("audio/alsa: break state '%s'", snd_pcm_state_name(snd_pcm_state(AlsaPCMHandle)));
break;
}
n = RingBufferGetReadPointer(AudioRing[AudioRingRead].RingBuffer, &p);
if (!n) { // ring buffer empty
if (first) { // only error on first loop
Debug6("audio/alsa: empty buffers %d", avail);
// ring buffer empty
// AlsaLowWaterMark = 1;
return 1;
}
return 0;
}
if (n < avail) { // not enough bytes in ring buffer
avail = n;
}
if (!avail) { // full or buffer empty
break;
}
// muting pass-through AC-3, can produce disturbance
if (AudioMute || (AudioSoftVolume && !AudioRing[AudioRingRead].Passthrough)) {
// FIXME: quick&dirty cast
AudioSoftAmplifier((int16_t *) p, avail);
// FIXME: if not all are written, we double amplify them
}
frames = snd_pcm_bytes_to_frames(AlsaPCMHandle, avail);
#ifdef DEBUG
if (avail != snd_pcm_frames_to_bytes(AlsaPCMHandle, frames)) {
Error("audio/alsa: bytes lost -> out of sync");
}
#endif
for (;;) {
pthread_mutex_lock(&ReadAdvance_mutex);
if (AlsaUseMmap) {
err = snd_pcm_mmap_writei(AlsaPCMHandle, p, frames);
} else {
err = snd_pcm_writei(AlsaPCMHandle, p, frames);
}
if (err != frames) {
if (err < 0) {
pthread_mutex_unlock(&ReadAdvance_mutex);
if (err == -EAGAIN) {
continue;
}
Error("audio/alsa: writei underrun error? '%s'", snd_strerror(err));
err = snd_pcm_recover(AlsaPCMHandle, err, 0);
if (err >= 0) {
return 0;
}
Error("audio/alsa: snd_pcm_writei failed: %s", snd_strerror(err));
return -1;
}
// this could happen, if underrun happened
Error("audio/alsa: not all frames written");
avail = snd_pcm_frames_to_bytes(AlsaPCMHandle, err);
}
break;
}
RingBufferReadAdvance(AudioRing[AudioRingRead].RingBuffer, avail);
pthread_mutex_unlock(&ReadAdvance_mutex);
first = 0;
}
return 0;
}
/**
** Flush alsa buffers.
*/
static void AlsaFlushBuffers(void)
{
if (AlsaPCMHandle) {
snd_pcm_state_t state;
state = snd_pcm_state(AlsaPCMHandle);
Debug5("audio/alsa: flush state %s", snd_pcm_state_name(state));
if (state != SND_PCM_STATE_OPEN) {
int err;
if ((err = snd_pcm_drop(AlsaPCMHandle)) < 0) {
Error("audio: snd_pcm_drop(): %s", snd_strerror(err));
}
// ****ing alsa crash, when in open state here
if ((err = snd_pcm_prepare(AlsaPCMHandle)) < 0) {
Error("audio: snd_pcm_prepare(): %s", snd_strerror(err));
}
}
}
}
//----------------------------------------------------------------------------
// thread playback
//----------------------------------------------------------------------------
/**
** Alsa thread
**
** Play some samples and return.
**
** @retval -1 error
** @retval 0 underrun
** @retval 1 running
*/
static int AlsaThread(void)
{
int err;
if (!AlsaPCMHandle) {
usleep(24 * 1000);
return -1;
}
for (;;) {
if (AudioPaused) {
return 1;
}
// wait for space in kernel buffers
if ((err = snd_pcm_wait(AlsaPCMHandle, 24)) < 0) {
Error("audio/alsa: wait underrun error? '%s'", snd_strerror(err));
err = snd_pcm_recover(AlsaPCMHandle, err, 0);
if (err >= 0) {
continue;
}
Error("audio/alsa: snd_pcm_wait(): %s", snd_strerror(err));
usleep(24 * 1000);
return -1;
}
break;
}
if (AudioPaused) { // timeout or some commands
return 1;
}
if ((err = AlsaPlayRingbuffer())) { // empty or error
snd_pcm_state_t state;
if (err < 0) { // underrun error
return -1;
}
state = snd_pcm_state(AlsaPCMHandle);
if (state != SND_PCM_STATE_RUNNING) {
Debug5("audio/alsa: stopping play '%s'", snd_pcm_state_name(state));
return 0;
}
usleep(24 * 1000); // let fill/empty the buffers
}
return 1;
}
//----------------------------------------------------------------------------
/**
** Open alsa pcm device.
**
** @param passthrough use pass-through (AC-3, ...) device
*/
static snd_pcm_t *AlsaOpenPCM(int passthrough)
{
const char *device;
snd_pcm_t *handle;
int err;
// &&|| hell
if (!(passthrough && ((device = AudioPassthroughDevice)
|| (device = getenv("ALSA_PASSTHROUGH_DEVICE"))))
&& !(device = AudioPCMDevice) && !(device = getenv("ALSA_DEVICE"))) {
device = "default";
}
if (!AudioDoingInit) { // reduce blabla during init
Info("audio/alsa: using %sdevice '%s'", passthrough ? "pass-through " : "", device);
}
// open none blocking; if device is already used, we don't want wait
if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) < 0) {
Error("audio/alsa: playback open '%s' error: %s", device, snd_strerror(err));
return NULL;
}
if ((err = snd_pcm_nonblock(handle, 0)) < 0) {
Error("audio/alsa: can't set block mode: %s", snd_strerror(err));
}
return handle;
}
/**
** Initialize alsa pcm device.
**
** @see AudioPCMDevice
*/
static void AlsaInitPCM(void)
{
snd_pcm_t *handle;
snd_pcm_hw_params_t *hw_params;
int err;
if (!(handle = AlsaOpenPCM(0))) {
return;
}
// FIXME: pass-through and pcm out can support different features
snd_pcm_hw_params_alloca(&hw_params);
// choose all parameters
if ((err = snd_pcm_hw_params_any(handle, hw_params)) < 0) {
Error("audio: snd_pcm_hw_params_any: no configurations available: %s", snd_strerror(err));
}
AlsaCanPause = snd_pcm_hw_params_can_pause(hw_params);
Info("audio/alsa: supports pause: %s", AlsaCanPause ? "yes" : "no");
AlsaPCMHandle = handle;
}
//----------------------------------------------------------------------------
// Alsa Mixer
//----------------------------------------------------------------------------
/**
** Set alsa mixer volume (0-1000)
**
** @param volume volume (0 .. 1000)
*/
static void AlsaSetVolume(int volume)
{
if (AlsaMixer && AlsaMixerElem) {
int v = (volume * AlsaRatio) / (1000 * 1000);
snd_mixer_selem_set_playback_volume(AlsaMixerElem, 0, v);
snd_mixer_selem_set_playback_volume(AlsaMixerElem, 1, v);
}
}
/**
** Initialize alsa mixer.
*/
static void AlsaInitMixer(void)
{
const char *device;
const char *channel;
snd_mixer_t *alsa_mixer;
snd_mixer_elem_t *alsa_mixer_elem;
long alsa_mixer_elem_min;
long alsa_mixer_elem_max;
if (!(device = AudioMixerDevice)) {
if (!(device = getenv("ALSA_MIXER"))) {
device = "default";
}
}
if (!(channel = AudioMixerChannel)) {
if (!(channel = getenv("ALSA_MIXER_CHANNEL"))) {
channel = "PCM";
}
}
Debug5("audio/alsa: mixer %s - %s open", device, channel);
snd_mixer_open(&alsa_mixer, 0);
if (alsa_mixer && snd_mixer_attach(alsa_mixer, device) >= 0
&& snd_mixer_selem_register(alsa_mixer, NULL, NULL) >= 0 && snd_mixer_load(alsa_mixer) >= 0) {
const char *const alsa_mixer_elem_name = channel;
alsa_mixer_elem = snd_mixer_first_elem(alsa_mixer);