forked from MythTV/mythtv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audiooutputca.cpp
1797 lines (1602 loc) · 54 KB
/
audiooutputca.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
/*****************************************************************************
* = NAME
* audiooutputca.cpp
*
* = DESCRIPTION
* Core Audio glue for Mac OS X.
*
* = REVISION
* $Id$
*
* = AUTHORS
* Jeremiah Morris, Andrew Kimpton, Nigel Pearson, Jean-Yves Avenard
*****************************************************************************/
#include <array>
#include <vector>
#include <CoreServices/CoreServices.h>
#include <CoreAudio/CoreAudio.h>
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioFormat.h>
#include "mythcorecontext.h"
#include "audiooutputca.h"
#include "config.h"
#include "SoundTouch.h"
#define LOC QString("CoreAudio: ")
#define CHANNELS_MIN 1
#define CHANNELS_MAX 8
using AudioStreamIDVec = std::vector<AudioStreamID>;
using AudioStreamRangedVec = std::vector<AudioStreamRangedDescription>;
using AudioValueRangeVec = std::vector<AudioValueRange>;
using RatesVec = std::vector<int>;
using ChannelsArr = std::array<bool,CHANNELS_MAX>;
#define OSS_STATUS(x) UInt32ToFourCC((UInt32*)&(x))
char* UInt32ToFourCC(const UInt32* pVal)
{
UInt32 inVal = *pVal;
char* pIn = (char*)&inVal;
static char fourCC[5];
fourCC[4] = 0;
fourCC[3] = pIn[0];
fourCC[2] = pIn[1];
fourCC[1] = pIn[2];
fourCC[0] = pIn[3];
return fourCC;
}
QString StreamDescriptionToString(AudioStreamBasicDescription desc)
{
UInt32 formatId = desc.mFormatID;
char* fourCC = UInt32ToFourCC(&formatId);
QString str;
switch (desc.mFormatID)
{
case kAudioFormatLinearPCM:
str = QString("[%1] %2%3 Channel %4-bit %5 %6 (%7Hz)")
.arg(fourCC)
.arg((desc.mFormatFlags & kAudioFormatFlagIsNonMixable) ? "" : "Mixable ")
.arg(desc.mChannelsPerFrame)
.arg(desc.mBitsPerChannel)
.arg((desc.mFormatFlags & kAudioFormatFlagIsFloat) ? "Floating Point" : "Signed Integer")
.arg((desc.mFormatFlags & kAudioFormatFlagIsBigEndian) ? "BE" : "LE")
.arg((UInt32)desc.mSampleRate);
break;
case kAudioFormatAC3:
str = QString("[%1] AC-3/DTS (%2Hz)")
.arg(fourCC)
.arg((UInt32)desc.mSampleRate);
break;
case kAudioFormat60958AC3:
str = QString("[%1] AC-3/DTS for S/PDIF %2 (%3Hz)")
.arg(fourCC)
.arg((desc.mFormatFlags & kAudioFormatFlagIsBigEndian) ? "BE" : "LE")
.arg((UInt32)desc.mSampleRate);
break;
default:
str = QString("[%1]").arg(fourCC);
break;
}
return str;
}
/** \class CoreAudioData
* \brief This holds Core Audio member variables and low-level audio IO methods
* The name is now a misnomer, it should be CoreAudioPrivate, or CoreAudioMgr
*/
class CoreAudioData {
public:
explicit CoreAudioData(AudioOutputCA *parent);
CoreAudioData(AudioOutputCA *parent, AudioDeviceID deviceID);
CoreAudioData(AudioOutputCA *parent, QString deviceName);
static AudioDeviceID GetDefaultOutputDevice();
int GetTotalOutputChannels();
QString *GetName();
static AudioDeviceID GetDeviceWithName(const QString& deviceName);
bool OpenDevice();
int OpenAnalog();
void CloseAnalog();
bool OpenSPDIF ();
void CloseSPDIF();
static void SetAutoHogMode(bool enable);
static bool GetAutoHogMode();
static pid_t GetHogStatus();
bool SetHogStatus(bool hog);
bool SetMixingSupport(bool mix);
bool GetMixingSupport();
bool FindAC3Stream();
static void ResetAudioDevices();
static void ResetStream(AudioStreamID s);
static RatesVec RatesList(AudioDeviceID d);
bool ChannelsList(AudioDeviceID d, bool passthru, ChannelsArr& chans);
static AudioStreamIDVec StreamsList(AudioDeviceID d);
static AudioStreamRangedVec FormatsList(AudioStreamID s);
static int AudioStreamChangeFormat(AudioStreamID s,
AudioStreamBasicDescription format);
// TODO: Convert these to macros!
static void Debug(const QString& msg)
{ LOG(VB_AUDIO, LOG_INFO, "CoreAudioData::" + msg); }
static void Error(const QString& msg)
{ LOG(VB_GENERAL, LOG_ERR, "CoreAudioData Error:" + msg); }
static void Warn (const QString& msg)
{ LOG(VB_GENERAL, LOG_WARNING, "CoreAudioData Warning:" + msg); }
AudioOutputCA *mCA {nullptr}; // We could subclass, but this ends up tidier
// Analog output specific
AudioUnit mOutputUnit {nullptr};
// SPDIF mode specific
bool mDigitalInUse {false}; // Is the digital (SPDIF) output in use?
pid_t mHog {-1};
int mMixerRestore {-1};
AudioDeviceID mDeviceID {0};
AudioStreamID mStreamID {}; // StreamID that has a cac3 streamformat
int mStreamIndex {-1}; // Index of mStreamID in an AudioBufferList
UInt32 mBytesPerPacket {UINT32_MAX};
AudioStreamBasicDescription mFormatOrig {}; // The original format the stream
AudioStreamBasicDescription mFormatNew {}; // The format we changed the stream to
bool mRevertFormat {false}; // Do we need to revert the stream format?
bool mIoProc {false};
bool mInitialized {false};
bool mStarted {false};
bool mWasDigital {false};
AudioDeviceIOProcID mIoProcID {};
};
// These callbacks communicate with Core Audio.
static OSStatus RenderCallbackAnalog(void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData);
static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
const AudioTimeStamp *inNow,
const void *inInputData,
const AudioTimeStamp *inInputTime,
AudioBufferList *outOutputData,
const AudioTimeStamp *inOutputTime,
void *inRefCon);
/** \class AudioOutputCA
* \brief Implements Core Audio (Mac OS X Hardware Abstraction Layer) output.
*/
AudioOutputCA::AudioOutputCA(const AudioSettings &settings) :
AudioOutputBase(settings)
{
m_mainDevice.remove(0, 10);
VBAUDIO(QString("AudioOutputCA::AudioOutputCA searching %1").arg(m_mainDevice));
d = new CoreAudioData(this, m_mainDevice);
InitSettings(settings);
if (settings.m_init)
Reconfigure(settings);
}
AudioOutputCA::~AudioOutputCA()
{
KillAudio();
delete d;
}
AudioOutputSettings* AudioOutputCA::GetOutputSettings(bool digital)
{
auto *settings = new AudioOutputSettings();
// Seek hardware sample rate available
RatesVec rates = CoreAudioData::RatesList(d->mDeviceID);
if (rates.empty())
{
// Error retrieving rates, assume 48kHz
settings->AddSupportedRate(48000);
}
else
{
while (int rate = settings->GetNextRate())
{
for (auto entry : rates)
{
if (entry != rate)
continue;
settings->AddSupportedRate(entry);
}
}
}
// Supported format: 16 bits audio or float
settings->AddSupportedFormat(FORMAT_S16);
settings->AddSupportedFormat(FORMAT_FLT);
ChannelsArr channels {};
if (!d->ChannelsList(d->mDeviceID, digital, channels))
{
// Error retrieving list of supported channels, assume stereo only
settings->AddSupportedChannels(2);
}
else
{
for (int i = CHANNELS_MIN; i <= CHANNELS_MAX; i++)
{
if (channels[i])
{
Debug(QString("Support %1 channels").arg(i));
// In case 8 channels are supported but not 6, fake 6
if (i == 8 && !channels[6])
settings->AddSupportedChannels(6);
settings->AddSupportedChannels(i);
}
}
}
if (d->FindAC3Stream())
{
settings->setPassthrough(1); // yes passthrough
}
return settings;
}
bool AudioOutputCA::OpenDevice()
{
bool deviceOpened = false;
if (d->mWasDigital)
{
}
Debug("OpenDevice: Entering");
if (m_passthru || m_enc)
{
Debug("OpenDevice() Trying Digital.");
if (!(deviceOpened = d->OpenSPDIF()))
d->CloseSPDIF();
}
if (!deviceOpened)
{
Debug("OpenDevice() Trying Analog.");
int result = -1;
//for (int i=0; result < 0 && i < 10; i++)
{
result = d->OpenAnalog();
Debug(QString("OpenDevice: OpenAnalog = %1").arg(result));
if (result < 0)
{
d->CloseAnalog();
usleep(1s - 1us); // Argument to usleep must be less than 1 second
}
}
deviceOpened = (result > 0);
}
if (!deviceOpened)
{
Error("Couldn't open any audio device!");
d->CloseAnalog();
return false;
}
if (m_internalVol && m_setInitialVol)
{
QString controlLabel = gCoreContext->GetSetting("MixerControl", "PCM");
controlLabel += "MixerVolume";
SetCurrentVolume(gCoreContext->GetNumSetting(controlLabel, 80));
}
return true;
}
void AudioOutputCA::CloseDevice()
{
VBAUDIO(QString("CloseDevice [%1]: Entering")
.arg(d->mDigitalInUse ? "SPDIF" : "Analog"));
if (d->mDigitalInUse)
d->CloseSPDIF();
else
d->CloseAnalog();
}
template <class AudioDataType>
static inline void _ReorderSmpteToCA(AudioDataType *buf, uint frames)
{
AudioDataType tmpLS;
AudioDataType tmpRS;
AudioDataType tmpRLs;
AudioDataType tmpRRs;
AudioDataType *buf2;
for (uint i = 0; i < frames; i++)
{
buf = buf2 = buf + 4;
tmpRLs = *buf++;
tmpRRs = *buf++;
tmpLS = *buf++;
tmpRS = *buf++;
*buf2++ = tmpLS;
*buf2++ = tmpRS;
*buf2++ = tmpRLs;
*buf2++ = tmpRRs;
}
}
static inline void ReorderSmpteToCA(void *buf, uint frames, AudioFormat format)
{
switch(AudioOutputSettings::FormatToBits(format))
{
case 8: _ReorderSmpteToCA((uchar *)buf, frames); break;
case 16: _ReorderSmpteToCA((short *)buf, frames); break;
default: _ReorderSmpteToCA((int *)buf, frames); break;
}
}
/** Object-oriented part of callback */
bool AudioOutputCA::RenderAudio(unsigned char *aubuf,
int size, unsigned long long timestamp)
{
if (m_pauseAudio || m_killAudio)
{
m_actuallyPaused = true;
return false;
}
/* This callback is called when the sound system requests
data. We don't want to block here, because that would
just cause dropouts anyway, so we always return whatever
data is available. If we haven't received enough, either
because we've finished playing or we have a buffer
underrun, we play silence to fill the unused space. */
int written_size = GetAudioData(aubuf, size, false);
if (written_size && (size > written_size))
{
// play silence on buffer underrun
memset(aubuf + written_size, 0, size - written_size);
}
//Audio received is in SMPTE channel order, reorder to CA unless passthru
if (!m_passthru && m_channels == 8)
{
ReorderSmpteToCA(aubuf, size / m_outputBytesPerFrame, m_outputFormat);
}
/* update audiotime (m_bufferedBytes is read by GetBufferedOnSoundcard) */
UInt64 nanos = AudioConvertHostTimeToNanos(timestamp -
AudioGetCurrentHostTime());
m_bufferedBytes = (int)((nanos / 1000000000.0) * // secs
(m_effDsp / 100.0) * // frames/sec
m_outputBytesPerFrame); // bytes/frame
return (written_size > 0);
}
// unneeded and unused in CA
void AudioOutputCA::WriteAudio(unsigned char *aubuf, int size)
{
(void)aubuf;
(void)size;
}
int AudioOutputCA::GetBufferedOnSoundcard(void) const
{
return m_bufferedBytes;
}
/** Reimplement the base class's version of GetAudiotime()
* so that we don't use gettimeofday or Qt mutexes.
*/
std::chrono::milliseconds AudioOutputCA::GetAudiotime(void)
{
std::chrono::milliseconds audbuf_timecode = GetBaseAudBufTimeCode();
if (audbuf_timecode == 0ms)
return 0ms;
int totalbuffer = audioready() + GetBufferedOnSoundcard();
return audbuf_timecode - millisecondsFromFloat(totalbuffer * 100000.0 /
(m_outputBytesPerFrame *
m_effDsp * m_stretchFactor));
}
/* This callback provides converted audio data to the default output device. */
OSStatus RenderCallbackAnalog(void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData)
{
(void)inBusNumber;
(void)inNumberFrames;
AudioOutputCA *inst = (static_cast<CoreAudioData *>(inRefCon))->mCA;
if (!inst->RenderAudio((unsigned char *)(ioData->mBuffers[0].mData),
ioData->mBuffers[0].mDataByteSize,
inTimeStamp->mHostTime))
{
// play silence if RenderAudio returns false
memset(ioData->mBuffers[0].mData, 0, ioData->mBuffers[0].mDataByteSize);
*ioActionFlags = kAudioUnitRenderAction_OutputIsSilence;
}
return noErr;
}
int AudioOutputCA::GetVolumeChannel(int channel) const
{
// FIXME: this only returns global volume
(void)channel;
Float32 volume;
if (!AudioUnitGetParameter(d->mOutputUnit,
kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, &volume))
return (int)lroundf(volume * 100.0F);
return 0; // error case
}
void AudioOutputCA::SetVolumeChannel(int channel, int volume)
{
// FIXME: this only sets global volume
(void)channel;
AudioUnitSetParameter(d->mOutputUnit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, (volume * 0.01F), 0);
}
// IOProc style callback for SPDIF audio output
static OSStatus RenderCallbackSPDIF(AudioDeviceID inDevice,
const AudioTimeStamp *inNow,
const void *inInputData,
const AudioTimeStamp *inInputTime,
AudioBufferList *outOutputData,
const AudioTimeStamp *inOutputTime,
void *inRefCon)
{
auto *d = static_cast<CoreAudioData *>(inRefCon);
AudioOutputCA *a = d->mCA;
int index = d->mStreamIndex;
(void)inDevice; // unused
(void)inNow; // unused
(void)inInputData; // unused
(void)inInputTime; // unused
/*
* HACK: No idea why this would be the case, but after the second run, we get
* incorrect value
*/
if (d->mBytesPerPacket > 0 &&
outOutputData->mBuffers[index].mDataByteSize > d->mBytesPerPacket)
{
outOutputData->mBuffers[index].mDataByteSize = d->mBytesPerPacket;
}
if (!a->RenderAudio((unsigned char *)(outOutputData->mBuffers[index].mData),
outOutputData->mBuffers[index].mDataByteSize,
inOutputTime->mHostTime))
{
// play silence if RenderAudio returns false
memset(outOutputData->mBuffers[index].mData, 0,
outOutputData->mBuffers[index].mDataByteSize);
}
return noErr;
}
CoreAudioData::CoreAudioData(AudioOutputCA *parent) : mCA(parent)
{
// Reset all the devices to a default 'non-hog' and mixable format.
// If we don't do this we may be unable to find the Default Output device.
// (e.g. if we crashed last time leaving it stuck in AC-3 mode)
ResetAudioDevices();
mDeviceID = GetDefaultOutputDevice();
}
CoreAudioData::CoreAudioData(AudioOutputCA *parent, AudioDeviceID deviceID) :
mCA(parent)
{
ResetAudioDevices();
mDeviceID = deviceID;
}
CoreAudioData::CoreAudioData(AudioOutputCA *parent, QString deviceName) :
mCA(parent)
{
ResetAudioDevices();
mDeviceID = GetDeviceWithName(deviceName);
if (!mDeviceID)
{
// Didn't find specified device, use default one
mDeviceID = GetDefaultOutputDevice();
if (deviceName != "Default Output Device")
{
Warn(QString("CoreAudioData: \"%1\" not found, using default device %2.")
.arg(deviceName).arg(mDeviceID));
}
}
Debug(QString("CoreAudioData: device number is %1")
.arg(mDeviceID));
}
AudioDeviceID CoreAudioData::GetDeviceWithName(const QString &deviceName)
{
UInt32 size = 0;
AudioDeviceID deviceID = 0;
AudioObjectPropertyAddress pa
{
kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &pa,
0, nullptr, &size);
if (err)
{
Warn(QString("GetPropertyDataSize: Unable to retrieve the property sizes. "
"Error [%1]")
.arg(err));
return deviceID;
}
UInt32 deviceCount = size / sizeof(AudioDeviceID);
auto* pDevices = new AudioDeviceID[deviceCount];
err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa,
0, nullptr, &size, pDevices);
if (err)
{
Warn(QString("GetDeviceWithName: Unable to retrieve the list of available devices. "
"Error [%1]")
.arg(err));
}
else
{
for (UInt32 dev = 0; dev < deviceCount; dev++)
{
CoreAudioData device(nullptr, pDevices[dev]);
if (device.GetTotalOutputChannels() == 0)
continue;
QString *name = device.GetName();
if (name && *name == deviceName)
{
Debug(QString("GetDeviceWithName: Found: %1").arg(*name));
deviceID = pDevices[dev];
delete name;
}
if (deviceID)
break;
}
}
delete[] pDevices;
return deviceID;
}
AudioDeviceID CoreAudioData::GetDefaultOutputDevice()
{
UInt32 paramSize;
AudioDeviceID deviceId = 0;
AudioObjectPropertyAddress pa
{
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// Find the ID of the default Device
paramSize = sizeof(deviceId);
OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa,
0, nullptr, ¶mSize, &deviceId);
if (err == noErr)
Debug(QString("GetDefaultOutputDevice: default device ID = %1").arg(deviceId));
else
{
Warn(QString("GetDefaultOutputDevice: could not get default audio device: [%1]")
.arg(OSS_STATUS(err)));
deviceId = 0;
}
return deviceId;
}
int CoreAudioData::GetTotalOutputChannels()
{
if (!mDeviceID)
return 0;
UInt32 channels = 0;
UInt32 size = 0;
AudioObjectPropertyAddress pa
{
kAudioDevicePropertyStreamConfiguration,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectGetPropertyDataSize(mDeviceID, &pa,
0, nullptr, &size);
if (err)
{
Warn(QString("GetTotalOutputChannels: Unable to get "
"size of device output channels - id: %1 Error = [%2]")
.arg(mDeviceID)
.arg(err));
return 0;
}
auto *pList = (AudioBufferList *)malloc(size);
err = AudioObjectGetPropertyData(mDeviceID, &pa,
0, nullptr, &size, pList);
if (!err)
{
for (UInt32 buffer = 0; buffer < pList->mNumberBuffers; buffer++)
channels += pList->mBuffers[buffer].mNumberChannels;
}
else
{
Warn(QString("GetTotalOutputChannels: Unable to get "
"total device output channels - id: %1 Error = [%2]")
.arg(mDeviceID)
.arg(err));
}
Debug(QString("GetTotalOutputChannels: Found %1 channels in %2 buffers")
.arg(channels).arg(pList->mNumberBuffers));
free(pList);
return channels;
}
QString *CoreAudioData::GetName()
{
if (!mDeviceID)
return nullptr;
AudioObjectPropertyAddress pa
{
kAudioObjectPropertyName,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
CFStringRef name;
UInt32 propertySize = sizeof(CFStringRef);
OSStatus err = AudioObjectGetPropertyData(mDeviceID, &pa,
0, nullptr, &propertySize, &name);
if (err)
{
Error(QString("AudioObjectGetPropertyData for kAudioObjectPropertyName error: [%1]")
.arg(err));
return nullptr;
}
char *cname = new char[CFStringGetLength(name) + 1];
CFStringGetCString(name, cname, CFStringGetLength(name) + 1, kCFStringEncodingUTF8);
auto *qname = new QString(cname);
delete[] cname;
return qname;
}
bool CoreAudioData::GetAutoHogMode()
{
UInt32 val = 0;
UInt32 size = sizeof(val);
AudioObjectPropertyAddress pa
{
kAudioHardwarePropertyHogModeIsAllowed,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa, 0, nullptr, &size, &val);
if (err)
{
Warn(QString("GetAutoHogMode: Unable to get auto 'hog' mode. Error = [%1]")
.arg(err));
return false;
}
return (val == 1);
}
void CoreAudioData::SetAutoHogMode(bool enable)
{
UInt32 val = enable ? 1 : 0;
AudioObjectPropertyAddress pa
{
kAudioHardwarePropertyHogModeIsAllowed,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectSetPropertyData(kAudioObjectSystemObject, &pa, 0, nullptr,
sizeof(val), &val);
if (err)
{
Warn(QString("SetAutoHogMode: Unable to set auto 'hog' mode. Error = [%1]")
.arg(err));
}
}
pid_t CoreAudioData::GetHogStatus()
{
pid_t PID;
UInt32 PIDsize = sizeof(PID);
AudioObjectPropertyAddress pa
{
kAudioDevicePropertyHogMode,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa, 0, nullptr,
&PIDsize, &PID);
if (err != noErr)
{
// This is not a fatal error.
// Some drivers simply don't support this property
Debug(QString("GetHogStatus: unable to check: [%1]")
.arg(err));
return -1;
}
return PID;
}
bool CoreAudioData::SetHogStatus(bool hog)
{
AudioObjectPropertyAddress pa
{
kAudioDevicePropertyHogMode,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// According to Jeff Moore (Core Audio, Apple), Setting kAudioDevicePropertyHogMode
// is a toggle and the only way to tell if you do get hog mode is to compare
// the returned pid against getpid, if the match, you have hog mode, if not you don't.
if (!mDeviceID)
return false;
if (hog)
{
if (mHog == -1) // Not already set
{
Debug(QString("SetHogStatus: Setting 'hog' status on device %1")
.arg(mDeviceID));
OSStatus err = AudioObjectSetPropertyData(mDeviceID, &pa, 0, nullptr,
sizeof(mHog), &mHog);
if (err || mHog != getpid())
{
Warn(QString("SetHogStatus: Unable to set 'hog' status. Error = [%1]")
.arg(OSS_STATUS(err)));
return false;
}
Debug(QString("SetHogStatus: Successfully set 'hog' status on device %1")
.arg(mDeviceID));
}
}
else
{
if (mHog > -1) // Currently Set
{
Debug(QString("SetHogStatus: Releasing 'hog' status on device %1")
.arg(mDeviceID));
pid_t hogPid = -1;
OSStatus err = AudioObjectSetPropertyData(mDeviceID, &pa, 0, nullptr,
sizeof(hogPid), &hogPid);
if (err || hogPid == getpid())
{
Warn(QString("SetHogStatus: Unable to release 'hog' status. Error = [%1]")
.arg(OSS_STATUS(err)));
return false;
}
mHog = hogPid; // Reset internal state
}
}
return true;
}
bool CoreAudioData::SetMixingSupport(bool mix)
{
if (!mDeviceID)
return false;
int restore = -1;
if (mMixerRestore == -1) // This is our first change to this setting. Store the original setting for restore
restore = (GetMixingSupport() ? 1 : 0);
UInt32 mixEnable = mix ? 1 : 0;
Debug(QString("SetMixingSupport: %1abling mixing for device %2")
.arg(mix ? "En" : "Dis")
.arg(mDeviceID));
AudioObjectPropertyAddress pa
{
kAudioDevicePropertySupportsMixing,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectSetPropertyData(mDeviceID, &pa, 0, nullptr,
sizeof(mixEnable), &mixEnable);
if (err)
{
Warn(QString("SetMixingSupport: Unable to set MixingSupport to %1. Error = [%2]")
.arg(mix ? "'On'" : "'Off'")
.arg(OSS_STATUS(err)));
return false;
}
if (mMixerRestore == -1)
mMixerRestore = restore;
return true;
}
bool CoreAudioData::GetMixingSupport()
{
if (!mDeviceID)
return false;
UInt32 val = 0;
UInt32 size = sizeof(val);
AudioObjectPropertyAddress pa
{
kAudioDevicePropertySupportsMixing,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus err = AudioObjectGetPropertyData(mDeviceID, &pa, 0, nullptr,
&size, &val);
if (err)
return false;
return (val > 0);
}
/**
* Get a list of all the streams on this device
*/
AudioStreamIDVec CoreAudioData::StreamsList(AudioDeviceID d)
{
OSStatus err;
UInt32 listSize;
AudioStreamIDVec vec {};
AudioObjectPropertyAddress pa
{
kAudioDevicePropertyStreams,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
err = AudioObjectGetPropertyDataSize(d, &pa,
0, nullptr, &listSize);
if (err != noErr)
{
Error(QString("StreamsList: could not get list size: [%1]")
.arg(OSS_STATUS(err)));
return {};
}
try
{
vec.reserve(listSize / sizeof(AudioStreamID));
}
catch (...)
{
Error("StreamsList(): out of memory?");
return {};
}
err = AudioObjectGetPropertyData(d, &pa,
0, nullptr, &listSize, vec.data());
if (err != noErr)
{
Error(QString("StreamsList: could not get list: [%1]")
.arg(OSS_STATUS(err)));
return {};
}
return vec;
}
AudioStreamRangedVec CoreAudioData::FormatsList(AudioStreamID s)
{
OSStatus err;
AudioStreamRangedVec vec;
UInt32 listSize;
AudioObjectPropertyAddress pa
{
kAudioStreamPropertyPhysicalFormats,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// Retrieve all the stream formats supported by this output stream
err = AudioObjectGetPropertyDataSize(s, &pa, 0, nullptr, &listSize);
if (err != noErr)
{
Warn(QString("FormatsList(): couldn't get list size: [%1]")
.arg(OSS_STATUS(err)));
return {};
}
try
{
vec.reserve(listSize / sizeof(AudioStreamRangedDescription));
}
catch (...)
{
Error("FormatsList(): out of memory?");
return {};
}
err = AudioObjectGetPropertyData(s, &pa, 0, nullptr, &listSize, vec.data());
if (err != noErr)
{
Warn(QString("FormatsList: couldn't get list: [%1]")
.arg(OSS_STATUS(err)));
return {};
}
return vec;
}
static UInt32 sNumberCommonSampleRates = 15;
static Float64 sCommonSampleRates[] = {
8000.0, 11025.0, 12000.0,
16000.0, 22050.0, 24000.0,
32000.0, 44100.0, 48000.0,
64000.0, 88200.0, 96000.0,
128000.0, 176400.0, 192000.0 };
static bool IsRateCommon(Float64 inRate)
{
bool theAnswer = false;
for(UInt32 i = 0; !theAnswer && (i < sNumberCommonSampleRates); i++)
{
theAnswer = inRate == sCommonSampleRates[i];
}
return theAnswer;
}
RatesVec CoreAudioData::RatesList(AudioDeviceID d)
{
OSStatus err;
AudioValueRangeVec ranges;
RatesVec finalvec;
UInt32 listSize;
AudioObjectPropertyAddress pa
{
kAudioDevicePropertyAvailableNominalSampleRates,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// retrieve size of rate list
err = AudioObjectGetPropertyDataSize(d, &pa, 0, nullptr, &listSize);
if (err != noErr)
{
Warn(QString("RatesList(): couldn't get data rate list size: [%1]")
.arg(err));
return {};
}
try
{
ranges.reserve(listSize / sizeof(AudioValueRange));
finalvec.reserve(listSize / sizeof(AudioValueRange));
}
catch (...)
{
Error("RatesList(): out of memory?");
return {};