forked from xbmc/xbmc
/
AESinkALSA.cpp
1140 lines (960 loc) · 35.8 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-2012 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "system.h"
#ifdef HAS_ALSA
#include <stdint.h>
#include <limits.h>
#include <set>
#include <sstream>
#include "AESinkALSA.h"
#include "Utils/AEUtil.h"
#include "Utils/AEELDParser.h"
#include "utils/StdString.h"
#include "utils/log.h"
#include "utils/MathUtils.h"
#include "threads/SingleLock.h"
#include "settings/GUISettings.h"
#define ALSA_OPTIONS (SND_PCM_NONBLOCK | SND_PCM_NO_AUTO_FORMAT | SND_PCM_NO_AUTO_CHANNELS | SND_PCM_NO_AUTO_RESAMPLE)
#define ALSA_PERIODS 16
#define ALSA_MAX_CHANNELS 16
static enum AEChannel ALSAChannelMap[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 unsigned int ALSASampleRateList[] =
{
5512,
8000,
11025,
16000,
22050,
32000,
44100,
48000,
64000,
88200,
96000,
176400,
192000,
384000,
0
};
CAESinkALSA::CAESinkALSA() :
m_pcm(NULL)
{
/* ensure that ALSA has been initialized */
if (!snd_config)
snd_config_update();
}
CAESinkALSA::~CAESinkALSA()
{
Deinitialize();
}
inline CAEChannelInfo CAESinkALSA::GetChannelLayout(AEAudioFormat format)
{
unsigned int count = 0;
if (format.m_dataFormat == AE_FMT_AC3 ||
format.m_dataFormat == AE_FMT_DTS ||
format.m_dataFormat == AE_FMT_EAC3)
count = 2;
else if (format.m_dataFormat == AE_FMT_TRUEHD ||
format.m_dataFormat == AE_FMT_DTSHD)
count = 8;
else
{
for (unsigned int c = 0; c < 8; ++c)
for (unsigned int i = 0; i < format.m_channelLayout.Count(); ++i)
if (format.m_channelLayout[i] == ALSAChannelMap[c])
{
count = c + 1;
break;
}
}
CAEChannelInfo info;
for (unsigned int i = 0; i < count; ++i)
info += ALSAChannelMap[i];
return info;
}
void CAESinkALSA::GetAESParams(AEAudioFormat format, std::string& params)
{
if (m_passthrough)
params = "AES0=0x06";
else
params = "AES0=0x04";
params += ",AES1=0x82,AES2=0x00";
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;
/* if we are raw, correct the data format */
if (AE_IS_RAW(format.m_dataFormat))
{
m_channelLayout = GetChannelLayout(format);
format.m_dataFormat = AE_FMT_S16NE;
m_passthrough = true;
}
else
{
m_channelLayout = GetChannelLayout(format);
m_passthrough = false;
}
if (m_channelLayout.Count() == 0)
{
CLog::Log(LOGERROR, "CAESinkALSA::Initialize - Unable to open the requested channel layout");
return false;
}
format.m_channelLayout = m_channelLayout;
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 \"%s\"", device.c_str());
/* get the sound config */
snd_config_t *config;
snd_config_copy(&config, snd_config);
snd_config_t *dmixRateConf;
long dmixRate;
if (snd_config_search(config, "defaults.pcm.dmix.rate", &dmixRateConf) < 0
|| snd_config_get_integer(dmixRateConf, &dmixRate) < 0)
dmixRate = 48000; /* assume default */
/* Prefer dmix for non-passthrough stereo when sample rate matches */
if (!OpenPCMDevice(device, AESParams, m_channelLayout.Count(), &m_pcm, config, format.m_sampleRate == (unsigned int) dmixRate && !m_passthrough))
{
CLog::Log(LOGERROR, "CAESinkALSA::Initialize - failed to initialize device \"%s\"", device.c_str());
snd_config_delete(config);
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 \"%s\"", device.c_str());
/* free the sound config */
snd_config_delete(config);
if (!InitializeHW(format) || !InitializeSW(format))
return false;
snd_pcm_nonblock(m_pcm, 1);
snd_pcm_prepare (m_pcm);
m_format = format;
m_formatSampleRateMul = 1.0 / (double)m_format.m_sampleRate;
return true;
}
bool CAESinkALSA::IsCompatible(const AEAudioFormat format, const std::string device)
{
return (
/* compare against the requested format and the real format */
(m_initFormat.m_sampleRate == format.m_sampleRate || m_format.m_sampleRate == format.m_sampleRate ) &&
(m_initFormat.m_dataFormat == format.m_dataFormat || m_format.m_dataFormat == format.m_dataFormat ) &&
(m_initFormat.m_channelLayout == format.m_channelLayout || m_format.m_channelLayout == format.m_channelLayout) &&
(m_initDevice == device)
);
}
snd_pcm_format_t CAESinkALSA::AEFormatToALSAFormat(const enum AEDataFormat format)
{
if (AE_IS_RAW(format))
return SND_PCM_FORMAT_S16;
switch (format)
{
case AE_FMT_S8 : return SND_PCM_FORMAT_S8;
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(AEAudioFormat &format)
{
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 = format.m_sampleRate;
unsigned int channelCount = format.m_channelLayout.Count();
snd_pcm_hw_params_set_rate_near (m_pcm, hw_params, &sampleRate, NULL);
snd_pcm_hw_params_set_channels_near(m_pcm, hw_params, &channelCount);
/* ensure we opened X channels or more */
if (format.m_channelLayout.Count() > channelCount)
{
CLog::Log(LOGINFO, "CAESinkALSA::InitializeHW - Unable to open the required number of channels");
}
/* update the channelLayout to what we managed to open */
format.m_channelLayout.Reset();
for (unsigned int i = 0; i < channelCount; ++i)
format.m_channelLayout += ALSAChannelMap[i];
snd_pcm_format_t fmt = AEFormatToALSAFormat(format.m_dataFormat);
if (fmt == SND_PCM_FORMAT_UNKNOWN)
{
/* if we dont support the requested format, fallback to float */
format.m_dataFormat = AE_FMT_FLOAT;
fmt = SND_PCM_FORMAT_FLOAT;
}
/* 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 decending order */
CLog::Log(LOGINFO, "CAESinkALSA::InitializeHW - Your hardware does not support %s, trying other formats", CAEUtil::DataFormatToStr(format.m_dataFormat));
for (enum AEDataFormat i = AE_FMT_MAX; i > AE_FMT_INVALID; i = (enum AEDataFormat)((int)i - 1))
{
if (AE_IS_RAW(i) || 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 || 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);
if (bits != fmtBits)
{
/* if we opened in 32bit and only have 24bits, pack into 24 */
if (fmtBits == 32 && bits == 24)
i = AE_FMT_S24NE4;
else
continue;
}
/* record that the format fell back to X */
format.m_dataFormat = i;
CLog::Log(LOGINFO, "CAESinkALSA::InitializeHW - Using data format %s", CAEUtil::DataFormatToStr(format.m_dataFormat));
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;
}
}
unsigned int periods;
snd_pcm_uframes_t periodSize, bufferSize;
snd_pcm_hw_params_get_buffer_size_max(hw_params, &bufferSize);
bufferSize = std::min(bufferSize, (snd_pcm_uframes_t)8192);
periodSize = bufferSize / ALSA_PERIODS;
periods = ALSA_PERIODS;
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Request: periodSize %lu, periods %u, bufferSize %lu", periodSize, periods, bufferSize);
/* work on a copy of the hw params */
snd_pcm_hw_params_t *hw_params_copy;
snd_pcm_hw_params_alloca(&hw_params_copy);
/* try to set the buffer size then the period size */
snd_pcm_hw_params_copy(hw_params_copy, hw_params);
snd_pcm_hw_params_set_buffer_size_near(m_pcm, hw_params_copy, &bufferSize);
snd_pcm_hw_params_set_period_size_near(m_pcm, hw_params_copy, &periodSize, NULL);
snd_pcm_hw_params_set_periods_near (m_pcm, hw_params_copy, &periods , NULL);
if (snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
/* try to set the period size then the buffer size */
snd_pcm_hw_params_copy(hw_params_copy, hw_params);
snd_pcm_hw_params_set_period_size_near(m_pcm, hw_params_copy, &periodSize, NULL);
snd_pcm_hw_params_set_buffer_size_near(m_pcm, hw_params_copy, &bufferSize);
snd_pcm_hw_params_set_periods_near (m_pcm, hw_params_copy, &periods , NULL);
if (snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
/* try to just set the buffer size */
snd_pcm_hw_params_copy(hw_params_copy, hw_params);
snd_pcm_hw_params_set_buffer_size_near(m_pcm, hw_params_copy, &bufferSize);
snd_pcm_hw_params_set_periods_near (m_pcm, hw_params_copy, &periods , NULL);
if (snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
/* try to just set the period size */
snd_pcm_hw_params_copy(hw_params_copy, hw_params);
snd_pcm_hw_params_set_period_size_near(m_pcm, hw_params_copy, &periodSize, NULL);
snd_pcm_hw_params_set_periods_near (m_pcm, hw_params_copy, &periods , NULL);
if (snd_pcm_hw_params(m_pcm, hw_params_copy) != 0)
{
CLog::Log(LOGERROR, "CAESinkALSA::InitializeHW - Failed to set the parameters");
return false;
}
}
}
}
snd_pcm_hw_params_get_period_size(hw_params_copy, &periodSize, NULL);
snd_pcm_hw_params_get_buffer_size(hw_params_copy, &bufferSize);
CLog::Log(LOGDEBUG, "CAESinkALSA::InitializeHW - Got: periodSize %lu, periods %u, bufferSize %lu", periodSize, periods, bufferSize);
/* set the format parameters */
format.m_sampleRate = sampleRate;
format.m_frames = periodSize;
format.m_frameSamples = periodSize * format.m_channelLayout.Count();
format.m_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 %d ms", m_timeout);
return true;
}
bool CAESinkALSA::InitializeSW(AEAudioFormat &format)
{
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, format.m_frames);
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()
{
Stop();
if (m_pcm)
{
snd_pcm_drop (m_pcm);
snd_pcm_close(m_pcm);
m_pcm = NULL;
}
}
void CAESinkALSA::Stop()
{
if (!m_pcm)
return;
snd_pcm_drop(m_pcm);
}
double CAESinkALSA::GetDelay()
{
if (!m_pcm)
return 0;
snd_pcm_sframes_t frames = 0;
snd_pcm_delay(m_pcm, &frames);
if (frames < 0)
{
#if SND_LIB_VERSION >= 0x000901 /* snd_pcm_forward() exists since 0.9.0rc8 */
snd_pcm_forward(m_pcm, -frames);
#endif
frames = 0;
}
return (double)frames * m_formatSampleRateMul;
}
double CAESinkALSA::GetCacheTime()
{
if (!m_pcm)
return 0.0;
int space = snd_pcm_avail_update(m_pcm);
if (space == 0)
{
snd_pcm_state_t state = snd_pcm_state(m_pcm);
if (state < 0)
{
HandleError("snd_pcm_state", state);
space = m_bufferSize;
}
if (state != SND_PCM_STATE_RUNNING && state != SND_PCM_STATE_PREPARED)
space = m_bufferSize;
}
return (double)(m_bufferSize - space) * m_formatSampleRateMul;
}
double CAESinkALSA::GetCacheTotal()
{
return (double)m_bufferSize * m_formatSampleRateMul;
}
unsigned int CAESinkALSA::AddPackets(uint8_t *data, unsigned int frames, bool hasAudio)
{
if (!m_pcm)
return 0;
if (snd_pcm_state(m_pcm) == SND_PCM_STATE_PREPARED)
snd_pcm_start(m_pcm);
int ret;
ret = snd_pcm_avail(m_pcm);
if (ret < 0)
{
HandleError("snd_pcm_avail", ret);
ret = 0;
}
if ((unsigned int)ret < frames);
{
ret = snd_pcm_wait(m_pcm, m_timeout);
if (ret < 0)
HandleError("snd_pcm_wait", ret);
}
ret = snd_pcm_writei(m_pcm, (void*)data, frames);
if (ret < 0)
{
HandleError("snd_pcm_writei(1)", ret);
ret = snd_pcm_writei(m_pcm, (void*)data, frames);
if (ret < 0)
{
HandleError("snd_pcm_writei(2)", ret);
ret = 0;
}
}
return ret;
}
void CAESinkALSA::HandleError(const char* name, int err)
{
switch(err)
{
case -EPIPE:
CLog::Log(LOGERROR, "CAESinkALSA::HandleError(%s) - underrun", name);
if ((err = snd_pcm_prepare(m_pcm)) < 0)
CLog::Log(LOGERROR, "CAESinkALSA::HandleError(%s) - snd_pcm_prepare returned %d (%s)", name, err, snd_strerror(err));
break;
case -ESTRPIPE:
CLog::Log(LOGINFO, "CAESinkALSA::HandleError(%s) - Resuming after suspend", name);
/* try to resume the stream */
while((err = snd_pcm_resume(m_pcm)) == -EAGAIN)
Sleep(1);
/* if the hardware doesnt support resume, prepare the stream */
if (err == -ENOSYS)
if ((err = snd_pcm_prepare(m_pcm)) < 0)
CLog::Log(LOGERROR, "CAESinkALSA::HandleError(%s) - snd_pcm_prepare returned %d (%s)", name, err, snd_strerror(err));
break;
default:
CLog::Log(LOGERROR, "CAESinkALSA::HandleError(%s) - snd_pcm_writei returned %d (%s)", name, err, snd_strerror(err));
break;
}
}
void CAESinkALSA::Drain()
{
if (!m_pcm)
return;
snd_pcm_nonblock(m_pcm, 0);
snd_pcm_drain(m_pcm);
snd_pcm_nonblock(m_pcm, 1);
}
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) ? ':' : ',';
device += params;
}
bool CAESinkALSA::TryDevice(const std::string &name, snd_pcm_t **pcmp, snd_config_t *lconf)
{
/* Check if this device was already open (e.g. when checking for supported
* channel count in EnumerateDevice()) */
if (*pcmp)
{
if (name == snd_pcm_name(*pcmp))
return true;
snd_pcm_close(*pcmp);
*pcmp = NULL;
}
int err = snd_pcm_open_lconf(pcmp, name.c_str(), SND_PCM_STREAM_PLAYBACK, ALSA_OPTIONS, lconf);
if (err < 0)
{
CLog::Log(LOGINFO, "CAESinkALSA - Unable to open device \"%s\" for playback", name.c_str());
}
return err == 0;
}
bool CAESinkALSA::TryDeviceWithParams(const std::string &name, const std::string ¶ms, snd_pcm_t **pcmp, snd_config_t *lconf)
{
if (!params.empty())
{
std::string nameWithParams = name;
AppendParams(nameWithParams, params);
if (TryDevice(nameWithParams, pcmp, lconf))
return true;
}
/* Try the variant without extra parameters.
* Custom devices often do not take the AESx parameters, for example.
*/
return TryDevice(name, pcmp, lconf);
}
bool CAESinkALSA::OpenPCMDevice(const std::string &name, const std::string ¶ms, int channels, snd_pcm_t **pcmp, snd_config_t *lconf, bool preferDmixStereo)
{
/* Special name denoting surroundXX mangling. This is needed for some
* devices for multichannel to work. */
if (name == "@" || name.substr(0, 2) == "@:")
{
std::string openName = name.substr(1);
/* These device names allow alsa-lib to perform special routing if needed
* for multichannel to work with the audio hardware.
* Fall through in switch() so that devices with more channels are
* added as fallback. */
switch (channels)
{
case 3:
case 4:
if (TryDeviceWithParams("surround40" + openName, params, pcmp, lconf))
return true;
case 5:
case 6:
if (TryDeviceWithParams("surround51" + openName, params, pcmp, lconf))
return true;
case 7:
case 8:
if (TryDeviceWithParams("surround71" + openName, params, pcmp, lconf))
return true;
}
/* If preferDmix is false, try non-dmix configuration first.
* This allows output with non-48000 sample rate if device is free */
if (!preferDmixStereo && TryDeviceWithParams("front" + openName, params, pcmp, lconf))
return true;
/* Try "sysdefault" and "default" (they provide dmix),
* unless the selected devices is not DEV=0 of the card, in which case
* "sysdefault" and "default" would point to another device.
* "sysdefault" is a newish device name that won't be overwritten in case
* system configuration redefines "default". "default" is still tried
* because "sysdefault" is rather new. */
size_t devPos = openName.find(",DEV=");
if (devPos == std::string::npos || (devPos + 5 < openName.size() && openName[devPos+5] == '0'))
{
/* "sysdefault" and "default" do not have "DEV=0", drop it */
std::string nameWithoutDev = openName;
if (devPos != std::string::npos)
nameWithoutDev.erase(nameWithoutDev.begin() + devPos, nameWithoutDev.begin() + devPos + 6);
if (TryDeviceWithParams("sysdefault" + nameWithoutDev, params, pcmp, lconf)
|| TryDeviceWithParams("default" + nameWithoutDev, params, pcmp, lconf))
return true;
}
/* Try non-dmix "front" */
if (preferDmixStereo && TryDeviceWithParams("front" + openName, params, pcmp, lconf))
return true;
}
else
{
/* Non-surroundXX device, just add it */
if (TryDeviceWithParams(name, params, pcmp, lconf))
return true;
}
return false;
}
void CAESinkALSA::EnumerateDevicesEx(AEDeviceInfoList &list)
{
/* ensure that ALSA has been initialized */
snd_lib_error_set_handler(sndLibErrorHandler);
if(!snd_config)
snd_config_update();
snd_config_t *config;
snd_config_copy(&config, snd_config);
/* Always enumerate the default device.
* Note: If "default" is a stereo device, EnumerateDevice()
* will automatically add "@" instead to enable surroundXX mangling.
* We don't want to do that if "default" can handle multichannel
* itself (e.g. in case of a pulseaudio server). */
EnumerateDevice(list, "default", "", config);
void **hints;
if (snd_device_name_hint(-1, "pcm", &hints) < 0)
{
CLog::Log(LOGINFO, "CAESinkALSA - Unable to get a list of devices");
return;
}
std::string defaultDescription;
for (void** hint = hints; *hint != NULL; ++hint)
{
char *io = snd_device_name_get_hint(*hint, "IOID");
char *name = snd_device_name_get_hint(*hint, "NAME");
char *desc = snd_device_name_get_hint(*hint, "DESC");
if ((!io || strcmp(io, "Output") == 0) && name
&& strcmp(name, "null") != 0)
{
std::string baseName = std::string(name);
baseName = baseName.substr(0, baseName.find(':'));
if (strcmp(name, "default") == 0)
{
/* added already, but lets get the description if we have one */
if (desc)
defaultDescription = desc;
}
else if (baseName == "front")
{
/* Enumerate using the surroundXX mangling */
/* do not enumerate basic "front", it is already handled
* by the default "@" entry added in the very beginning */
if (strcmp(name, "front") != 0)
EnumerateDevice(list, std::string("@") + (name+5), desc ? desc : name, config);
}
/* Do not enumerate "default", it is already enumerated above. */
/* Do not enumerate the sysdefault or surroundXX devices, those are
* always accompanied with a "front" device and it is handled above
* as "@". The below devices will be automatically used if available
* for a "@" device. */
/* Ubuntu has patched their alsa-lib so that "defaults.namehint.extended"
* defaults to "on" instead of upstream "off", causing lots of unwanted
* extra devices (many of which are not actually routed properly) to be
* found by the enumeration process. Skip them as well ("hw", "dmix",
* "plughw", "dsnoop"). */
else if (baseName != "default"
&& baseName != "sysdefault"
&& baseName != "surround40"
&& baseName != "surround41"
&& baseName != "surround50"
&& baseName != "surround51"
&& baseName != "surround71"
&& baseName != "hw"
&& baseName != "dmix"
&& baseName != "plughw"
&& baseName != "dsnoop")
{
EnumerateDevice(list, name, desc ? desc : name, config);
}
}
free(io);
free(name);
free(desc);
}
snd_device_name_free_hint(hints);
/* set the displayname for default device */
if (!list.empty() && list[0].m_deviceName == "default")
{
/* If we have one from a hint (DESC), use it */
if (!defaultDescription.empty())
list[0].m_displayName = defaultDescription;
/* Otherwise use the discovered name or (unlikely) "Default" */
else if (list[0].m_displayName.empty())
list[0].m_displayName = "Default";
}
/* lets check uniqueness, we may need to append DEV or CARD to DisplayName */
/* If even a single device of card/dev X clashes with Y, add suffixes to
* all devices of both them, for clarity. */
/* clashing card names, e.g. "NVidia", "NVidia_2" */
std::set<std::string> cardsToAppend;
/* clashing basename + cardname combinations, e.g. ("hdmi","Nvidia") */
std::set<std::pair<std::string, std::string> > devsToAppend;
for (AEDeviceInfoList::iterator it1 = list.begin(); it1 != list.end(); ++it1)
{
for (AEDeviceInfoList::iterator it2 = it1+1; it2 != list.end(); ++it2)
{
if (it1->m_displayName == it2->m_displayName
&& it1->m_displayNameExtra == it2->m_displayNameExtra)
{
/* something needs to be done */
std::string cardString1 = GetParamFromName(it1->m_deviceName, "CARD");
std::string cardString2 = GetParamFromName(it2->m_deviceName, "CARD");
if (cardString1 != cardString2)
{
/* card name differs, add identifiers to all devices */
cardsToAppend.insert(cardString1);
cardsToAppend.insert(cardString2);
continue;
}
std::string devString1 = GetParamFromName(it1->m_deviceName, "DEV");
std::string devString2 = GetParamFromName(it2->m_deviceName, "DEV");
if (devString1 != devString2)
{
/* device number differs, add identifiers to all such devices */
devsToAppend.insert(std::make_pair(it1->m_deviceName.substr(0, it1->m_deviceName.find(':')), cardString1));
devsToAppend.insert(std::make_pair(it2->m_deviceName.substr(0, it2->m_deviceName.find(':')), cardString2));
continue;
}
/* if we got here, the configuration is really weird, just append the whole device string */
it1->m_displayName += " (" + it1->m_deviceName + ")";
it2->m_displayName += " (" + it2->m_deviceName + ")";
}
}
}
for (std::set<std::string>::iterator it = cardsToAppend.begin();
it != cardsToAppend.end(); ++it)
{
for (AEDeviceInfoList::iterator itl = list.begin(); itl != list.end(); ++itl)
{
std::string cardString = GetParamFromName(itl->m_deviceName, "CARD");
if (cardString == *it)
/* "HDA NVidia (NVidia)", "HDA NVidia (NVidia_2)", ... */
itl->m_displayName += " (" + cardString + ")";
}
}
for (std::set<std::pair<std::string, std::string> >::iterator it = devsToAppend.begin();
it != devsToAppend.end(); ++it)
{
for (AEDeviceInfoList::iterator itl = list.begin(); itl != list.end(); ++itl)
{
std::string baseName = itl->m_deviceName.substr(0, itl->m_deviceName.find(':'));
std::string cardString = GetParamFromName(itl->m_deviceName, "CARD");
if (baseName == it->first && cardString == it->second)
{
std::string devString = GetParamFromName(itl->m_deviceName, "DEV");
/* "HDMI #0", "HDMI #1" ... */
itl->m_displayNameExtra += " #" + devString;
}
}
}
}
AEDeviceType CAESinkALSA::AEDeviceTypeFromName(const std::string &name)
{
if (name.substr(0, 4) == "hdmi")
return AE_DEVTYPE_HDMI;
else if (name.substr(0, 6) == "iec958" || name.substr(0, 5) == "spdif")
return AE_DEVTYPE_IEC958;
return AE_DEVTYPE_PCM;
}
std::string CAESinkALSA::GetParamFromName(const std::string &name, const std::string ¶m)
{
/* name = "hdmi:CARD=x,DEV=y" param = "CARD" => return "x" */
size_t parPos = name.find(param + '=');
if (parPos != std::string::npos)
{
parPos += param.size() + 1;
return name.substr(parPos, name.find_first_of(",'\"", parPos)-parPos);
}
return "";
}
void CAESinkALSA::EnumerateDevice(AEDeviceInfoList &list, const std::string &device, const std::string &description, snd_config_t *config)
{
snd_pcm_t *pcmhandle = NULL;
if (!OpenPCMDevice(device, "", ALSA_MAX_CHANNELS, &pcmhandle, config, false))
return;
snd_pcm_info_t *pcminfo;
snd_pcm_info_alloca(&pcminfo);
memset(pcminfo, 0, snd_pcm_info_sizeof());
int err = snd_pcm_info(pcmhandle, pcminfo);
if (err < 0)
{
CLog::Log(LOGINFO, "CAESinkALSA - Unable to get pcm_info for \"%s\"", device.c_str());
snd_pcm_close(pcmhandle);
}
int cardNr = snd_pcm_info_get_card(pcminfo);
CAEDeviceInfo info;
info.m_deviceName = device;
info.m_deviceType = AEDeviceTypeFromName(device);
if (cardNr >= 0)
{
/* "HDA NVidia", "HDA Intel", "HDA ATI HDMI", "SB Live! 24-bit External", ... */
char *cardName;
if (snd_card_get_name(cardNr, &cardName) == 0)
info.m_displayName = cardName;
if (info.m_deviceType == AE_DEVTYPE_HDMI && info.m_displayName.size() > 5 &&
info.m_displayName.substr(info.m_displayName.size()-5) == " HDMI")
{
/* We already know this is HDMI, strip it */
info.m_displayName.erase(info.m_displayName.size()-5);
}
/* "CONEXANT Analog", "USB Audio", "HDMI 0", "ALC889 Digital" ... */
std::string pcminfoName = snd_pcm_info_get_name(pcminfo);
/*
* Filter "USB Audio", in those cases snd_card_get_name() is more
* meaningful already
*/
if (pcminfoName != "USB Audio")
info.m_displayNameExtra = pcminfoName;
if (info.m_deviceType == AE_DEVTYPE_HDMI)
{
/* replace, this was likely "HDMI 0" */
info.m_displayNameExtra = "HDMI";
int dev = snd_pcm_info_get_device(pcminfo);
if (dev >= 0)
{
/* lets see if we can get ELD info */
snd_ctl_t *ctlhandle;
std::stringstream sstr;
sstr << "hw:" << cardNr;
std::string strHwName = sstr.str();
if (snd_ctl_open_lconf(&ctlhandle, strHwName.c_str(), 0, config) == 0)
{
snd_hctl_t *hctl;
if (snd_hctl_open_ctl(&hctl, ctlhandle) == 0)
{
snd_hctl_load(hctl);
bool badHDMI = false;
if (!GetELD(hctl, dev, info, badHDMI))
CLog::Log(LOGDEBUG, "CAESinkALSA - Unable to obtain ELD information for device \"%s\" (not supported by device, or kernel older than 3.2)",
device.c_str());
/* snd_hctl_close also closes ctlhandle */
snd_hctl_close(hctl);
if (badHDMI)
{
/* only trust badHDMI (= unconnected or non-existent port) on Intel
* and NVIDIA where it has been confirmed to work, show the empty
* port on other systems */
if (info.m_displayName.compare(0, 9, "HDA Intel") == 0 || info.m_displayName.compare(0, 10, "HDA NVidia") == 0)
{
/* unconnected HDMI port */
CLog::Log(LOGDEBUG, "CAESinkALSA - Skipping HDMI device \"%s\" as it has no ELD data", device.c_str());
snd_pcm_close(pcmhandle);
return;
}
else
{
CLog::Log(LOGDEBUG, "CAESinkALSA - HDMI device \"%s\" may be unconnected (no ELD data)", device.c_str());
}
}
}
else
{
snd_ctl_close(ctlhandle);
}
}
}
}
else if (info.m_deviceType == AE_DEVTYPE_IEC958)
{
/* append instead of replace, pcminfoName is useful for S/PDIF */
if (!info.m_displayNameExtra.empty())
info.m_displayNameExtra += ' ';
info.m_displayNameExtra += "S/PDIF";
}
else if (info.m_displayNameExtra.empty())
{
/* for USB audio, it gets a bit confusing as there is
* - "SB Live! 24-bit External"
* - "SB Live! 24-bit External, S/PDIF"
* so add "Analog" qualifier to the first one */
info.m_displayNameExtra = "Analog";
}
/* "default" is a device that will be used for all inputs, while
* "@" will be mangled to front/default/surroundXX as necessary */
if (device == "@" || device == "default")
{
/* Make it "Default (whatever)" */
info.m_displayName = "Default (" + info.m_displayName + (info.m_displayNameExtra.empty() ? "" : " " + info.m_displayNameExtra + ")");
info.m_displayNameExtra = "";
}
}
else
{
/* virtual devices: "default", "pulse", ... */
/* description can be e.g. "PulseAudio Sound Server" - for hw devices it is
* normally uninteresting, like "HDMI Audio Output" or "Default Audio Device",
* so we only use it for virtual devices that have no better display name */