/
AESinkALSA.cpp
1695 lines (1448 loc) · 54.4 KB
/
AESinkALSA.cpp
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) 2010-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "AESinkALSA.h"
#include "ServiceBroker.h"
#include "cores/AudioEngine/AESinkFactory.h"
#include "cores/AudioEngine/Sinks/alsa/ALSADeviceMonitor.h"
#ifndef HAVE_X11
#include "cores/AudioEngine/Sinks/alsa/ALSAHControlMonitor.h"
#endif
#include "cores/AudioEngine/Utils/AEELDParser.h"
#include "cores/AudioEngine/Utils/AEUtil.h"
#include "platform/Platform.h"
#include "utils/XTimeUtils.h"
#include "utils/log.h"
#include <algorithm>
#include <limits.h>
#include <set>
#include <sstream>
#include <stdint.h>
#include <string>
#include <sys/utsname.h>
using namespace std::chrono_literals;
#define ALSA_OPTIONS (SND_PCM_NO_AUTO_FORMAT | SND_PCM_NO_AUTO_CHANNELS | SND_PCM_NO_AUTO_RESAMPLE)
#define ALSA_MAX_CHANNELS 16
static enum AEChannel LegacyALSAChannelMap[ALSA_MAX_CHANNELS + 1] = {
AE_CH_FL , AE_CH_FR , AE_CH_BL , AE_CH_BR , AE_CH_FC , AE_CH_LFE , AE_CH_SL , AE_CH_SR ,
AE_CH_UNKNOWN1, AE_CH_UNKNOWN2, AE_CH_UNKNOWN3, AE_CH_UNKNOWN4, AE_CH_UNKNOWN5, AE_CH_UNKNOWN6, AE_CH_UNKNOWN7, AE_CH_UNKNOWN8, /* for p16v devices */
AE_CH_NULL
};
static enum AEChannel LegacyALSAChannelMap51Wide[ALSA_MAX_CHANNELS + 1] = {
AE_CH_FL , AE_CH_FR , AE_CH_SL , AE_CH_SR , AE_CH_FC , AE_CH_LFE , AE_CH_BL , AE_CH_BR ,
AE_CH_UNKNOWN1, AE_CH_UNKNOWN2, AE_CH_UNKNOWN3, AE_CH_UNKNOWN4, AE_CH_UNKNOWN5, AE_CH_UNKNOWN6, AE_CH_UNKNOWN7, AE_CH_UNKNOWN8, /* for p16v devices */
AE_CH_NULL
};
static enum AEChannel ALSAChannelMapPassthrough[ALSA_MAX_CHANNELS + 1] = {
AE_CH_RAW , AE_CH_RAW , AE_CH_RAW , AE_CH_RAW , AE_CH_RAW , AE_CH_RAW , AE_CH_RAW , AE_CH_RAW ,
AE_CH_UNKNOWN1, AE_CH_UNKNOWN2, AE_CH_UNKNOWN3, AE_CH_UNKNOWN4, AE_CH_UNKNOWN5, AE_CH_UNKNOWN6, AE_CH_UNKNOWN7, AE_CH_UNKNOWN8, /* for p16v devices */
AE_CH_NULL
};
static unsigned int ALSASampleRateList[] =
{
5512,
8000,
11025,
16000,
22050,
32000,
44100,
48000,
64000,
88200,
96000,
176400,
192000,
384000,
0
};
namespace
{
struct SndConfigDeleter
{
void operator()(snd_config_t* p) { snd_config_delete(p); }
};
inline std::unique_ptr<snd_config_t, SndConfigDeleter> SndConfigCopy(snd_config_t* original)
{
snd_config_t* config;
snd_config_copy(&config, original);
return std::unique_ptr<snd_config_t, SndConfigDeleter>(config, SndConfigDeleter());
}
} // namespace
CAESinkALSA::CAESinkALSA() :
m_pcm(NULL)
{
/* ensure that ALSA has been initialized */
if (!snd_config)
snd_config_update();
}
CAESinkALSA::~CAESinkALSA()
{
Deinitialize();
}
void CAESinkALSA::Register()
{
AE::AESinkRegEntry entry;
entry.sinkName = "ALSA";
entry.createFunc = CAESinkALSA::Create;
entry.enumerateFunc = CAESinkALSA::EnumerateDevicesEx;
entry.cleanupFunc = CAESinkALSA::Cleanup;
AE::CAESinkFactory::RegisterSink(entry);
}
std::unique_ptr<IAESink> CAESinkALSA::Create(std::string& device, AEAudioFormat& desiredFormat)
{
auto sink = std::make_unique<CAESinkALSA>();
if (sink->Initialize(desiredFormat, device))
return sink;
return {};
}
inline CAEChannelInfo CAESinkALSA::GetChannelLayoutRaw(const AEAudioFormat& format)
{
unsigned int count = 0;
switch (format.m_streamInfo.m_type)
{
case CAEStreamInfo::STREAM_TYPE_DTSHD_MA:
case CAEStreamInfo::STREAM_TYPE_TRUEHD:
count = 8;
break;
case CAEStreamInfo::STREAM_TYPE_DTSHD_CORE:
case CAEStreamInfo::STREAM_TYPE_DTS_512:
case CAEStreamInfo::STREAM_TYPE_DTS_1024:
case CAEStreamInfo::STREAM_TYPE_DTS_2048:
case CAEStreamInfo::STREAM_TYPE_AC3:
case CAEStreamInfo::STREAM_TYPE_EAC3:
case CAEStreamInfo::STREAM_TYPE_DTSHD:
count = 2;
break;
default:
count = 0;
break;
}
CAEChannelInfo info;
for (unsigned int i = 0; i < count; ++i)
info += ALSAChannelMapPassthrough[i];
return info;
}
inline CAEChannelInfo CAESinkALSA::GetChannelLayoutLegacy(const AEAudioFormat& format, unsigned int minChannels, unsigned int maxChannels)
{
enum AEChannel* channelMap = LegacyALSAChannelMap;
unsigned int count = 0;
if (format.m_dataFormat == AE_FMT_RAW)
return GetChannelLayoutRaw(format);
// According to CEA-861-D only RL and RR are known. In case of a format having SL and SR channels
// but no BR BL channels, we use the wide map in order to open only the num of channels really
// needed.
if (format.m_channelLayout.HasChannel(AE_CH_SL) && !format.m_channelLayout.HasChannel(AE_CH_BL))
{
channelMap = LegacyALSAChannelMap51Wide;
}
for (unsigned int c = 0; c < 8; ++c)
{
for (unsigned int i = 0; i < format.m_channelLayout.Count(); ++i)
{
if (format.m_channelLayout[i] == channelMap[c])
{
count = c + 1;
break;
}
}
}
count = std::max(count, minChannels);
count = std::min(count, maxChannels);
CAEChannelInfo info;
for (unsigned int i = 0; i < count; ++i)
info += channelMap[i];
return info;
}
inline CAEChannelInfo CAESinkALSA::GetChannelLayout(const AEAudioFormat& format, unsigned int channels)
{
CAEChannelInfo info;
std::string alsaMapStr("none");
if (format.m_dataFormat == AE_FMT_RAW)
{
info = GetChannelLayoutRaw(format);
}
else
{
/* ask for the actual map */
snd_pcm_chmap_t* actualMap = snd_pcm_get_chmap(m_pcm);
if (actualMap)
{
alsaMapStr = ALSAchmapToString(actualMap);
info = ALSAchmapToAEChannelMap(actualMap);
/* "fake" a compatible map if it is more suitable for AE */
if (!info.ContainsChannels(format.m_channelLayout))
{
CAEChannelInfo infoAlternate = GetAlternateLayoutForm(info);
if (infoAlternate.Count())
{
std::vector<CAEChannelInfo> alts;
alts.push_back(info);
alts.push_back(infoAlternate);
if (format.m_channelLayout.BestMatch(alts) == 1)
info = infoAlternate;
}
}
/* add empty channels as needed (with e.g. FL,FR,LFE in 4ch) */
while (info.Count() < channels)
info += AE_CH_UNKNOWN1;
free(actualMap);
}
else
{
info = GetChannelLayoutLegacy(format, channels, channels);
}
}
CLog::Log(LOGDEBUG,
"CAESinkALSA::GetChannelLayout - Input Channel Count: {} Output Channel Count: {}",
format.m_channelLayout.Count(), info.Count());
CLog::Log(LOGDEBUG, "CAESinkALSA::GetChannelLayout - Requested Layout: {}",
std::string(format.m_channelLayout));
CLog::Log(LOGDEBUG, "CAESinkALSA::GetChannelLayout - Got Layout: {} (ALSA: {})",
std::string(info), alsaMapStr);
return info;
}
AEChannel CAESinkALSA::ALSAChannelToAEChannel(unsigned int alsaChannel)
{
AEChannel aeChannel;
switch (alsaChannel)
{
case SND_CHMAP_FL: aeChannel = AE_CH_FL; break;
case SND_CHMAP_FR: aeChannel = AE_CH_FR; break;
case SND_CHMAP_FC: aeChannel = AE_CH_FC; break;
case SND_CHMAP_LFE: aeChannel = AE_CH_LFE; break;
case SND_CHMAP_RL: aeChannel = AE_CH_BL; break;
case SND_CHMAP_RR: aeChannel = AE_CH_BR; break;
case SND_CHMAP_FLC: aeChannel = AE_CH_FLOC; break;
case SND_CHMAP_FRC: aeChannel = AE_CH_FROC; break;
case SND_CHMAP_RC: aeChannel = AE_CH_BC; break;
case SND_CHMAP_SL: aeChannel = AE_CH_SL; break;
case SND_CHMAP_SR: aeChannel = AE_CH_SR; break;
case SND_CHMAP_TFL: aeChannel = AE_CH_TFL; break;
case SND_CHMAP_TFR: aeChannel = AE_CH_TFR; break;
case SND_CHMAP_TFC: aeChannel = AE_CH_TFC; break;
case SND_CHMAP_TC: aeChannel = AE_CH_TC; break;
case SND_CHMAP_TRL: aeChannel = AE_CH_TBL; break;
case SND_CHMAP_TRR: aeChannel = AE_CH_TBR; break;
case SND_CHMAP_TRC: aeChannel = AE_CH_TBC; break;
case SND_CHMAP_RLC: aeChannel = AE_CH_BLOC; break;
case SND_CHMAP_RRC: aeChannel = AE_CH_BROC; break;
default: aeChannel = AE_CH_UNKNOWN1; break;
}
return aeChannel;
}
unsigned int CAESinkALSA::AEChannelToALSAChannel(AEChannel aeChannel)
{
unsigned int alsaChannel;
switch (aeChannel)
{
case AE_CH_FL: alsaChannel = SND_CHMAP_FL; break;
case AE_CH_FR: alsaChannel = SND_CHMAP_FR; break;
case AE_CH_FC: alsaChannel = SND_CHMAP_FC; break;
case AE_CH_LFE: alsaChannel = SND_CHMAP_LFE; break;
case AE_CH_BL: alsaChannel = SND_CHMAP_RL; break;
case AE_CH_BR: alsaChannel = SND_CHMAP_RR; break;
case AE_CH_FLOC: alsaChannel = SND_CHMAP_FLC; break;
case AE_CH_FROC: alsaChannel = SND_CHMAP_FRC; break;
case AE_CH_BC: alsaChannel = SND_CHMAP_RC; break;
case AE_CH_SL: alsaChannel = SND_CHMAP_SL; break;
case AE_CH_SR: alsaChannel = SND_CHMAP_SR; break;
case AE_CH_TFL: alsaChannel = SND_CHMAP_TFL; break;
case AE_CH_TFR: alsaChannel = SND_CHMAP_TFR; break;
case AE_CH_TFC: alsaChannel = SND_CHMAP_TFC; break;
case AE_CH_TC: alsaChannel = SND_CHMAP_TC; break;
case AE_CH_TBL: alsaChannel = SND_CHMAP_TRL; break;
case AE_CH_TBR: alsaChannel = SND_CHMAP_TRR; break;
case AE_CH_TBC: alsaChannel = SND_CHMAP_TRC; break;
case AE_CH_BLOC: alsaChannel = SND_CHMAP_RLC; break;
case AE_CH_BROC: alsaChannel = SND_CHMAP_RRC; break;
default: alsaChannel = SND_CHMAP_UNKNOWN; break;
}
return alsaChannel;
}
CAEChannelInfo CAESinkALSA::ALSAchmapToAEChannelMap(snd_pcm_chmap_t* alsaMap)
{
CAEChannelInfo info;
for (unsigned int i = 0; i < alsaMap->channels; i++)
info += ALSAChannelToAEChannel(alsaMap->pos[i]);
return info;
}
snd_pcm_chmap_t* CAESinkALSA::AEChannelMapToALSAchmap(const CAEChannelInfo& info)
{
int AECount = info.Count();
snd_pcm_chmap_t* alsaMap = (snd_pcm_chmap_t*)malloc(sizeof(snd_pcm_chmap_t) + AECount * sizeof(int));
alsaMap->channels = AECount;
for (int i = 0; i < AECount; i++)
alsaMap->pos[i] = AEChannelToALSAChannel(info[i]);
return alsaMap;
}
snd_pcm_chmap_t* CAESinkALSA::CopyALSAchmap(snd_pcm_chmap_t* alsaMap)
{
snd_pcm_chmap_t* copyMap = (snd_pcm_chmap_t*)malloc(sizeof(snd_pcm_chmap_t) + alsaMap->channels * sizeof(int));
copyMap->channels = alsaMap->channels;
memcpy(copyMap->pos, alsaMap->pos, alsaMap->channels * sizeof(int));
return copyMap;
}
std::string CAESinkALSA::ALSAchmapToString(snd_pcm_chmap_t* alsaMap)
{
char buf[128] = {};
//! @bug ALSA bug - buffer overflow by a factor of 2 is possible
//! http://mailman.alsa-project.org/pipermail/alsa-devel/2014-December/085815.html
int err = snd_pcm_chmap_print(alsaMap, sizeof(buf) / 2, buf);
if (err < 0)
return "Error";
return std::string(buf);
}
CAEChannelInfo CAESinkALSA::GetAlternateLayoutForm(const CAEChannelInfo& info)
{
CAEChannelInfo altLayout;
/* only handle symmetrical layouts */
if (info.HasChannel(AE_CH_BL) == info.HasChannel(AE_CH_BR) &&
info.HasChannel(AE_CH_SL) == info.HasChannel(AE_CH_SR) &&
info.HasChannel(AE_CH_BLOC) == info.HasChannel(AE_CH_BROC))
{
/* CEA-861-D used by HDMI 1.x has 7.1 as back+back-x-of-center, not
* side+back. Mangle it here. */
if (info.HasChannel(AE_CH_SL) && info.HasChannel(AE_CH_BL) && !info.HasChannel(AE_CH_BLOC))
{
altLayout = info;
altLayout.ReplaceChannel(AE_CH_BL, AE_CH_BLOC);
altLayout.ReplaceChannel(AE_CH_BR, AE_CH_BROC);
altLayout.ReplaceChannel(AE_CH_SL, AE_CH_BL);
altLayout.ReplaceChannel(AE_CH_SR, AE_CH_BR);
}
/* same in reverse */
else if (!info.HasChannel(AE_CH_SL) && info.HasChannel(AE_CH_BL) && info.HasChannel(AE_CH_BLOC))
{
altLayout = info;
altLayout.ReplaceChannel(AE_CH_BL, AE_CH_SL);
altLayout.ReplaceChannel(AE_CH_BR, AE_CH_SR);
altLayout.ReplaceChannel(AE_CH_BLOC, AE_CH_BL);
altLayout.ReplaceChannel(AE_CH_BROC, AE_CH_BR);
}
/* We have side speakers but no back speakers, allow map to back
* speakers. */
else if (info.HasChannel(AE_CH_SL) && !info.HasChannel(AE_CH_BL))
{
altLayout = info;
altLayout.ReplaceChannel(AE_CH_SL, AE_CH_BL);
altLayout.ReplaceChannel(AE_CH_SR, AE_CH_BR);
}
/* reverse */
else if (!info.HasChannel(AE_CH_SL) && info.HasChannel(AE_CH_BL))
{
altLayout = info;
altLayout.ReplaceChannel(AE_CH_BL, AE_CH_SL);
altLayout.ReplaceChannel(AE_CH_BR, AE_CH_SR);
}
}
return altLayout;
}
snd_pcm_chmap_t* CAESinkALSA::SelectALSAChannelMap(const CAEChannelInfo& info)
{
snd_pcm_chmap_t* chmap = NULL;
snd_pcm_chmap_query_t** supportedMaps;
supportedMaps = snd_pcm_query_chmaps(m_pcm);
if (!supportedMaps)
return NULL;
CAEChannelInfo infoAlternate = GetAlternateLayoutForm(info);
/* for efficiency, first try to find an exact match, and only then fallback
* to searching for less perfect matches */
int i = 0;
for (snd_pcm_chmap_query_t* supportedMap = supportedMaps[i++];
supportedMap; supportedMap = supportedMaps[i++])
{
if (supportedMap->map.channels == info.Count())
{
CAEChannelInfo candidate = ALSAchmapToAEChannelMap(&supportedMap->map);
const CAEChannelInfo* selectedInfo = &info;
if (!candidate.ContainsChannels(info) || !info.ContainsChannels(candidate))
{
selectedInfo = &infoAlternate;
if (!candidate.ContainsChannels(infoAlternate) || !infoAlternate.ContainsChannels(candidate))
continue;
}
if (supportedMap->type == SND_CHMAP_TYPE_VAR)
{
/* device supports the AE map directly */
chmap = AEChannelMapToALSAchmap(*selectedInfo);
break;
}
else
{
/* device needs 1:1 remapping */
chmap = CopyALSAchmap(&supportedMap->map);
break;
}
}
}
/* if no exact chmap was found, fallback to best-effort */
if (!chmap)
{
CAEChannelInfo allChannels;
std::vector<CAEChannelInfo> supportedMapsAE;
/* Convert the ALSA maps to AE maps. */
int i = 0;
for (snd_pcm_chmap_query_t* supportedMap = supportedMaps[i++];
supportedMap; supportedMap = supportedMaps[i++])
supportedMapsAE.push_back(ALSAchmapToAEChannelMap(&supportedMap->map));
int score = 0;
int best = info.BestMatch(supportedMapsAE, &score);
/* see if we find a better result with the alternate form */
if (infoAlternate.Count() && score < 0)
{
int scoreAlt = 0;
int bestAlt = infoAlternate.BestMatch(supportedMapsAE, &scoreAlt);
if (scoreAlt > score)
best = bestAlt;
}
if (best > 0)
chmap = CopyALSAchmap(&supportedMaps[best]->map);
}
if (chmap && CServiceBroker::GetLogging().CanLogComponent(LOGAUDIO))
CLog::Log(LOGDEBUG, "CAESinkALSA::SelectALSAChannelMap - Selected ALSA map \"{}\"",
ALSAchmapToString(chmap));
snd_pcm_free_chmaps(supportedMaps);
return chmap;
}
void CAESinkALSA::GetAESParams(const AEAudioFormat& format, std::string& params)
{
if (m_passthrough)
params = "AES0=0x06";
else
params = "AES0=0x04";
params += ",AES1=0x82,AES2=0x00";
if (m_passthrough && format.m_channelLayout.Count() == 8) params += ",AES3=0x09";
else if (format.m_sampleRate == 192000) params += ",AES3=0x0e";
else if (format.m_sampleRate == 176400) params += ",AES3=0x0c";
else if (format.m_sampleRate == 96000) params += ",AES3=0x0a";
else if (format.m_sampleRate == 88200) params += ",AES3=0x08";
else if (format.m_sampleRate == 48000) params += ",AES3=0x02";
else if (format.m_sampleRate == 44100) params += ",AES3=0x00";
else if (format.m_sampleRate == 32000) params += ",AES3=0x03";
else params += ",AES3=0x01";
}
bool CAESinkALSA::Initialize(AEAudioFormat &format, std::string &device)
{
m_initDevice = device;
m_initFormat = format;
ALSAConfig inconfig, outconfig;
inconfig.format = format.m_dataFormat;
inconfig.sampleRate = format.m_sampleRate;
/*
* We can't use the better GetChannelLayout() at this point as the device
* is not opened yet, and we need inconfig.channels to select the correct
* device... Legacy layouts should be accurate enough for device selection
* in all cases, though.
*/
inconfig.channels = GetChannelLayoutLegacy(format, 2, 8).Count();
/* if we are raw, correct the data format */
if (format.m_dataFormat == AE_FMT_RAW)
{
inconfig.format = AE_FMT_S16NE;
m_passthrough = true;
}
else
{
m_passthrough = false;
}
if (inconfig.channels == 0)
{
CLog::Log(LOGERROR, "CAESinkALSA::Initialize - Unable to open the requested channel layout");
return false;
}
AEDeviceType devType = AEDeviceTypeFromName(device);
std::string AESParams;
/* digital interfaces should have AESx set, though in practice most
* receivers don't care */
if (m_passthrough || devType == AE_DEVTYPE_HDMI || devType == AE_DEVTYPE_IEC958)
GetAESParams(format, AESParams);
CLog::Log(LOGINFO, "CAESinkALSA::Initialize - Attempting to open device \"{}\"", device);
/* get the sound config */
std::unique_ptr<snd_config_t, SndConfigDeleter> config = SndConfigCopy(snd_config);
if (!OpenPCMDevice(device, AESParams, inconfig.channels, &m_pcm, config.get()))
{
CLog::Log(LOGERROR, "CAESinkALSA::Initialize - failed to initialize device \"{}\"", device);
return false;
}
/* get the actual device name that was used */
device = snd_pcm_name(m_pcm);
m_device = device;
CLog::Log(LOGINFO, "CAESinkALSA::Initialize - Opened device \"{}\"", device);
snd_pcm_chmap_t* selectedChmap = NULL;
if (!m_passthrough)
{
selectedChmap = SelectALSAChannelMap(format.m_channelLayout);
if (selectedChmap)
{
/* update wanted channel count according to the selected map */
inconfig.channels = selectedChmap->channels;
}
}
if (!InitializeHW(inconfig, outconfig) || !InitializeSW(outconfig))
{
free(selectedChmap);
return false;
}
if (selectedChmap)
{
/* failure is OK, that likely just means the selected chmap is fixed already */
snd_pcm_set_chmap(m_pcm, selectedChmap);
free(selectedChmap);
}
// we want it blocking
snd_pcm_nonblock(m_pcm, 0);
snd_pcm_prepare (m_pcm);
if (m_passthrough && inconfig.channels != outconfig.channels)
{
CLog::Log(LOGINFO, "CAESinkALSA::Initialize - could not open required number of channels");
return false;
}
// adjust format to the configuration we got
format.m_channelLayout = GetChannelLayout(format, outconfig.channels);
// we might end up with an unusable channel layout that contains only UNKNOWN
// channels, let's do a sanity check.
if (!format.m_channelLayout.IsLayoutValid())
return false;
format.m_sampleRate = outconfig.sampleRate;
format.m_frames = outconfig.periodSize;
format.m_frameSize = outconfig.frameSize;
format.m_dataFormat = outconfig.format;
m_format = format;
m_formatSampleRateMul = 1.0 / (double)m_format.m_sampleRate;
return true;
}
snd_pcm_format_t CAESinkALSA::AEFormatToALSAFormat(const enum AEDataFormat format)
{
if (format == AE_FMT_RAW)
return SND_PCM_FORMAT_S16;
switch (format)
{
case AE_FMT_U8 : return SND_PCM_FORMAT_U8;
case AE_FMT_S16NE : return SND_PCM_FORMAT_S16;
case AE_FMT_S16LE : return SND_PCM_FORMAT_S16_LE;
case AE_FMT_S16BE : return SND_PCM_FORMAT_S16_BE;
case AE_FMT_S24NE4: return SND_PCM_FORMAT_S24;
#ifdef __BIG_ENDIAN__
case AE_FMT_S24NE3: return SND_PCM_FORMAT_S24_3BE;
#else
case AE_FMT_S24NE3: return SND_PCM_FORMAT_S24_3LE;
#endif
case AE_FMT_S32NE : return SND_PCM_FORMAT_S32;
case AE_FMT_FLOAT : return SND_PCM_FORMAT_FLOAT;
default:
return SND_PCM_FORMAT_UNKNOWN;
}
}
bool CAESinkALSA::InitializeHW(const ALSAConfig &inconfig, ALSAConfig &outconfig)
{
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
memset(hw_params, 0, snd_pcm_hw_params_sizeof());
snd_pcm_hw_params_any(m_pcm, hw_params);
snd_pcm_hw_params_set_access(m_pcm, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
unsigned int sampleRate = inconfig.sampleRate;
snd_pcm_hw_params_set_rate_near (m_pcm, hw_params, &sampleRate, NULL);
unsigned int channelCount = inconfig.channels;
/* select a channel count >=wanted, or otherwise the highest available */
if (snd_pcm_hw_params_set_channels_min(m_pcm, hw_params, &channelCount) == 0)
snd_pcm_hw_params_set_channels_first(m_pcm, hw_params, &channelCount);
else
snd_pcm_hw_params_set_channels_last(m_pcm, hw_params, &channelCount);
/* ensure we opened X channels or more */
if (inconfig.channels > channelCount)
{
CLog::Log(LOGINFO, "CAESinkALSA::InitializeHW - Unable to open the required number of channels");
}
/* update outconfig */
outconfig.channels = channelCount;
snd_pcm_format_t fmt = AEFormatToALSAFormat(inconfig.format);
outconfig.format = inconfig.format;
if (fmt == SND_PCM_FORMAT_UNKNOWN)
{
/* if we dont support the requested format, fallback to float */
fmt = SND_PCM_FORMAT_FLOAT;
outconfig.format = AE_FMT_FLOAT;
}
snd_pcm_hw_params_t *hw_params_copy;
snd_pcm_hw_params_alloca(&hw_params_copy);
snd_pcm_hw_params_copy(hw_params_copy, hw_params); // copy what we have
/* try the data format */
if (snd_pcm_hw_params_set_format(m_pcm, hw_params, fmt) < 0)
{
/* if the chosen format is not supported, try each one in descending order */
CLog::Log(LOGINFO,
"CAESinkALSA::InitializeHW - Your hardware does not support {}, trying other formats",
CAEUtil::DataFormatToStr(outconfig.format));
for (enum AEDataFormat i = AE_FMT_MAX; i > AE_FMT_INVALID; i = (enum AEDataFormat)((int)i - 1))
{
if (i == AE_FMT_RAW || i == AE_FMT_MAX)
continue;
if (m_passthrough && i != AE_FMT_S16BE && i != AE_FMT_S16LE)
continue;
fmt = AEFormatToALSAFormat(i);
if (fmt == SND_PCM_FORMAT_UNKNOWN)
continue;
snd_pcm_hw_params_copy(hw_params, hw_params_copy); // restore from copy
if (snd_pcm_hw_params_set_format(m_pcm, hw_params, fmt) < 0)
{
fmt = SND_PCM_FORMAT_UNKNOWN;
continue;
}
int fmtBits = CAEUtil::DataFormatToBits(i);
int bits = snd_pcm_hw_params_get_sbits(hw_params);
// skip bits check when alsa reports invalid sbits value
if (bits > 0 && bits != fmtBits)
{
/* if we opened in 32bit and only have 24bits, signal it accordingly */
if (fmt == SND_PCM_FORMAT_S32 && bits == 24)
i = AE_FMT_S24NE4MSB;
else if (fmt == SND_PCM_FORMAT_S24 && bits == 24)
i = AE_FMT_S24NE4;
else
continue;
}
/* record that the format fell back to X */
outconfig.format = i;
CLog::Log(LOGINFO, "CAESinkALSA::InitializeHW - Using data format {}",
CAEUtil::DataFormatToStr(outconfig.format));
break;
}
/* if we failed to find a valid output format */
if (fmt == SND_PCM_FORMAT_UNKNOWN)
{
CLog::Log(LOGERROR, "CAESinkALSA::InitializeHW - Unable to find a suitable output format");
return false;
}
}
snd_pcm_uframes_t periodSize, bufferSize;
snd_pcm_hw_params_get_buffer_size_max(hw_params, &bufferSize);
snd_pcm_hw_params_get_period_size_max(hw_params, &periodSize, NULL);
/*
We want to make sure, that we have max 200 ms Buffer with
a periodSize of approx 50 ms. Choosing a higher bufferSize
will cause problems with menu sounds. Buffer will be increased
after those are fixed.
*/
periodSize = std::min(periodSize, (snd_pcm_uframes_t) sampleRate / 20);
bufferSize = std::min(bufferSize, (snd_pcm_uframes_t) sampleRate / 5);
/*
According to upstream we should set buffer size first - so make sure it is always at least
4x period size to not get underruns (some systems seem to have issues with only 2 periods)
*/
periodSize = std::min(periodSize, bufferSize / 4);
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Request: periodSize {}, bufferSize {}",
periodSize, bufferSize);
snd_pcm_hw_params_copy(hw_params_copy, hw_params); // copy what we have and is already working
// Make sure to not initialize too large to not cause underruns
snd_pcm_uframes_t periodSizeMax = bufferSize / 3;
if(snd_pcm_hw_params_set_period_size_max(m_pcm, hw_params_copy, &periodSizeMax, NULL) != 0)
{
snd_pcm_hw_params_copy(hw_params_copy, hw_params); // restore working copy
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Request: Failed to limit periodSize to {}",
periodSizeMax);
}
// first trying bufferSize, PeriodSize
// for more info see here:
// http://mailman.alsa-project.org/pipermail/alsa-devel/2009-September/021069.html
// the last three tries are done as within pulseaudio
// backup periodSize and bufferSize first. Restore them after every failed try
snd_pcm_uframes_t periodSizeTemp, bufferSizeTemp;
periodSizeTemp = periodSize;
bufferSizeTemp = bufferSize;
if (snd_pcm_hw_params_set_buffer_size_near(m_pcm, hw_params_copy, &bufferSize) != 0
|| snd_pcm_hw_params_set_period_size_near(m_pcm, hw_params_copy, &periodSize, NULL) != 0
|| snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
bufferSize = bufferSizeTemp;
periodSize = periodSizeTemp;
// retry with PeriodSize, bufferSize
snd_pcm_hw_params_copy(hw_params_copy, hw_params); // restore working copy
if (snd_pcm_hw_params_set_period_size_near(m_pcm, hw_params_copy, &periodSize, NULL) != 0
|| snd_pcm_hw_params_set_buffer_size_near(m_pcm, hw_params_copy, &bufferSize) != 0
|| snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
// try only periodSize
periodSize = periodSizeTemp;
snd_pcm_hw_params_copy(hw_params_copy, hw_params); // restore working copy
if(snd_pcm_hw_params_set_period_size_near(m_pcm, hw_params_copy, &periodSize, NULL) != 0
|| snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
// try only BufferSize
bufferSize = bufferSizeTemp;
snd_pcm_hw_params_copy(hw_params_copy, hw_params); // restore working copy
if (snd_pcm_hw_params_set_buffer_size_near(m_pcm, hw_params_copy, &bufferSize) != 0
|| snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
// set default that Alsa would choose
CLog::Log(LOGWARNING, "CAESinkAlsa::InitializeHW - Using default alsa values - set failed");
if (snd_pcm_hw_params(m_pcm, hw_params) != 0)
{
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Could not init a valid sink");
return false;
}
}
}
// reread values when alsa default was kept
snd_pcm_get_params(m_pcm, &bufferSize, &periodSize);
}
}
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Got: periodSize {}, bufferSize {}", periodSize,
bufferSize);
/* set the format parameters */
outconfig.sampleRate = sampleRate;
/* if periodSize is too small Audio Engine might starve */
m_fragmented = false;
unsigned int fragments = 1;
if (periodSize < AE_MIN_PERIODSIZE)
{
fragments = std::ceil((double) AE_MIN_PERIODSIZE / periodSize);
CLog::Log(LOGDEBUG, "Audio Driver reports too low periodSize {} - will use {} fragments",
(int)periodSize, (int)fragments);
m_fragmented = true;
}
m_originalPeriodSize = periodSize;
outconfig.periodSize = fragments * periodSize;
outconfig.frameSize = snd_pcm_frames_to_bytes(m_pcm, 1);
m_bufferSize = (unsigned int)bufferSize;
m_timeout = std::ceil((double)(bufferSize * 1000) / (double)sampleRate);
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Setting timeout to {} ms", m_timeout);
return true;
}
bool CAESinkALSA::InitializeSW(const ALSAConfig &inconfig)
{
snd_pcm_sw_params_t *sw_params;
snd_pcm_uframes_t boundary;
snd_pcm_sw_params_alloca(&sw_params);
memset(sw_params, 0, snd_pcm_sw_params_sizeof());
snd_pcm_sw_params_current (m_pcm, sw_params);
snd_pcm_sw_params_set_start_threshold (m_pcm, sw_params, INT_MAX);
snd_pcm_sw_params_set_silence_threshold(m_pcm, sw_params, 0);
snd_pcm_sw_params_get_boundary (sw_params, &boundary);
snd_pcm_sw_params_set_silence_size (m_pcm, sw_params, boundary);
snd_pcm_sw_params_set_avail_min (m_pcm, sw_params, inconfig.periodSize);
if (snd_pcm_sw_params(m_pcm, sw_params) < 0)
{
CLog::Log(LOGERROR, "CAESinkALSA::InitializeSW - Failed to set the parameters");
return false;
}
return true;
}
void CAESinkALSA::Deinitialize()
{
if (m_pcm)
{
Stop();
snd_pcm_close(m_pcm);
m_pcm = NULL;
}
}
void CAESinkALSA::Stop()
{
if (!m_pcm)
return;
snd_pcm_drop(m_pcm);
}
void CAESinkALSA::GetDelay(AEDelayStatus& status)
{
if (!m_pcm)
{
status.SetDelay(0);
return;
}
snd_pcm_sframes_t frames = 0;
snd_pcm_delay(m_pcm, &frames);
if (frames < 0)
{
snd_pcm_forward(m_pcm, -frames);
frames = 0;
}
status.SetDelay((double)frames * m_formatSampleRateMul);
}
double CAESinkALSA::GetCacheTotal()
{
return (double)m_bufferSize * m_formatSampleRateMul;
}
unsigned int CAESinkALSA::AddPackets(uint8_t **data, unsigned int frames, unsigned int offset)
{
if (!m_pcm)
{
CLog::Log(LOGERROR, "CAESinkALSA - Tried to add packets without a sink");
return INT_MAX;
}
void *buffer = data[0]+offset*m_format.m_frameSize;
unsigned int amount = 0;
int64_t data_left = (int64_t) frames;
int frames_written = 0;
while (data_left > 0)
{
if (m_fragmented)
amount = std::min((unsigned int) data_left, m_originalPeriodSize);
else // take care as we can come here a second time if the sink does not eat all data
amount = (unsigned int) data_left;
int ret = snd_pcm_writei(m_pcm, buffer, amount);
if (ret < 0)
{
CLog::Log(LOGERROR, "CAESinkALSA - snd_pcm_writei({}) {} - trying to recover", ret,
snd_strerror(ret));
ret = snd_pcm_recover(m_pcm, ret, 1);
if(ret < 0)
{
HandleError("snd_pcm_writei(1)", ret);
ret = snd_pcm_writei(m_pcm, buffer, amount);
if (ret < 0)
{
HandleError("snd_pcm_writei(2)", ret);
ret = 0;
}
}
}
if ( ret > 0 && snd_pcm_state(m_pcm) == SND_PCM_STATE_PREPARED)
snd_pcm_start(m_pcm);
if (ret <= 0)
break;
frames_written += ret;
data_left -= ret;
buffer = data[0]+offset*m_format.m_frameSize + frames_written*m_format.m_frameSize;
}
return frames_written;
}
void CAESinkALSA::HandleError(const char* name, int err)
{
switch(err)
{
case -EPIPE:
CLog::Log(LOGERROR, "CAESinkALSA::HandleError({}) - underrun", name);
if ((err = snd_pcm_prepare(m_pcm)) < 0)
CLog::Log(LOGERROR, "CAESinkALSA::HandleError({}) - snd_pcm_prepare returned {} ({})", name,
err, snd_strerror(err));
break;
case -ESTRPIPE:
CLog::Log(LOGINFO, "CAESinkALSA::HandleError({}) - Resuming after suspend", name);
/* try to resume the stream */
while((err = snd_pcm_resume(m_pcm)) == -EAGAIN)
KODI::TIME::Sleep(1ms);
/* if the hardware doesn't support resume, prepare the stream */
if (err == -ENOSYS)
if ((err = snd_pcm_prepare(m_pcm)) < 0)
CLog::Log(LOGERROR, "CAESinkALSA::HandleError({}) - snd_pcm_prepare returned {} ({})",
name, err, snd_strerror(err));
break;
default:
CLog::Log(LOGERROR, "CAESinkALSA::HandleError({}) - snd_pcm_writei returned {} ({})", name,
err, snd_strerror(err));
break;
}
}
void CAESinkALSA::Drain()
{
if (!m_pcm)
return;
snd_pcm_drain(m_pcm);
snd_pcm_prepare(m_pcm);
}
void CAESinkALSA::AppendParams(std::string &device, const std::string ¶ms)
{
/* Note: escaping, e.g. "plug:'something:X=y'" isn't handled,
* but it is not normally encountered at this point. */
device += (device.find(':') == std::string::npos) ? ':' : ',';