-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppleUSBAudioDevice.cpp
executable file
·8435 lines (7283 loc) · 312 KB
/
AppleUSBAudioDevice.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) 1998-2010 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
//--------------------------------------------------------------------------------
//
// File: DJM03AudioDevice.cpp
//
// Contains: Support for the USB Audio Class Control Interface.
// This includes support for exporting device controls
// to the Audio HAL such as Volume, Bass, Treble and
// Mute.
//
// Future support will include parsing of the device
// topology and exporting of all appropriate device
// control functions through the Audio HAL.
//
// Technology: OS X
//
//--------------------------------------------------------------------------------
#include "AppleUSBAudioDevice.h"
#include "AppleUSBAudioDictionary.h"
//#undef debugIOLog
//#define debugIOLog( message... ) do {IOLog( message );IOLog("\n");} while (0)
#define super IOAudioDevice
#define LOCALIZABLE FALSE
OSDefineMetaClassAndStructors (DJM03AudioDevice, super)
void DJM03AudioDevice::free () {
debugIOLog ("+ DJM03AudioDevice[%p]::free ()", this);
if (NULL != mUpdateTimer)
{
mUpdateTimer->cancelTimeout ();
mUpdateTimer->release ();
mUpdateTimer = NULL;
}
if (mStatusInterruptBuffer)
{
// <rdar://7000283> Pointer was obtained from mInterruptEndpointMemoryDescriptor, so no need to free it
// explicitly here.
mStatusInterruptBuffer = NULL;
}
if (mInterruptEndpointMemoryDescriptor)
{
mInterruptEndpointMemoryDescriptor->release ();
mInterruptEndpointMemoryDescriptor = NULL;
}
// <rdar://problem/7378275>
if (mTimeLock)
{
IOLockFree (mTimeLock);
mTimeLock = NULL;
}
if (mInterfaceLock)
{
IORecursiveLockFree (mInterfaceLock);
mInterfaceLock = NULL;
}
// <rdar://problem/6369110>
if (mRegisteredEnginesMutex)
{
IORecursiveLockFree (mRegisteredEnginesMutex);
mRegisteredEnginesMutex = NULL;
}
// <rdar://problem/6420832>
if (mRegisteredStreamsMutex)
{
IORecursiveLockFree (mRegisteredStreamsMutex);
mRegisteredStreamsMutex = NULL;
}
if (mConfigDictionary)
{
mConfigDictionary->release ();
mConfigDictionary = NULL;
}
if (mRegisteredEngines)
{
mRegisteredEngines->release ();
mRegisteredEngines = NULL;
}
// <rdar://problem/6420832>
if (mRegisteredStreams)
{
mRegisteredStreams->release ();
mRegisteredStreams = NULL;
}
if ( 0 != mEngineArray )
{
for ( UInt32 engineIndex = 0; engineIndex < mEngineArray->getCount (); engineIndex++ )
{
DJM03AudioEngine * engine = OSDynamicCast ( DJM03AudioEngine, mEngineArray->getObject ( engineIndex ) );
if ( 0 != engine )
{
engine->release ();
}
}
mEngineArray->release ();
mEngineArray = 0;
}
if (mMonoControlsArray)
{
mMonoControlsArray->release ();
mMonoControlsArray = NULL;
}
if (mRetryEQDownloadThread)
{
thread_call_free (mRetryEQDownloadThread);
}
super::free ();
debugIOLog ("- DJM03AudioDevice[%p]::free ()", this);
}
bool DJM03AudioDevice::ControlsStreamNumber (UInt8 streamNumber) {
OSArray * streamNumberArray = NULL;
OSObject * arrayObject = NULL;
OSNumber * arrayNumber = NULL;
UInt8 numStreams;
UInt8 streamIndex;
bool doesControl;
doesControl = FALSE;
if (mConfigDictionary)
{
FailIf (kIOReturnSuccess != mConfigDictionary->getControlledStreamNumbers (&streamNumberArray, &numStreams), Exit);
for (streamIndex = 0; streamIndex < numStreams; streamIndex++)
{
FailIf (NULL == (arrayObject = streamNumberArray->getObject (streamIndex)), Exit);
FailIf (NULL == (arrayNumber = OSDynamicCast (OSNumber, arrayObject)), Exit);
debugIOLog ("? DJM03AudioDevice[%p]::ControlsStreamNumber () - Checking stream %d against controled stream %d", this, streamNumber, arrayNumber->unsigned8BitValue());
if (streamNumber == arrayNumber->unsigned8BitValue())
{
doesControl = TRUE;
break; // get out of for loop
}
}
}
Exit:
return doesControl;
}
bool DJM03AudioDevice::start (IOService * provider) {
bool result;
debugIOLog ("+ DJM03AudioDevice[%p]::start (%p)", this, provider);
result = FALSE;
mControlInterface = OSDynamicCast (IOUSBInterface, provider);
FailIf (NULL == mControlInterface, Exit); // <rdar://7085810>
FailIf (FALSE == mControlInterface->open (this), Exit);
// <rdar://problem/6686515>
mInitHardwareThread = thread_call_allocate ((thread_call_func_t)DJM03AudioDevice::initHardwareThread, (thread_call_param_t)this);
FailIf (NULL == mInitHardwareThread, Exit);
result = super::start (provider); // Causes our initHardware routine to be called.
Exit:
// <rdar://problems/6576824&6674310> DJM03Audio fails to unload properly
if ( !result )
{
stop ( provider );
}
debugIOLog ("- DJM03AudioDevice[%p]::start (%p) = result = %d", this, provider, result);
return result;
}
// <rdar://problem/6686515>
bool DJM03AudioDevice::initHardware (IOService * provider) {
bool result;
result = FALSE;
FailIf (NULL == mInitHardwareThread, Exit);
// <rdar://6223517> Retain a reference in case the DJM03AudioDevice object is release while it is trying to execute the thread.
retain ();
if (TRUE == thread_call_enter1 (mInitHardwareThread, (void *)provider))
{
// <rdar://6223517> Release the reference if the thread is already scheduled.
release ();
}
result = TRUE;
Exit:
return result;
}
// <rdar://problem/6686515>
void DJM03AudioDevice::initHardwareThread (DJM03AudioDevice * aua, void * provider) {
IOCommandGate * cg;
IOReturn result;
FailIf (NULL == aua, Exit);
// FailIf (TRUE == aua->mTerminating, Exit);
cg = aua->getCommandGate ();
if (cg)
{
result = cg->runAction (aua->initHardwareThreadAction, provider);
}
aua->release (); // <rdar://6223517> Release the reference that were retained before thread_call_enter1().
Exit:
return;
}
IOReturn DJM03AudioDevice::initHardwareThreadAction (OSObject * owner, void * provider, void * arg2, void * arg3, void * arg4) {
DJM03AudioDevice * aua;
IOReturn result;
result = kIOReturnError;
aua = (DJM03AudioDevice *)owner;
FailIf (NULL == aua, Exit);
result = aua->protectedInitHardware ((IOService *)provider);
Exit:
return result;
}
IOReturn DJM03AudioDevice::protectedInitHardware (IOService * provider) {
char string[kStringBufferSize];
UInt8 stringIndex;
IOReturn err;
Boolean resultCode;
// OSArray * streamNumberArray;
// UInt8 numStreamInterfaces;
// UInt8 numStreams;
OSObject * nameObject = NULL;
OSString * nameString = NULL;
OSString * localizedBundle = NULL;
debugIOLog ("+ DJM03AudioDevice[%p]::protectedInitHardware (%p)", this, provider);
resultCode = FALSE;
FailIf (NULL == mControlInterface, Exit);
debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - %d configuration(s) on this device. This control interface number is %d", this, mControlInterface->GetDevice()->GetNumConfigurations (), mControlInterface->GetInterfaceNumber ());
debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - Attempting to create configuration dictionary...", this);
// mConfigDictionary = DJM03ConfigurationDictionary::create (getConfigurationDescriptor(), mControlInterface->GetInterfaceNumber()); // rdar://5495653
mConfigDictionary = DJM03ConfigurationDictionary::create (getConfigurationDescriptor(), 0); // rdar://5495653
FailIf (NULL == mConfigDictionary, Exit);
debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - Successfully created configuration dictionary.", this);
// if ( !mConfigDictionary->hasAudioStreamingInterfaces () )
// {
// Bail since here is nothing related to audio streaming.
// debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - No audio streaming interfaces in configuration dictionary.", this);
// goto Exit;
// }
// <rdar://problem/7378275>
mTimeLock = IOLockAlloc ();
FailIf (NULL == mTimeLock, Exit);
mInterfaceLock = IORecursiveLockAlloc ();
FailIf (NULL == mInterfaceLock, Exit);
// <rdar://problem/6369110> Occassional kernel panic when multiple threads access mRegisteredEngines array simultaneously
mRegisteredEnginesMutex = IORecursiveLockAlloc ();
FailIf (NULL == mRegisteredEnginesMutex, Exit);
// <rdar://problem/6420832> Serialize access to mRegisteredStreams
mRegisteredStreamsMutex = IORecursiveLockAlloc ();
FailIf (NULL == mRegisteredStreamsMutex, Exit);
mControlGraph = BuildConnectionGraph (mControlInterface->GetInterfaceNumber ());
FailIf ( NULL == mControlGraph, Exit );
// FailIf ( 0 == mControlGraph->getCount (), Exit );
// [rdar://4801032]
if ( IP_VERSION_02_00 == mControlInterface->GetInterfaceProtocol() )
{
FailIf ( NULL == ( mClockGraph = buildClockGraph ( mControlInterface->GetInterfaceNumber () ) ), Exit );
// From this moment forward, we may assume that a device is attempting to be USB 2.0 audio class-compliant by the presence of mClockGraph
// Since supported sample rates are no longer listed explicitly in the USB 2.0 audio specification, we must discover them through device
// request inquiries.
FailIf ( kIOReturnSuccess != addSampleRatesFromClockSpace (), Exit );
}
// Check to make sure that the control interface we loaded against has audio streaming interfaces and not just MIDI.
// FailIf (kIOReturnSuccess != mConfigDictionary->getControlledStreamNumbers (&streamNumberArray, &numStreams), Exit);
// FailIf (kIOReturnSuccess != mConfigDictionary->getNumStreamInterfaces (&numStreamInterfaces), Exit);
// debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - %d controlled stream(s). %d stream interface(s).", this, numStreams, numStreamInterfaces);
// FailIf (0 == numStreams, Exit);
// [rdar://problem/5797761]
// Try to get the name to give this control. We will attempt to name it by the following order:
// 1. "USB Interface Name" for this control interface
// 2. Get the "InterfaceStringIndex" and GetStringDescriptor and use that string
// 3. Get the device's "USB Product Name" and use that
err = kIOReturnError;
string[0] = 0;
debugIOLog ( "? DJM03AudioDevice[%p]::protectedInitHardware () - Trying to retrieve the USB Interface Name... ", this );
nameObject = mControlInterface->getProperty ( "USB Interface Name" );
if ( nameObject )
{
if ( NULL != ( nameString = OSDynamicCast ( OSString, nameObject ) ) )
{
debugIOLog ( "? DJM03AudioDevice[%p]::protectedInitHardware () - Retrieved product name %s from registry", this, nameString->getCStringNoCopy () );
strncpy ( string, nameString->getCStringNoCopy(), kStringBufferSize );
err = kIOReturnSuccess;
}
}
else
{
stringIndex = mControlInterface->GetInterfaceStringIndex ();
if (0 != stringIndex)
{
err = mControlInterface->GetDevice()->GetStringDescriptor (stringIndex, string, kStringBufferSize);
// [rdar://3886272] - This could fail on some devices, so we should retry
if (kIOReturnSuccess != err)
{
// Try a regular retry once
debugIOLog ("! DJM03AudioDevice[%p]::protectedInitHardware () - couldn't get string descriptor. Retrying ...", this);
err = mControlInterface->GetDevice()->GetStringDescriptor (stringIndex, string, kStringBufferSize);
}
if (kIOReturnSuccess != err)
{
// Reset the device and try one last time
debugIOLog ("! DJM03AudioDevice[%p]::protectedInitHardware () - Still couldn't get string descriptor. Resetting device ...", this);
mControlInterface->GetDevice()->ResetDevice(); // Doesn't matter if this fails
IOSleep (50); // Give the device 50 ms to get ready
debugIOLog ("! DJM03AudioDevice[%p]::protectedInitHardware () - Last retry ...", this);
err = mControlInterface->GetDevice()->GetStringDescriptor (stringIndex, string, kStringBufferSize);
}
}
else
{
// [rdar://5159683] This device may not have either string, so read it from the IOUSBDevice.
nameObject = NULL;
nameString = NULL;
debugIOLog ( "! DJM03AudioDevice[%p]::protectedInitHardware () - Trying to retrieve the product name from the IOUSBDevice ... ", this );
nameObject = mControlInterface->GetDevice ()->getProperty ( "USB Product Name" );
if ( nameObject )
{
if ( NULL != ( nameString = OSDynamicCast ( OSString, nameObject ) ) )
{
debugIOLog ( "? DJM03AudioDevice[%p]::protectedInitHardware () - Retrieved product name %s from registry", this, nameString->getCStringNoCopy () );
strncpy ( string, nameString->getCStringNoCopy(), kStringBufferSize );
err = kIOReturnSuccess;
}
}
else
{
// If there is no USB Product Name, there is no ProductString index, so just return an error.
debugIOLog ("! DJM03AudioDevice[%p]::protectedInitHardware () - There was no USB Product Name", this);
err = kIOReturnBadArgument;
}
}
}
if (0 == string[0] || kIOReturnSuccess != err)
{
strncpy (string, "Unknown USB Audio Device", kStringBufferSize);
}
setDeviceName ("PIONEER DJM-850");
// <rdar://problem/6398888> Attempt to retrieve the manufacturer name from registry before reading it from the device
err = kIOReturnError;
string[0] = 0;
nameObject = mControlInterface->GetDevice ()->getProperty ( "USB Vendor Name" );
if ( nameObject )
{
if ( NULL != ( nameString = OSDynamicCast ( OSString, nameObject ) ) )
{
debugIOLog ( "? DJM03AudioDevice[%p]::protectedInitHardware () - Retrieved vendor name %s from registry", this, nameString->getCStringNoCopy () );
strncpy ( string, nameString->getCStringNoCopy (), kStringBufferSize );
err = kIOReturnSuccess;
}
}
else
{
stringIndex = mControlInterface->GetDevice()->GetManufacturerStringIndex ();
if (0 != stringIndex)
{
err = mControlInterface->GetDevice()->GetStringDescriptor (stringIndex, string, kStringBufferSize);
}
}
if (0 == string[0] || kIOReturnSuccess != err)
{
strncpy (string, "Unknown Manufacturer", kStringBufferSize);
}
setManufacturerName (string);
setDeviceTransportType (kIOAudioDeviceTransportTypeUSB);
// <rdar://problem/5797761> <rdar://problem/5797877>
// If our provider has a kIOAudioDeviceLocalizedBundleKey, copy it to our entry. This allows us to localize
// a string by using a codeless kext to specify the bundle
// Try to get the localized kext bundle. We will attempt to name it by the following order:
// 1. kIOAudioDeviceLocalizedBundleKey for this control interface
// 2. Get the device's kIOAudioDeviceLocalizedBundleKey and use that
localizedBundle = OSDynamicCast ( OSString, mControlInterface->getProperty ( kIOAudioDeviceLocalizedBundleKey ) );
if ( NULL == localizedBundle )
{
localizedBundle = OSDynamicCast ( OSString, mControlInterface->GetDevice()->getProperty ( kIOAudioDeviceLocalizedBundleKey ) );
}
if ( NULL != localizedBundle )
{
debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - setting kIOAudioDeviceLocalizedBundleKey property to %s", this, localizedBundle->getCStringNoCopy () );
setProperty ( kIOAudioDeviceLocalizedBundleKey, localizedBundle );
}
#if LOCALIZABLE
else
{
debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - setting kIOAudioDeviceLocalizedBundleKey property to DJM03Audio.kext", this);
setProperty ( kIOAudioDeviceLocalizedBundleKey, "DJM-850 USBAudio.kext" );
}
#endif
// Create the audio engines
resultCode = createAudioEngines ();
FailIf ( FALSE == resultCode, Exit ); // <rdar://problem/6576824> DJM03Audio fails to unload properly
resultCode = activateAudioEngines ();
FailIf ( FALSE == resultCode, Exit ); // <rdar://problem/6576824> DJM03Audio fails to unload properly
resultCode = super::initHardware (provider);
FailIf ( FALSE == resultCode, Exit ); // <rdar://problem/6576824> DJM03Audio fails to unload properly
// Start the anchored time stamp timer if necessary
// Initialize time stamp member variables
mLastUSBFrame = 0ull;
mLastWallTime_nanos = 0ull;
// Initialize mWallTimePerUSBCycle
resetRateTimer();
// We should get a new anchor immediately.
updateUSBCycleTime (); // <rdar://problem/7378275>, <rdar://problem/7666699>
// [rdar://] This member variable keeps track an engine that has had a catastrophic failure that requires an emergency format change.
mFailingAudioEngine = NULL;
// Register and start update timer <rdar://problem/7378275>
mTimerCallCount = 0;
mRampUpdateCounter = 0; // <rdar://problem/7666699>
mUpdateTimer = IOTimerEventSource::timerEventSource (this, TimerAction);
FailIf (NULL == mUpdateTimer, Exit);
workLoop->addEventSource (mUpdateTimer);
debugIOLog ("? DJM03AudioDevice[%p]::protectedInitHardware () - starting rate timer", this);
TimerAction ( this, mUpdateTimer);
// <rdar://problem/6021475> DJM03Audio: Status Interrupt Endpoint support
mProcessStatusInterruptThread = thread_call_allocate ( ( thread_call_func_t )processStatusInterrupt, ( thread_call_param_t )this );
FailIf ( NULL == mProcessStatusInterruptThread, Exit );
checkForStatusInterruptEndpoint ();
// Added for rdar://3993906 . This forces matchPropertyTable () to run again.
// <rdar://7295322> Asynchronous to prevent deadlock if the device or interface is terminated while
// registerService() is performing matching.
IOService::registerService ( kIOServiceAsynchronous );
Exit:
debugIOLog ("- DJM03AudioDevice[%p]::protectedInitHardware (%p)", this, provider);
return ( resultCode ? kIOReturnSuccess : kIOReturnError ); // <rdar://problem/6576824>
}
// <rdar://problem/6021475> DJM03Audio: Status Interrupt Endpoint support
void DJM03AudioDevice::checkForStatusInterruptEndpoint( void )
{
IOUSBFindEndpointRequest interruptEndpoint;
UInt8 endpointAddress;
UInt8 controlInterfaceNum;
UInt32 messageLength;
debugIOLog ("+ DJM03AudioDevice[%p]::checkForStatusInterruptEndpoint ()", this);
FailIf ( NULL == mControlInterface, Exit ); // <rdar://7085810>
controlInterfaceNum = mControlInterface->GetInterfaceNumber ();
// check for interrupt endpoint
if ( mConfigDictionary->hasInterruptEndpoint ( controlInterfaceNum, 0 ) && ( kIOReturnSuccess == mConfigDictionary->getInterruptEndpointAddress( &endpointAddress, controlInterfaceNum, 0 ) ) )
{
// setup pipe
if ( IP_VERSION_02_00 == mControlInterface->GetInterfaceProtocol () )
{
// USB Audio 2.0
mStatusInterruptBufferType = kInterruptDataMessageFormat;
messageLength = sizeof(USBAUDIO_0200::InterruptDataMessageFormat);
}
else
{
// USB Audio 1.0
mStatusInterruptBufferType = kAudioStatusWordFormat;
messageLength = sizeof(AudioStatusWordFormat);
}
interruptEndpoint.type = kUSBInterrupt;
interruptEndpoint.direction = kUSBIn; // The associated endpoint always goes "in"
interruptEndpoint.maxPacketSize = messageLength;
interruptEndpoint.interval = 0xFF;
mInterruptPipe = mControlInterface->FindNextPipe ( NULL, &interruptEndpoint );
FailIf ( NULL == mInterruptPipe, Exit );
if ( NULL == mInterruptEndpointMemoryDescriptor )
{
// <rdar://7000283> Remove the use of deprecated IOMallocContiguous(). Use IOBufferMemoryDescriptor to allocate memory instead.
mInterruptEndpointMemoryDescriptor = IOBufferMemoryDescriptor::withOptions ( kIODirectionInOut, messageLength, 8 );
FailIf ( NULL == mInterruptEndpointMemoryDescriptor, Exit );
mStatusInterruptBuffer = mInterruptEndpointMemoryDescriptor->getBytesNoCopy ();
FailIf ( NULL == mStatusInterruptBuffer, Exit );
bzero ( mStatusInterruptBuffer, messageLength );
}
mStatusInterruptCompletion.target = ( void * )this;
mStatusInterruptCompletion.action = statusInterruptHandler;
mStatusInterruptCompletion.parameter = NULL;
mInterruptPipe->retain ();
FailMessage ( kIOReturnSuccess != mInterruptPipe->Read ( mInterruptEndpointMemoryDescriptor, 0, 0, mInterruptEndpointMemoryDescriptor->getLength(), &mStatusInterruptCompletion ) );
}
Exit:
debugIOLog ("- DJM03AudioDevice[%p]::checkForStatusInterruptEndpoint ()", this);
}
void DJM03AudioDevice::statusInterruptHandler( void * target, void * parameter, IOReturn status, UInt32 bufferSizeRemaining )
{
DJM03AudioDevice * self;
FailIf ( NULL == target, Exit );
self = ( DJM03AudioDevice * )target;
debugIOLog ("+ DJM03AudioDevice[%p]::statusInterruptHandler ()", self);
// spawn thread to process interrupt
// <rdar://problem/6622487> Clear stall if detected
if ( kIOReturnAborted == status || self->isInactive () )
{
debugIOLog ("! DJM03AudioDevice[%p]::statusInterruptHandler () error from USB: 0x%X or IOService inactive: %u, NOT reposting read to interrupt pipe", self, status, self->isInactive ());
}
else
{
if ( kIOUSBPipeStalled == status )
{
debugIOLog ("! DJM03AudioDevice[%p]::statusInterruptHandler () error from USB: kIOUSBPipeStalled, reposting read to interrupt pipe", self);
// <rdar://7865729> Defer the ClearPipeStall() to our own thread.
self->mInterruptPipeStalled = true;
}
else if ( kIOReturnSuccess != status )
{
debugIOLog ("! DJM03AudioDevice[%p]::statusInterruptHandler () error from USB: 0x%X, reposting read to interrupt pipe", self, status);
}
self->retain ();
if ( TRUE == thread_call_enter1 ( ( thread_call_t )self->mProcessStatusInterruptThread, ( thread_call_param_t )self ) )
{
self->release ();
}
}
Exit:
debugIOLog ("- DJM03AudioDevice[%p]::statusInterruptHandler ()", self);
return;
}
void DJM03AudioDevice::processStatusInterrupt ( void * arg )
{
DJM03AudioDevice * self;
IOCommandGate * cg;
FailIf ( NULL == arg, Exit );
self = ( DJM03AudioDevice * )arg;
cg = self->getCommandGate ();
if ( cg )
{
cg->runAction ( self->runStatusInterruptTask, ( void * )0, ( void * )0 );
}
self->release ();
Exit:
return;
}
IOReturn DJM03AudioDevice::runStatusInterruptTask( OSObject * target, void * arg0, void * arg1, void * arg2, void * arg3 )
{
DJM03AudioDevice * self;
FailIf ( NULL == target, Exit );
self = ( DJM03AudioDevice * )target;
self->handleStatusInterrupt ();
Exit:
return kIOReturnSuccess;
}
void DJM03AudioDevice::handleStatusInterrupt ( void )
{
AudioStatusWordFormatPtr audioStatusWord;
USBAUDIO_0200::InterruptDataMessageFormatPtr interruptDataMessage;
UInt8 subType;
DJM03AudioEngine * currentEngine = NULL;
OSDictionary * currentEngineInfo = NULL;
IOUSBDevRequestDesc devReq;
OSSet * defaultAudioControls;
bool interruptPending = false;
bool originatedFromACInterface = false;
UInt8 bOriginator;
debugIOLog ("+ DJM03AudioDevice[%p]::handleStatusInterrupt ()", this);
FailIf ( NULL == mControlInterface, Exit );
// <rdar://7865729> Clear the pipe stall here instead of the statusInterruptHandler(). ClearPipeStall() cannot be
// made at that point because it will never be able to complete the correctly as that is the only thread available for
// processing interrupts.
if ( mInterruptPipeStalled )
{
debugIOLog ("! DJM03AudioDevice[%p]::handleStatusInterrupt () clearing pipe stall", this);
if ( mInterruptPipe )
{
mInterruptPipe->ClearPipeStall ( true );
}
mInterruptPipeStalled = false;
}
if ( kAudioStatusWordFormat == mStatusInterruptBufferType )
{
audioStatusWord = ( AudioStatusWordFormatPtr )mStatusInterruptBuffer;
interruptPending = ( 0 != ( audioStatusWord->bStatusType & 0x80 ) );
originatedFromACInterface = ( 0 == ( audioStatusWord->bStatusType & 0x0F ) );
bOriginator = audioStatusWord->bOriginator;
}
else // if ( kInterruptDataMessageFormat == mStatusInterruptBufferType )
{
interruptDataMessage = ( USBAUDIO_0200::InterruptDataMessageFormatPtr )mStatusInterruptBuffer;
interruptPending = ( 0 == ( interruptDataMessage->bInfo & 0x1 ) ); // Class-specific interrupt.
originatedFromACInterface = ( 0 == ( interruptDataMessage->bInfo & 0x02 ) ) && ( ( interruptDataMessage->wIndex & 0xFF ) == mControlInterface->GetInterfaceNumber () );
bOriginator = (UInt8)( ( interruptDataMessage->wIndex >> 8 ) & 0xFF );
}
if ( interruptPending )
{
if ( originatedFromACInterface ) // AudioControl interface
{
mConfigDictionary->getSubType ( &subType, mControlInterface->GetInterfaceNumber (), 0, bOriginator );
// if this is a feature unit, dispatch to engines
if ( ( FEATURE_UNIT == subType ) || ( SELECTOR_UNIT == subType ) ) // <rdar://6523676>
{
FailIf ( NULL == mRegisteredEngines, Exit );
for ( UInt8 engineIndex = 0; engineIndex < mRegisteredEngines->getCount (); engineIndex++ )
{
currentEngineInfo = OSDynamicCast ( OSDictionary, mRegisteredEngines->getObject ( engineIndex ) );
FailIf ( NULL == currentEngineInfo, Exit );
currentEngine = OSDynamicCast ( DJM03AudioEngine, currentEngineInfo->getObject ( kEngine ) );
FailIf ( NULL == currentEngine, Exit );
defaultAudioControls = currentEngine->copyDefaultAudioControls ();
if ( 0 != defaultAudioControls ) // <rdar://7695055>
{
controlHasChangedOnDevice ( bOriginator, defaultAudioControls );
defaultAudioControls->release ();
defaultAudioControls = NULL;
}
}
}
else if ( USBAUDIO_0200::CLOCK_SOURCE == subType )
{
debugIOLog ("? DJM03AudioDevice[%p]::handleStatusInterrupt () - CLOCK_SOURCE : %d", this, bOriginator );
FailIf ( NULL == mRegisteredEngines, Exit );
for ( UInt8 engineIndex = 0; engineIndex < mRegisteredEngines->getCount (); engineIndex++ )
{
currentEngineInfo = OSDynamicCast ( OSDictionary, mRegisteredEngines->getObject ( engineIndex ) );
FailIf ( NULL == currentEngineInfo, Exit );
currentEngine = OSDynamicCast ( DJM03AudioEngine, currentEngineInfo->getObject ( kEngine ) );
FailIf ( NULL == currentEngine, Exit );
currentEngine->updateClockStatus ( bOriginator );
}
}
}
}
if ( kAudioStatusWordFormat == mStatusInterruptBufferType )
{
// Clear status interrupt
devReq.bmRequestType = USBmakebmRequestType ( kUSBIn, kUSBClass, kUSBInterface );
devReq.bRequest = GET_STAT;
devReq.wValue = 0;
FailIf ( NULL == mControlInterface, Exit );
devReq.wIndex = ( 0xFF00 & ( bOriginator << 8 ) ) | ( 0x00FF & mControlInterface->GetInterfaceNumber () );
devReq.wLength = 0;
devReq.pData = NULL;
FailIf ( kIOReturnSuccess != deviceRequest ( &devReq ), Exit );
}
else
{
// For USB Audio 2.0, interrupts are considered 'edge-triggered' type, meaning that an interrupt is generated whenever
// an event occurs, but there is no specific action required from the Host to clear the interrupt condition.
}
// Clear the buffer before next read
bzero ( mStatusInterruptBuffer, ( kAudioStatusWordFormat == mStatusInterruptBufferType ) ? sizeof (AudioStatusWordFormat) : sizeof (USBAUDIO_0200::InterruptDataMessageFormat) );
// Queue next read
if ( mInterruptPipe )
{
FailMessage ( kIOReturnSuccess != mInterruptPipe->Read ( mInterruptEndpointMemoryDescriptor, 0, 0, mInterruptEndpointMemoryDescriptor->getLength (), &mStatusInterruptCompletion ) );
}
Exit:
debugIOLog ("- DJM03AudioDevice[%p]::handleStatusInterrupt ()", this);
return;
}
void DJM03AudioDevice::controlHasChangedOnDevice ( UInt8 controlID, OSSet * defaultAudioControls )
{
UInt32 controlSubType;
SInt16 deviceCur;
SInt16 deviceMin;
SInt16 deviceMax;
UInt16 volRes;
SInt32 controlCur;
OSNumber * settingNumber = NULL;
UInt8 numControls;
UInt8 channelNum;
IOAudioControl * controlObject = NULL ;
OSCollectionIterator * controlsIterator = NULL;
// Find all volume/mute controls associated with this controlID
controlsIterator = OSCollectionIterator::withCollection( defaultAudioControls );
if ( controlsIterator )
{
while ( NULL != ( controlObject = OSDynamicCast( IOAudioControl, controlsIterator->getNextObject () ) ) )
{
if ( controlID == ( ( UInt8 )controlObject->getControlID () & 0xFF ) ) // <rdar://6413207>
{
controlSubType = 0;
controlSubType = controlObject->getSubType();
// only adjust volume and mute subtypes
switch ( controlSubType )
{
case kIOAudioLevelControlSubTypeVolume:
FailIf ( NULL == mControlInterface, Exit );
FailIf ( kIOReturnSuccess != mConfigDictionary->getNumControls ( &numControls, mControlInterface->GetInterfaceNumber (), 0, controlID ), Exit );
for ( channelNum = 0; channelNum <= numControls; channelNum++ )
{
// <rdar://6497818> Update the control with the values in the corresponding channel.
if ( controlObject->getChannelID () == channelNum )
{
// <rdar://6497818> Only if there is volume control present on the channel.
if ( mConfigDictionary->channelHasVolumeControl ( mControlInterface->GetInterfaceNumber (), 0, controlID, channelNum ) )
{
// Read settings on device
FailIf ( kIOReturnSuccess != getCurVolume ( controlID, channelNum, &deviceCur ), Exit );
FailIf ( kIOReturnSuccess != getMinVolume ( controlID, channelNum, &deviceMin ), Exit );
FailIf ( kIOReturnSuccess != getMaxVolume ( controlID, channelNum, &deviceMax ), Exit );
getVolumeResolution ( controlID, channelNum, &volRes );
// [rdar://4511427] Need to check volRes for class compliance (Audio Spec 5.2.2.4.3.2).
FailIf ( 0 == volRes, Exit );
// The current control value is a bit of a special case because the device may violate the spec. The rules are as follows:
// * If the current value is negative infinity, use a control value of 0.
// * If the current value is the minimum value, use a control value of 0.
// * Otherwise calculate the current value as normal.
if ( ( (SInt16) kNegativeInfinity == deviceCur )
|| ( deviceCur == deviceMin ) )
{
controlCur = 0;
}
else
{
controlCur = ( ( deviceCur - deviceMin ) / volRes );
}
// Call hardwareValueChanged() for each with settings read from device
FailIf ( NULL == ( settingNumber = OSNumber::withNumber ( controlCur, SIZEINBITS(SInt32) ) ), Exit );
controlObject->hardwareValueChanged ( settingNumber );
settingNumber->release ();
settingNumber = NULL;
}
break; // <rdar://6497818>
}
}
break;
case kIOAudioToggleControlSubTypeMute:
FailIf ( NULL == mControlInterface, Exit );
FailIf ( kIOReturnSuccess != mConfigDictionary->getNumControls ( &numControls, mControlInterface->GetInterfaceNumber (), 0, controlID ), Exit );
for ( channelNum = 0; channelNum <= numControls; channelNum++ )
{
// <rdar://6497818> Update the control with the values in the corresponding channel.
if ( controlObject->getChannelID () == channelNum )
{
// <rdar://6497818> Only if there is mute control present on the channel.
if ( mConfigDictionary->channelHasMuteControl ( mControlInterface->GetInterfaceNumber (), 0, controlID, channelNum ) )
{
FailIf ( kIOReturnSuccess != getCurMute ( controlID, controlObject->getChannelID (), &deviceCur ), Exit );
FailIf ( NULL == ( settingNumber = OSNumber::withNumber ( deviceCur, SIZEINBITS(SInt16) ) ), Exit );
controlObject->hardwareValueChanged ( settingNumber );
settingNumber->release ();
settingNumber = NULL;
}
break; // <rdar://6497818>
}
}
break;
// <rdar://6523676> Handle changes in the input source selector
case kIOAudioSelectorControlSubTypeInput:
if ( kIOAudioControlTypeSelector == controlObject->getType() )
{
UInt8 oldSelectorPosition;
UInt8 newSelectorPosition;
FailIf ( NULL == mControlInterface, Exit );
oldSelectorPosition = controlObject->getIntValue () & 0x000000FF;
newSelectorPosition = getSelectorSetting ( controlID );
if ( oldSelectorPosition != newSelectorPosition )
{
// The current selected input is no longer valid. Switch over to the new input source.
OSArray * availableSelections = OSDynamicCast ( OSArray, controlObject->getProperty ( kIOAudioSelectorControlAvailableSelectionsKey ) );
if ( NULL != availableSelections )
{
for ( UInt32 index = 0; index < availableSelections->getCount (); index++ )
{
OSDictionary * selectionDictionary = OSDynamicCast ( OSDictionary, availableSelections->getObject ( index ) );
if ( NULL != selectionDictionary )
{
OSNumber * selectionNumber = OSDynamicCast ( OSNumber, selectionDictionary->getObject ( kIOAudioSelectorControlSelectionValueKey ) );
if ( NULL != selectionNumber )
{
SInt32 selection = (SInt32)selectionNumber->unsigned32BitValue ();
if ( ( selection & 0x000000FF ) == newSelectorPosition )
{
// Found the input source. Switch over to it.
debugIOLog ( "? DJM03AudioDevice[%p]::controlHasChangedOnDevice () - Switch input selector over to selection = 0x%x", this, selection );
controlObject->setValue ( selection );
break;
}
}
}
}
}
}
}
break;
} // end switch
} // end if
} // end while
}
Exit:
controlsIterator->release ();
}
IOReturn DJM03AudioDevice::performPowerStateChange (IOAudioDevicePowerState oldPowerState, IOAudioDevicePowerState newPowerState, UInt32 *microSecsUntilComplete) {
IOReturn result;
bool performDeviceResetOnWake = false;
IOUSBDevice * usbDevice = NULL;
// debugIOLog ("+ DJM03AudioDevice[%p]::performPowerStateChange (%d, %d, %p)", this, oldPowerState, newPowerState, microSecsUntilComplete);
result = super::performPowerStateChange (oldPowerState, newPowerState, microSecsUntilComplete);
// We need to stop the time stamp rate timer now
if ( (mUpdateTimer)
&& (kIOAudioDeviceSleep == newPowerState))
{
// Stop the timer and reset the anchor.
debugIOLog ("? DJM03AudioDevice[%p]::performPowerStateChange () - Going to sleep - stopping the rate timer.", this);
mUpdateTimer->cancelTimeout ();
// The frame/time correlation isn't preserved across sleep/wake
mLastUSBFrame = 0ull;
mLastWallTime_nanos = 0ull;
}
if (oldPowerState == kIOAudioDeviceSleep)
{
// A new anchor should be taken at the first opportunity. The timer action will handle this with the following instruction.
// [rdar://4380545] We need to reset the wall time per USB cycle because the frame number could become invalid entering sleep.
resetRateTimer();
// We should get a new anchor immediately.
updateUSBCycleTime (); // <rdar://problem/7378275>, <rdar://problem/7666699>
#if RESETAFTERSLEEP
// [rdar://4234453] Reset the device after waking from sleep just to be safe.
performDeviceResetOnWake = true;
#endif /* RESETAFTERSLEEP */
FailIf (NULL == mControlInterface, Exit);
// <rdar://7499125> Check if the GetDevice() returns a valid pointer.
usbDevice = mControlInterface->GetDevice ();
FailIf (NULL == usbDevice, Exit);
// <rdar://problem/6392504> Make sure that the device is connected before resetting it
if ( kIOReturnSuccess == usbDevice->message( kIOUSBMessageHubIsDeviceConnected, NULL, 0 ) ) // <rdar://7499125>
{
if ( performDeviceResetOnWake )
{
debugIOLog ("? DJM03AudioDevice[%p]::performPowerStateChange () - Resetting port after wake from sleep ...", this);
usbDevice->ResetDevice(); // <rdar://7499125>
IOSleep (10);
}
}
// We need to restart the time stamp rate timer now
debugIOLog ("? DJM03AudioDevice[%p]::performPowerStateChange () - Waking from sleep - restarting the rate timer.", this);
TimerAction ( this, mUpdateTimer);
debugIOLog ("? DJM03AudioDevice[%p]::performPowerStateChange () - Flushing controls to the device ...", this);
flushAudioControls ();
}
Exit:
// debugIOLog ("- DJM03AudioDevice[%p]::performPowerStateChange (%d, %d, %p)", this, oldPowerState, newPowerState, microSecsUntilComplete);
return result;
}
void DJM03AudioDevice::stop (IOService *provider) {
debugIOLog ("+ DJM03AudioDevice[%p]::stop (%p) - audioEngines = %p - rc=%d", this, provider, audioEngines, getRetainCount());
// <rdar://problem/6021475> DJM03Audio: Status Interrupt Endpoint support
if ( NULL != mInterruptPipe )
{
mInterruptPipe->Abort ();
mInterruptPipe->release ();
mInterruptPipe = NULL;
}
if ( mProcessStatusInterruptThread )
{
thread_call_cancel ( mProcessStatusInterruptThread );
thread_call_free ( mProcessStatusInterruptThread );
mProcessStatusInterruptThread = NULL;
}