debug aggregate device issue - i386/10.8 only
[ardour.git] / libs / backends / coreaudio / coreaudio_pcmio_aggregate.cc
1 /*
2  * Copyright (C) 2015 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2004-2008 Grame
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <vector>
21
22 void
23 CoreAudioPCM::destroy_aggregate_device ()
24 {
25         if (_aggregate_plugin_id == 0) {
26                 return;
27         }
28
29         OSStatus err;
30
31         AudioObjectPropertyAddress property_address;
32         property_address.mSelector = kAudioPlugInDestroyAggregateDevice;
33         property_address.mScope = kAudioObjectPropertyScopeGlobal;
34         property_address.mElement = kAudioObjectPropertyElementMaster;
35         UInt32 outDataSize = 0;
36
37         err = AudioObjectGetPropertyDataSize(_aggregate_plugin_id, &property_address, 0, NULL, &outDataSize);
38         if (err != noErr) {
39                 fprintf(stderr, "DestroyAggregateDevice : AudioObjectGetPropertyDataSize error\n");
40                 return;
41         }
42
43         err = AudioObjectGetPropertyData(_aggregate_plugin_id, &property_address, 0, NULL, &outDataSize, &_aggregate_device_id);
44         if (err != noErr) {
45                 fprintf(stderr, "DestroyAggregateDevice : AudioObjectGetPropertyData error\n");
46                 return;
47         }
48 #ifndef NDEBUG
49         printf("DestroyAggregateDevice : OK (plugin: %u device:%u)\n",
50                         (unsigned int)_aggregate_plugin_id,
51                         (unsigned int)_aggregate_device_id);
52 #endif
53 }
54
55 int
56 CoreAudioPCM::create_aggregate_device (
57                 AudioDeviceID input_device_id,
58                 AudioDeviceID output_device_id,
59                 uint32_t sample_rate,
60                 AudioDeviceID* created_device)
61 {
62         OSStatus err;
63         AudioObjectID sub_device[32];
64         UInt32 size = sizeof(sub_device);
65
66         /* look up sub-devices */
67         err = GetPropertyWrapper (input_device_id, 0, 0, kAudioAggregateDevicePropertyActiveSubDeviceList, &size, sub_device);
68         std::vector<AudioDeviceID> input_device_ids;
69
70         if (err != noErr) {
71                 input_device_ids.push_back(input_device_id);
72         } else {
73                 uint32_t num_devices = size / sizeof(AudioObjectID);
74                 for (uint32_t i = 0; i < num_devices; ++i) {
75                         input_device_ids.push_back(sub_device[i]);
76                 }
77         }
78
79         size = sizeof(sub_device);
80         err = GetPropertyWrapper (output_device_id, 0, 0, kAudioAggregateDevicePropertyActiveSubDeviceList, &size, sub_device);
81         std::vector<AudioDeviceID> output_device_ids;
82
83         if (err != noErr) {
84                 output_device_ids.push_back(output_device_id);
85         } else {
86                 uint32_t num_devices = size / sizeof(AudioObjectID);
87                 for (uint32_t i = 0; i < num_devices; ++i) {
88                         output_device_ids.push_back(sub_device[i]);
89                 }
90         }
91
92         //---------------------------------------------------------------------------
93         // Setup SR of both devices otherwise creating AD may fail...
94         //---------------------------------------------------------------------------
95         UInt32 keptclockdomain = 0;
96         UInt32 clockdomain = 0;
97         size = sizeof(UInt32);
98         bool need_clock_drift_compensation = false;
99
100         for (size_t i = 0; i < input_device_ids.size(); ++i) {
101                 set_device_sample_rate_id(input_device_ids[i], sample_rate, true);
102
103                 // Check clock domain
104                 err = GetPropertyWrapper (input_device_ids[i], 0, 0, kAudioDevicePropertyClockDomain, &size, &clockdomain);
105                 if (err == noErr) {
106                         keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
107                         if (clockdomain != 0 && clockdomain != keptclockdomain) {
108 #ifndef NDEBUG
109                                 printf("AggregateDevice: devices do not share the same clock.\n");
110 #endif
111                                 need_clock_drift_compensation = true;
112                         }
113                 }
114         }
115
116         for (UInt32 i = 0; i < output_device_ids.size(); i++) {
117                 set_device_sample_rate_id(output_device_ids[i], sample_rate, true);
118
119                 // Check clock domain
120                 err = GetPropertyWrapper (output_device_ids[i], 0, 0, kAudioDevicePropertyClockDomain, &size, &clockdomain);
121                 if (err == noErr) {
122                         keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
123                         if (clockdomain != 0 && clockdomain != keptclockdomain) {
124 #ifndef NDEBUG
125                                 printf("AggregateDevice: devices do not share the same clock.\n");
126 #endif
127                                 need_clock_drift_compensation = true;
128                         }
129                 }
130         }
131
132         // If no valid clock domain was found, then assume we have to compensate...
133         if (keptclockdomain == 0) {
134                 need_clock_drift_compensation = true;
135         }
136
137         //---------------------------------------------------------------------------
138         // Start to create a new aggregate by getting the base audio hardware plugin
139         //---------------------------------------------------------------------------
140
141 #ifndef NDEBUG
142         char device_name[256];
143         for (size_t i = 0; i < input_device_ids.size(); ++i) {
144                 GetDeviceNameFromID(input_device_ids[i], device_name);
145                 printf("Separated input = '%s'\n", device_name);
146         }
147
148         for (size_t i = 0; i < output_device_ids.size(); ++i) {
149                 GetDeviceNameFromID(output_device_ids[i], device_name);
150                 printf("Separated output = '%s'\n", device_name);
151         }
152 #endif
153
154         err = GetHardwarePropertyInfoWrapper (kAudioHardwarePropertyPlugInForBundleID, &size);
155         if (err != noErr) {
156                 fprintf(stderr, "AggregateDevice: AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error\n");
157                 return -1;
158         }
159
160         AudioValueTranslation pluginAVT;
161
162         CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
163
164         pluginAVT.mInputData = &inBundleRef;
165         pluginAVT.mInputDataSize = sizeof(inBundleRef);
166         pluginAVT.mOutputData = &_aggregate_plugin_id;
167         pluginAVT.mOutputDataSize = sizeof(AudioDeviceID);
168
169         err = GetHardwarePropertyWrapper (kAudioHardwarePropertyPlugInForBundleID, &size, &pluginAVT);
170         if (err != noErr) {
171                 fprintf(stderr, "AggregateDevice: AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error\n");
172                 return -1;
173         }
174
175         //-------------------------------------------------
176         // Create a CFDictionary for our aggregate device
177         //-------------------------------------------------
178
179         CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
180
181         CFStringRef AggregateDeviceNameRef = CFSTR("ArdourDuplex");
182         CFStringRef AggregateDeviceUIDRef = CFSTR("com.ardour.CoreAudio");
183         CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
184         CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
185
186 #ifndef NDEBUG
187         // hide from list
188         int value = 1;
189         CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
190         CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
191 #endif
192
193         //-------------------------------------------------
194         // Create a CFMutableArray for our sub-device list
195         //-------------------------------------------------
196
197         // we need to append the UID for each device to a CFMutableArray, so create one here
198         CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
199
200         std::vector<CFStringRef> captureDeviceUID;
201         for (UInt32 i = 0; i < input_device_ids.size(); i++) {
202                 CFStringRef ref = GetDeviceName(input_device_ids[i]);
203                 if (ref == NULL) {
204                         return -1;
205                 }
206                 captureDeviceUID.push_back(ref);
207                 CFArrayAppendValue(subDevicesArray, ref);
208         }
209
210         std::vector<CFStringRef> playbackDeviceUID;
211         for (UInt32 i = 0; i < output_device_ids.size(); i++) {
212                 CFStringRef ref = GetDeviceName(output_device_ids[i]);
213                 if (ref == NULL) {
214                         return -1;
215                 }
216                 playbackDeviceUID.push_back(ref);
217                 CFArrayAppendValue(subDevicesArray, ref);
218         }
219
220         //-----------------------------------------------------------------------
221         // Feed the dictionary to the plugin, to create a blank aggregate device
222         //-----------------------------------------------------------------------
223
224         AudioObjectPropertyAddress pluginAOPA;
225         pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
226         pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
227         pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
228         UInt32 outDataSize = 0;
229
230         err = AudioObjectGetPropertyDataSize(_aggregate_plugin_id, &pluginAOPA, 0, NULL, &outDataSize);
231 #ifdef WE_DONT_CARE_ABOUT_SOME_ODD_MAVERICKS_I386_ODDITITY
232         if (err != noErr) {
233                 fprintf(stderr, "AggregateDevice: AudioObjectGetPropertyDataSize error %d\n", err);
234                 goto error;
235         }
236 #endif
237
238         err = AudioObjectGetPropertyData(_aggregate_plugin_id, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, created_device);
239         if (err != noErr) {
240                 fprintf(stderr, "AggregateDevice: AudioObjectGetPropertyData error %d\n", err);
241                 goto error;
242         }
243
244         // pause for a bit to make sure that everything completed correctly
245         // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
246         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
247
248         //-------------------------
249         // Set the sub-device list
250         //-------------------------
251
252         pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
253         pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
254         pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
255         outDataSize = sizeof(CFMutableArrayRef);
256         err = AudioObjectSetPropertyData(*created_device, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
257         if (err != noErr) {
258                 fprintf(stderr, "AggregateDevice: AudioObjectSetPropertyData for sub-device list error\n");
259                 goto error;
260         }
261
262         // pause again to give the changes time to take effect
263         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
264
265         //-----------------------
266         // Set the master device
267         //-----------------------
268
269         // set the master device manually (this is the device which will act as the master clock for the aggregate device)
270         // pass in the UID of the device you want to use
271         pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
272         pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
273         pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
274         outDataSize = sizeof(CFStringRef);
275         err = AudioObjectSetPropertyData(*created_device, &pluginAOPA, 0, NULL, outDataSize, &playbackDeviceUID[0]);
276         if (err != noErr) {
277                 fprintf(stderr, "AggregateDevice: AudioObjectSetPropertyData for playback-master device error\n");
278                 // try playback
279                 err = AudioObjectSetPropertyData(*created_device, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]);
280         }
281         if (err != noErr) {
282                 fprintf(stderr, "AggregateDevice: AudioObjectSetPropertyData for capture-master device error\n");
283                 goto error;
284         }
285
286         // pause again to give the changes time to take effect
287         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
288
289         // Prepare sub-devices for clock drift compensation
290         // Workaround for bug in the HAL : until 10.6.2
291         if (need_clock_drift_compensation) {
292
293                 AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
294                 AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
295                 UInt32 theQualifierDataSize = sizeof(AudioObjectID);
296                 AudioClassID inClass = kAudioSubDeviceClassID;
297                 void* theQualifierData = &inClass;
298                 UInt32 subDevicesNum = 0;
299
300 #ifndef NDEBUG
301                 printf("Clock drift compensation activated...\n");
302 #endif
303
304                 // Get the property data size
305                 err = AudioObjectGetPropertyDataSize(*created_device, &theAddressOwned, theQualifierDataSize, theQualifierData, &size);
306                 if (err != noErr) {
307                         fprintf(stderr, "AggregateDevice: kAudioObjectPropertyOwnedObjects error\n");
308                 }
309
310                 //      Calculate the number of object IDs
311                 subDevicesNum = size / sizeof(AudioObjectID);
312 #ifndef NDEBUG
313                 printf("AggregateDevice: clock drift compensation, number of sub-devices = %u\n", (unsigned int)subDevicesNum);
314 #endif
315                 AudioObjectID subDevices[subDevicesNum];
316                 size = sizeof(subDevices);
317
318                 err = AudioObjectGetPropertyData(*created_device, &theAddressOwned, theQualifierDataSize, theQualifierData, &size, subDevices);
319                 if (err != noErr) {
320                         fprintf(stderr, "AggregateDevice: kAudioObjectPropertyOwnedObjects error\n");
321                 }
322
323                 // Set kAudioSubDevicePropertyDriftCompensation property...
324                 for (UInt32 index = 0; index < subDevicesNum; ++index) {
325                         UInt32 theDriftCompensationValue = 1;
326                         err = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
327                         if (err != noErr) {
328                                 fprintf(stderr, "AggregateDevice: kAudioSubDevicePropertyDriftCompensation error\n");
329                         }
330                 }
331         }
332
333         // pause again to give the changes time to take effect
334         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
335
336         //----------
337         // Clean up
338         //----------
339
340         // release the private AD key
341         CFRelease(AggregateDeviceNumberRef);
342
343         // release the CF objects we have created - we don't need them any more
344         CFRelease(aggDeviceDict);
345         CFRelease(subDevicesArray);
346
347         // release the device UID
348         for (size_t i = 0; i < captureDeviceUID.size(); ++i) {
349                 CFRelease(captureDeviceUID[i]);
350         }
351
352         for (size_t i = 0; i < playbackDeviceUID.size(); ++i) {
353                 CFRelease(playbackDeviceUID[i]);
354         }
355
356 #ifndef NDEBUG
357         printf("AggregateDevice: new aggregate device %u\n", (unsigned int)*created_device);
358 #endif
359         return 0;
360
361 error:
362         destroy_aggregate_device();
363         return -1;
364 }