-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathaudio.c
1781 lines (1575 loc) · 46.8 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
///
/// @file audio.c @brief Audio module
///
/// Copyright (c) 2009 - 2014 by Johns. All Rights Reserved.
/// Copyright (c) 2018 by zille. All Rights Reserved.
///
/// Contributor(s):
///
/// License: AGPLv3
///
/// This program is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Affero General Public License as
/// published by the Free Software Foundation, either version 3 of the
/// License.
///
/// This program 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 Affero General Public License for more details.
///
/// $Id$
//////////////////////////////////////////////////////////////////////////////
///
/// @defgroup Audio The audio module.
///
/// 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!
///
/// @todo FIXME: there can be problems with little/big endian.
///
#include <stdint.h>
#include <math.h>
#include <libintl.h>
#define _(str) gettext(str) ///< gettext shortcut
#define _N(str) str ///< gettext_noop shortcut
#include <alsa/asoundlib.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <pthread.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libavfilter/avfilter.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include "iatomic.h" // portable atomic_t
#include "ringbuffer.h"
#include "misc.h"
#include "audio.h"
#include "video.h"
#include "codec.h"
#include "softhddev.h"
//----------------------------------------------------------------------------
// Defines
//----------------------------------------------------------------------------
#define MIN_AUDIO_BUFFER 450 ///< minimal output buffer in ms
//----------------------------------------------------------------------------
// Variables
//----------------------------------------------------------------------------
static const char *AudioPCMDevice; ///< PCM device name
static const char *AudioPassthroughDevice; ///< Passthrough device name
static char AudioAppendAES; ///< flag automatic append AES
static const char *AudioMixerDevice; ///< mixer device name
static const char *AudioMixerChannel; ///< mixer channel name
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; ///< audio buffer time in ms
static pthread_t AudioThread; ///< audio play thread
static pthread_mutex_t AudioRbMutex; ///< audio condition mutex
static pthread_mutex_t AudioStartMutex; ///< audio condition mutex
static pthread_cond_t AudioStartCond; ///< condition variable
static char AudioThreadStop; ///< stop audio thread
static char AlsaPlayerStop; ///< 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)
static int AudioDownMix;
extern int VideoAudioDelay; ///< import audio/video delay
/// default ring buffer size ~2s 8ch 16bit (3 * 5 * 7 * 8)
static const unsigned AudioRingBufferSize = 3 * 5 * 7 * 8 * 2 * 1000;
// 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
// Filter variables
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
AVFilterGraph *filter_graph;
AVFilterContext *abuffersrc_ctx, *abuffersink_ctx;
int FilterInit;
float AudioEqBand[18];
int AudioEq;
int Filterchanged;
// ring buffer variables
char Passthrough; ///< flag: use pass-through (AC-3, ...)
unsigned int HwSampleRate; ///< hardware sample rate in Hz
unsigned int HwChannels; ///< hardware number of channels
AVRational *timebase; ///< pointer to AVCodecContext pkts_timebase
int64_t PTS; ///< pts clock
RingBuffer *AudioRingBuffer; ///< sample ring buffer
static unsigned AudioStartThreshold; ///< start play, if filled
static int AlsaSetup(int channels, int sample_rate, int passthrough);
//----------------------------------------------------------------------------
// Filter
//----------------------------------------------------------------------------
/**
** Reorder audio frame.
**
** 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 buf[IN,OUT] sample buffer
** @param size size of sample buffer in bytes
** @param channels number of channels interleaved in sample buffer
*/
static void AudioReorderAudioFrame(int16_t * buf, int size, int channels)
{
int i;
int c;
int ls;
int rs;
int lfe;
switch (channels) {
case 5:
size /= 2;
for (i = 0; i < size; i += 5) {
c = buf[i + 2];
ls = buf[i + 3];
rs = buf[i + 4];
buf[i + 2] = ls;
buf[i + 3] = rs;
buf[i + 4] = c;
}
break;
case 6:
size /= 2;
for (i = 0; i < size; i += 6) {
c = buf[i + 2];
lfe = buf[i + 3];
// ls = buf[i + 4]; tested from jsffm
// rs = buf[i + 5];
// buf[i + 2] = ls;
// buf[i + 3] = rs;
buf[i + 2] = lfe;
buf[i + 3] = c;
// buf[i + 4] = c;
// buf[i + 5] = lfe;
}
break;
case 8:
size /= 2;
for (i = 0; i < size; i += 8) {
c = buf[i + 2];
lfe = buf[i + 3];
ls = buf[i + 4];
rs = buf[i + 5];
buf[i + 2] = ls;
buf[i + 3] = rs;
buf[i + 4] = c;
buf[i + 5] = lfe;
}
break;
}
}
/**
** 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 n;
uint32_t avg;
int factor;
int16_t *data;
// average samples
l = count / AudioBytesProSample;
data = samples;
do {
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;
}
Debug(4, "audio/noramlize: avg %8d, fac=%6.3f, norm=%6.3f\n",
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)
{
int max_sample;
int i;
int factor;
// find loudest sample
max_sample = 0;
for (i = 0; i < count / AudioBytesProSample; ++i) {
int t;
t = abs(samples[i]);
if (t > max_sample) {
max_sample = t;
}
}
// calculate compression factor
if (max_sample > 0) {
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;
}
} else {
return; // silent nothing todo
}
Debug(4, "audio/compress: max %5d, fac=%6.3f, com=%6.3f\n", max_sample,
factor / 1000.0, AudioCompressionFactor / 1000.0);
// apply compression factor
for (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;
}
}
/**
** Set filter bands.
**
** @param band setting frequenz bands
** @param onoff set using equalizer
*/
void AudioSetEq(int band[17], int onoff)
{
int i;
/* fprintf(stderr, "AudioSetEq %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i onoff %d\n",
band[0], band[1], band[2], band[3], band[4], band[5], band[6], band[7],
band[8], band[9], band[10], band[11], band[12], band[13], band[14],
band[15], band[16], band[17], onoff);*/
for (i = 0; i < 18; i++) {
switch (band[i]) {
case 1:
AudioEqBand[i] = 1.5;
break;
case 0:
AudioEqBand[i] = 1;
break;
case -1:
AudioEqBand[i] = 0.95;
break;
case -2:
AudioEqBand[i] = 0.9;
break;
case -3:
AudioEqBand[i] = 0.85;
break;
case -4:
AudioEqBand[i] = 0.8;
break;
case -5:
AudioEqBand[i] = 0.75;
break;
case -6:
AudioEqBand[i] = 0.7;
break;
case -7:
AudioEqBand[i] = 0.65;
break;
case -8:
AudioEqBand[i] = 0.6;
break;
case -9:
AudioEqBand[i] = 0.55;
break;
case -10:
AudioEqBand[i] = 0.5;
break;
case -11:
AudioEqBand[i] = 0.45;
break;
case -12:
AudioEqBand[i] = 0.4;
break;
case -13:
AudioEqBand[i] = 0.35;
break;
case -14:
AudioEqBand[i] = 0.3;
break;
case -15:
AudioEqBand[i] = 0.25;
break;
}
}
Filterchanged = 1;
AudioEq = onoff;
}
/**
** Filter init.
**
** @retval 0 everything ok
** @retval 1 didn't support channels, CodecDownmix set > scrap this frame, test next
** @retval -1 something gone wrong
*/
static int AudioFilterInit(AVCodecContext *AudioCtx)
{
const AVFilter *abuffer;
AVFilterContext *filter_ctx[3];
const AVFilter *eq;
const AVFilter *aformat;
const AVFilter *abuffersink;
char ch_layout[64];
char options_str[1024];
int err, i, n_filter = 0;
// Before filter init set HW parameter.
if (AudioCtx->sample_rate != (int)HwSampleRate ||
(AudioCtx->channels != (int)HwChannels &&
!(AudioDownMix && HwChannels == 2))) {
err = AlsaSetup(AudioCtx->channels, AudioCtx->sample_rate, 0);
if (err)
return err;
}
timebase = &AudioCtx->pkt_timebase;
#if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(7,16,100)
avfilter_register_all();
#endif
if (!(filter_graph = avfilter_graph_alloc()))
fprintf(stderr, "Unable to create filter graph.\n");
// input buffer
if (!(abuffer = avfilter_get_by_name("abuffer")))
fprintf(stderr, "AudioFilterInit: Could not find the abuffer filter.\n");
if (!(abuffersrc_ctx = avfilter_graph_alloc_filter(filter_graph, abuffer, "src")))
fprintf(stderr, "AudioFilterInit: Could not allocate the abuffersrc_ctx instance.\n");
av_get_channel_layout_string(ch_layout, sizeof(ch_layout), AudioCtx->channels, AudioCtx->channel_layout);
#ifdef DEBUG
fprintf(stderr, "AudioFilterInit: IN ch_layout %s sample_fmt %s sample_rate %d channels %d\n",
ch_layout, av_get_sample_fmt_name(AudioCtx->sample_fmt), AudioCtx->sample_rate, AudioCtx->channels);
#endif
av_opt_set (abuffersrc_ctx, "channel_layout", ch_layout, AV_OPT_SEARCH_CHILDREN);
av_opt_set (abuffersrc_ctx, "sample_fmt", av_get_sample_fmt_name(AudioCtx->sample_fmt), AV_OPT_SEARCH_CHILDREN);
av_opt_set_q (abuffersrc_ctx, "time_base", (AVRational){ 1, AudioCtx->sample_rate }, AV_OPT_SEARCH_CHILDREN);
av_opt_set_int(abuffersrc_ctx, "sample_rate", AudioCtx->sample_rate, AV_OPT_SEARCH_CHILDREN);
// av_opt_set_int(abuffersrc_ctx, "channel_counts", AudioCtx->channels, AV_OPT_SEARCH_CHILDREN);
// initialize the filter with NULL options, set all options above.
if (avfilter_init_str(abuffersrc_ctx, NULL) < 0)
fprintf(stderr, "AudioFilterInit: Could not initialize the abuffer filter.\n");
if (AudioEq) {
// superequalizer
if (!(eq = avfilter_get_by_name("superequalizer")))
fprintf(stderr, "AudioFilterInit: Could not find the superequalizer filter.\n");
if (!(filter_ctx[n_filter] = avfilter_graph_alloc_filter(filter_graph, eq, "superequalizer")))
fprintf(stderr, "AudioFilterInit: Could not allocate the superequalizer instance.\n");
snprintf(options_str, sizeof(options_str),"1b=%.2f:2b=%.2f:3b=%.2f:4b=%.2f:5b=%.2f"
":6b=%.2f:7b=%.2f:8b=%.2f:9b=%.2f:10b=%.2f:11b=%.2f:12b=%.2f:13b=%.2f:14b=%.2f:"
"15b=%.2f:16b=%.2f:17b=%.2f:18b=%.2f ", AudioEqBand[0], AudioEqBand[1],
AudioEqBand[2], AudioEqBand[3], AudioEqBand[4], AudioEqBand[5],
AudioEqBand[6], AudioEqBand[7], AudioEqBand[8], AudioEqBand[9],
AudioEqBand[10], AudioEqBand[11], AudioEqBand[12], AudioEqBand[13],
AudioEqBand[14], AudioEqBand[15], AudioEqBand[16], AudioEqBand[17]);
if (avfilter_init_str(filter_ctx[n_filter], options_str) < 0)
fprintf(stderr, "AudioFilterInit: Could not initialize the superequalizer filter.\n");
n_filter++;
}
// aformat
av_get_channel_layout_string(ch_layout, sizeof(ch_layout),
HwChannels, av_get_default_channel_layout(HwChannels)); // should use IN layout if more then 2 ch!?
#ifdef DEBUG
fprintf(stderr, "AudioFilterInit: OUT AudioDownMix %d HwChannels %d HwSampleRate %d ch_layout %s bytes_per_sample %d\n",
AudioDownMix, HwChannels, HwSampleRate,
ch_layout, av_get_bytes_per_sample(AV_SAMPLE_FMT_S16));
#endif
if (!(aformat = avfilter_get_by_name("aformat")))
fprintf(stderr, "AudioFilterInit: Could not find the aformat filter.\n");
if (!(filter_ctx[n_filter] = avfilter_graph_alloc_filter(filter_graph, aformat, "aformat")))
fprintf(stderr, "AudioFilterInit: Could not allocate the aformat instance.\n");
snprintf(options_str, sizeof(options_str),
"sample_fmts=%s:sample_rates=%d:channel_layouts=%s",
av_get_sample_fmt_name(AV_SAMPLE_FMT_S16), HwSampleRate, ch_layout);
if (avfilter_init_str(filter_ctx[n_filter], options_str) < 0)
fprintf(stderr, "AudioFilterInit: Could not initialize the aformat filter.\n");
n_filter++;
// abuffersink
if (!(abuffersink = avfilter_get_by_name("abuffersink")))
fprintf(stderr, "AudioFilterInit: Could not find the abuffersink filter.\n");
if (!(filter_ctx[n_filter] = avfilter_graph_alloc_filter(filter_graph, abuffersink, "sink")))
fprintf(stderr, "AudioFilterInit: Could not allocate the abuffersink instance.\n");
if (avfilter_init_str(filter_ctx[n_filter], NULL) < 0)
fprintf(stderr, "AudioFilterInit: Could not initialize the abuffersink instance.\n");
n_filter++;
// Connect the filters
for (i = 0; i < n_filter; i++) {
if (i == 0) {
err = avfilter_link(abuffersrc_ctx, 0, filter_ctx[i], 0);
} else {
err = avfilter_link(filter_ctx[i - 1], 0, filter_ctx[i], 0);
}
}
if (err < 0)
fprintf(stderr, "AudioFilterInit: Error connecting audio filters\n");
// Configure the graph.
if (avfilter_graph_config(filter_graph, NULL) < 0)
fprintf(stderr, "AudioFilterInit: Error configuring the audio filter graph\n");
abuffersink_ctx = filter_ctx[n_filter - 1];
Filterchanged = 0;
FilterInit = 1;
return 0;
}
//----------------------------------------------------------------------------
// ring buffer
//----------------------------------------------------------------------------
/**
** Setup audio ring.
*/
static void AudioRingInit(void)
{
// ~2s 8ch 16bit
AudioRingBuffer = RingBufferNew(AudioRingBufferSize);
}
/**
** Cleanup audio ring.
*/
static void AudioRingExit(void)
{
if (AudioRingBuffer) {
RingBufferDel(AudioRingBuffer);
AudioRingBuffer = NULL;
}
HwSampleRate = 0; // checked for valid setup
}
//============================================================================
// A L S A
//============================================================================
//----------------------------------------------------------------------------
// alsa pcm
//----------------------------------------------------------------------------
/**
** xrun recovery
**/
static void xrun_recovery(void)
{
int err;
snd_pcm_state_t state;
err = snd_pcm_prepare(AlsaPCMHandle);
if (err < 0) {
state = snd_pcm_state(AlsaPCMHandle);
Error(_("audio/alsa: Can't recovery from xrun: %s pcm state: %s\n"),
snd_strerror(err), snd_pcm_state_name(state));
}
}
/**
** Flush alsa buffers.
*/
static void AlsaFlushBuffers(void)
{
int err;
snd_pcm_state_t state;
#ifdef DEBUG
fprintf(stderr, "AlsaFlushBuffers: AlsaFlushBuffers\n");
#endif
state = snd_pcm_state(AlsaPCMHandle);
if (state != SND_PCM_STATE_OPEN) {
if ((err = snd_pcm_drop(AlsaPCMHandle)) < 0) {
Error(_("audio: snd_pcm_drop(): %s\n"), snd_strerror(err));
fprintf(stderr, "AlsaFlushBuffers: snd_pcm_drop(): %s\n", snd_strerror(err));
}
// ****ing alsa crash, when in open state here
if ((err = snd_pcm_prepare(AlsaPCMHandle)) < 0) {
Error(_("audio: snd_pcm_prepare(): %s\n"), snd_strerror(err));
fprintf(stderr, "AlsaFlushBuffers: snd_pcm_prepare(): %s\n",
snd_strerror(err));
}
state = snd_pcm_state(AlsaPCMHandle);
Debug(3, "audio/AlsaFlushBuffers: pcm state %s\n", snd_pcm_state_name(state));
}
RingBufferReset(AudioRingBuffer);
AudioSkip = 0;
PTS = AV_NOPTS_VALUE;
AudioVideoIsReady = 0;
}
//----------------------------------------------------------------------------
// thread playback
//----------------------------------------------------------------------------
/**
** Alsa thread
**
** Play some samples and return.
**
** @retval -1 error
** @retval 1 running
*/
static int AlsaPlayer(void)
{
for (;;) {
int avail;
int n;
int err;
int frames;
const void *p;
if (AudioPaused || AlsaPlayerStop) {
return 1;
}
// wait for space in kernel buffers
if ((err = snd_pcm_wait(AlsaPCMHandle, 150)) < 0) {
// fprintf(stderr, "AlsaPlayer: snd_pcm_wait error? '%s'\n", snd_strerror(err));
err = snd_pcm_recover(AlsaPCMHandle, err, 0);
// printf("AlsaPlayer: snd_pcm_wait error: snd_pcm_recover %s\n", snd_strerror(err));
}
if (AudioPaused || AlsaPlayerStop) {
return 1;
}
// how many bytes can be written?
// n = snd_pcm_avail_update(AlsaPCMHandle);
n = snd_pcm_avail(AlsaPCMHandle);
if (n < 0) {
if (n == -EAGAIN) {
continue;
}
err = snd_pcm_recover(AlsaPCMHandle, n, 0);
if (err >= 0) {
continue;
}
Error(_("audio/alsa: snd_pcm_avail_update(): %s\n"),
snd_strerror(n));
return -1;
}
avail = snd_pcm_frames_to_bytes(AlsaPCMHandle, n);
if (avail < 256) { // too much overhead
Debug(4, "audio/alsa: break state '%s'\n",
snd_pcm_state_name(snd_pcm_state(AlsaPCMHandle)));
break;
}
n = RingBufferGetReadPointer(AudioRingBuffer, &p);
if (!n) { // ring buffer empty
fprintf(stderr, "AlsaPlayer: ring buffer empty Videopkts: %d\n",
VideoGetPackets());
}
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
&& !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);
pthread_mutex_lock(&AudioRbMutex);
if (AlsaUseMmap) {
err = snd_pcm_mmap_writei(AlsaPCMHandle, p, frames);
} else {
err = snd_pcm_writei(AlsaPCMHandle, p, frames);
}
RingBufferReadAdvance(AudioRingBuffer, avail);
pthread_mutex_unlock(&AudioRbMutex);
if (err != frames) {
if (err < 0) {
if (err == -EAGAIN) {
continue;
}
Warning(_("audio/alsa: writei underrun error? '%s'\n"),
snd_strerror(err));
err = snd_pcm_recover(AlsaPCMHandle, err, 0);
if (err >= 0) {
continue;
}
Error(_("audio/alsa: snd_pcm_writei failed: %s\n"),
snd_strerror(err));
return -1;
}
// this could happen, if underrun happened
Warning(_("audio/alsa: not all frames written\n"));
avail = snd_pcm_frames_to_bytes(AlsaPCMHandle, err);
break;
}
}
return 0;
}
//----------------------------------------------------------------------------
/**
** Open alsa pcm device.
*/
static void AlsaInitPCM(void)
{
const char *device;
int err;
if (!(Passthrough && ((device = AudioPassthroughDevice)
|| (device = getenv("ALSA_PASSTHROUGH_DEVICE"))))
&& !(device = AudioPCMDevice) && !(device = getenv("ALSA_DEVICE"))) {
device = "default";
}
Info(_("audio/alsa: using %sdevice '%s'\n"),
Passthrough ? "pass-through " : "", device);
#if 0
// for AC3 pass-through try to set the non-audio bit, use AES0=6 to set spdif in raw mode
if (Passthrough && AudioAppendAES) {
// FIXME: not yet finished
char *buf;
const char *s;
int n;
n = strlen(device);
buf = alloca(n + sizeof(":AES0=6") + 1);
strcpy(buf, device);
if (!(s = strchr(buf, ':'))) {
// no alsa parameters
strcpy(buf + n, ":AES=6");
}
Debug(3, "audio/alsa: try '%s'\n", buf);
}
#endif
// open none blocking; if device is already used, we don't want wait
if ((err = snd_pcm_open(&AlsaPCMHandle, device, SND_PCM_STREAM_PLAYBACK,
SND_PCM_NONBLOCK)) < 0) {
fprintf(stderr, "AlsaOpenPCM: playback open '%s' error: %s\n",
device, snd_strerror(err));
Fatal(_("audio/alsa: playback open '%s' error: %s\n"), device,
snd_strerror(err));
}
if ((err = snd_pcm_nonblock(AlsaPCMHandle, 0)) < 0) {
Error(_("audio/alsa: can't set block mode: %s\n"), snd_strerror(err));
}
}
//----------------------------------------------------------------------------
// Alsa Mixer
//----------------------------------------------------------------------------
/**
** Set alsa mixer volume (0-1000)
**
** @param volume volume (0 .. 1000)
*/
static void AlsaSetVolume(int volume)
{
int v;
if (AlsaMixer && AlsaMixerElem) {
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";
}
}
Debug(3, "audio/alsa: mixer %s - %s open\n", 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);
while (alsa_mixer_elem) {
const char *name;
name = snd_mixer_selem_get_name(alsa_mixer_elem);
if (!strcasecmp(name, alsa_mixer_elem_name)) {
snd_mixer_selem_get_playback_volume_range(alsa_mixer_elem,
&alsa_mixer_elem_min, &alsa_mixer_elem_max);
AlsaRatio = 1000 * (alsa_mixer_elem_max - alsa_mixer_elem_min);
Debug(3, "audio/alsa: PCM mixer found %ld - %ld ratio %d\n",
alsa_mixer_elem_min, alsa_mixer_elem_max, AlsaRatio);
break;
}
alsa_mixer_elem = snd_mixer_elem_next(alsa_mixer_elem);
}
AlsaMixer = alsa_mixer;
AlsaMixerElem = alsa_mixer_elem;
} else {
Error(_("audio/alsa: can't open mixer '%s'\n"), device);
}
}
//----------------------------------------------------------------------------
// Alsa API
//----------------------------------------------------------------------------
/**
** Setup alsa audio for requested format.
**
** @param channels Channels requested
** @param sample_rate SampleRate requested
** @param passthrough use pass-through (AC-3, ...) device
**
** @retval 0 everything ok
** @retval 1 didn't support hw channels, CodecDownmix set > retest
** @retval -1 something gone wrong
**
** @todo FIXME: remove pointer for freq + channels
*/
static int AlsaSetup(int channels, int sample_rate, __attribute__ ((unused)) int passthrough)
{
snd_pcm_hw_params_t *hwparams;
snd_pcm_state_t state;
int err;
int delay;
unsigned buffer_time = 100000; // 100ms
AudioDownMix = 0;
if (AudioRunning) {
#ifdef SOUND_DEBUG
fprintf(stderr, "AlsaSetup: Audio is Running => AudioFlushBuffers\n");
#endif
AudioFlushBuffers();
}
state = snd_pcm_state(AlsaPCMHandle);
if (state == SND_PCM_STATE_XRUN) {
Error(_("audio/AlsaSetup: recover from xrun pcm state: %s\n"),
snd_pcm_state_name(state));
xrun_recovery();
}
snd_pcm_hw_params_alloca(&hwparams);
if ((err = snd_pcm_hw_params_any(AlsaPCMHandle, hwparams)) < 0) {
fprintf(stderr, "AlsaSetup: Read HW config failed! %s\n", snd_strerror(err));
return -1;
}
if (!snd_pcm_hw_params_test_access(AlsaPCMHandle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED)) {
AlsaUseMmap = 1;
}
HwSampleRate = sample_rate;
if ((err = snd_pcm_hw_params_set_rate_near(AlsaPCMHandle, hwparams, &HwSampleRate, 0) < 0)) {
fprintf(stderr, "AlsaSetup: SampleRate %d not supported! %s\n",
sample_rate, snd_strerror(err));
return -1;
}
if ((int)HwSampleRate != sample_rate) {
fprintf(stderr, "AlsaSetup: sample_rate %d HwSampleRate %d\n",
sample_rate, HwSampleRate);
}