do not try to categorize AU plugins based on the "subtype" property, since that is...
[ardour2.git] / libs / ardour / audio_unit.cc
blobf8d9698c39faeaab2641fe8607c9a2367e754af9
1 /*
2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
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.
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.
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.
21 #include <sstream>
22 #include <errno.h>
23 #include <string.h>
24 #include <math.h>
25 #include <ctype.h>
27 #include <pbd/transmitter.h>
28 #include <pbd/xml++.h>
29 #include <pbd/whitespace.h>
30 #include <pbd/pathscanner.h>
31 #include <pbd/localeguard.h>
33 #include <glibmm/thread.h>
34 #include <glibmm/fileutils.h>
35 #include <glibmm/miscutils.h>
37 #include <ardour/ardour.h>
38 #include <ardour/audioengine.h>
39 #include <ardour/io.h>
40 #include <ardour/audio_unit.h>
41 #include <ardour/session.h>
42 #include <ardour/tempo.h>
43 #include <ardour/utils.h>
45 #include <appleutility/CAAudioUnit.h>
46 #include <appleutility/CAAUParameter.h>
48 #include <CoreFoundation/CoreFoundation.h>
49 #include <CoreServices/CoreServices.h>
50 #include <AudioUnit/AudioUnit.h>
51 #include <AudioToolbox/AudioUnitUtilities.h>
53 #include "i18n.h"
55 using namespace std;
56 using namespace PBD;
57 using namespace ARDOUR;
59 //#define TRACE_AU_API
60 #ifdef TRACE_AU_API
61 #define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
62 #else
63 #define TRACE_API(fmt,...)
64 #endif
66 #ifndef AU_STATE_SUPPORT
67 static bool seen_get_state_message = false;
68 static bool seen_set_state_message = false;
69 static bool seen_loading_message = false;
70 static bool seen_saving_message = false;
71 #endif
73 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
75 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
76 static string preset_suffix = ".aupreset";
77 static bool preset_search_path_initialized = false;
78 static bool debug_io_config = true;
80 static OSStatus
81 _render_callback(void *userData,
82 AudioUnitRenderActionFlags *ioActionFlags,
83 const AudioTimeStamp *inTimeStamp,
84 UInt32 inBusNumber,
85 UInt32 inNumberFrames,
86 AudioBufferList* ioData)
88 if (userData) {
89 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
91 return paramErr;
94 static OSStatus
95 _get_beat_and_tempo_callback (void* userData,
96 Float64* outCurrentBeat,
97 Float64* outCurrentTempo)
99 if (userData) {
100 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
103 return paramErr;
106 static OSStatus
107 _get_musical_time_location_callback (void * userData,
108 UInt32 * outDeltaSampleOffsetToNextBeat,
109 Float32 * outTimeSig_Numerator,
110 UInt32 * outTimeSig_Denominator,
111 Float64 * outCurrentMeasureDownBeat)
113 if (userData) {
114 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
115 outTimeSig_Numerator,
116 outTimeSig_Denominator,
117 outCurrentMeasureDownBeat);
119 return paramErr;
122 static OSStatus
123 _get_transport_state_callback (void* userData,
124 Boolean* outIsPlaying,
125 Boolean* outTransportStateChanged,
126 Float64* outCurrentSampleInTimeLine,
127 Boolean* outIsCycling,
128 Float64* outCycleStartBeat,
129 Float64* outCycleEndBeat)
131 if (userData) {
132 return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
133 outCurrentSampleInTimeLine, outIsCycling,
134 outCycleStartBeat, outCycleEndBeat);
136 return paramErr;
140 static int
141 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
144 CFDataRef xmlData;
145 int fd;
147 // Convert the property list into XML data.
149 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
151 if (!xmlData) {
152 error << _("Could not create XML version of property list") << endmsg;
153 return -1;
156 // Write the XML data to the file.
158 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
159 while (fd < 0) {
160 if (errno == EEXIST) {
161 /* tell any UI's that this file already exists and ask them what to do */
162 bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
163 if (overwrite) {
164 fd = open (path.c_str(), O_WRONLY, 0664);
165 continue;
166 } else {
167 return 0;
170 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
171 CFRelease (xmlData);
172 return -1;
175 size_t cnt = CFDataGetLength (xmlData);
177 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
178 CFRelease (xmlData);
179 close (fd);
180 return -1;
183 close (fd);
184 return 0;
188 static CFPropertyListRef
189 load_property_list (Glib::ustring path)
191 int fd;
192 CFPropertyListRef propertyList;
193 CFDataRef xmlData;
194 CFStringRef errorString;
196 // Read the XML file.
198 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
199 return propertyList;
203 off_t len = lseek (fd, 0, SEEK_END);
204 char* buf = new char[len];
205 lseek (fd, 0, SEEK_SET);
207 if (read (fd, buf, len) != len) {
208 delete [] buf;
209 close (fd);
210 return propertyList;
213 close (fd);
215 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
217 // Reconstitute the dictionary using the XML data.
219 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
220 xmlData,
221 kCFPropertyListImmutable,
222 &errorString);
224 CFRelease (xmlData);
225 delete [] buf;
227 return propertyList;
230 //-----------------------------------------------------------------------------
231 static void
232 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
234 if (!plist) {
235 return;
237 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
239 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
240 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
243 CFRelease (pn);
246 //-----------------------------------------------------------------------------
247 static std::string
248 get_preset_name_in_plist (CFPropertyListRef plist)
250 std::string ret;
252 if (!plist) {
253 return ret;
256 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
257 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
258 if (p) {
259 CFStringRef str = (CFStringRef) p;
260 int len = CFStringGetLength(str);
261 len = (len * 2) + 1;
262 char local_buffer[len];
263 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
264 ret = local_buffer;
268 return ret;
271 //--------------------------------------------------------------------------
272 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
273 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
274 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
275 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
277 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
278 return FALSE;
280 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
281 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
283 // only sub-type and manufacturer IDs need to be equal
284 if (inIgnoreType)
285 return TRUE;
286 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
287 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
288 return TRUE;
291 return FALSE;
294 //--------------------------------------------------------------------------
295 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
296 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
297 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
298 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
300 OSErr status;
301 ComponentDescription desc;
303 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
304 return FALSE;
306 // get the ComponentDescription of the input Component
307 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
308 if (status != noErr)
309 return FALSE;
311 // check if the Component's ComponentDescription matches the input ComponentDescription
312 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
315 //--------------------------------------------------------------------------
316 // determine if 2 ComponentDescriptions are basically equal
317 // (by that, I mean that the important identifying values are compared,
318 // but not the ComponentDescription flags)
319 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
321 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
324 //--------------------------------------------------------------------------
325 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
326 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
328 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
331 //--------------------------------------------------------------------------
332 // determine if a ComponentDescription basically matches that of a particular Component
333 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
335 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
338 //--------------------------------------------------------------------------
339 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
340 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
342 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
346 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
347 : Plugin (engine, session)
348 , comp (_comp)
349 , unit (new CAAudioUnit)
350 , initialized (false)
351 , _current_block_size (0)
352 , _requires_fixed_size_buffers (false)
353 , buffers (0)
354 , current_maxbuf (0)
355 , current_offset (0)
356 , current_buffers (0)
357 , frames_processed (0)
358 , last_transport_rolling (false)
359 , last_transport_speed (0.0)
361 if (!preset_search_path_initialized) {
362 Glib::ustring p = Glib::get_home_dir();
363 p += "/Library/Audio/Presets:";
364 p += preset_search_path;
365 preset_search_path = p;
366 preset_search_path_initialized = true;
369 init ();
372 AUPlugin::AUPlugin (const AUPlugin& other)
373 : Plugin (other)
374 , comp (other.get_comp())
375 , unit (new CAAudioUnit)
376 , initialized (false)
377 , _current_block_size (0)
378 , _last_nframes (0)
379 , _requires_fixed_size_buffers (false)
380 , buffers (0)
381 , current_maxbuf (0)
382 , current_offset (0)
383 , current_buffers (0)
384 , frames_processed (0)
387 init ();
390 AUPlugin::~AUPlugin ()
392 if (unit) {
393 TRACE_API ("about to call uninitialize in plugin destructor\n");
394 unit->Uninitialize ();
397 if (buffers) {
398 free (buffers);
402 void
403 AUPlugin::discover_factory_presets ()
405 CFArrayRef presets;
406 UInt32 dataSize = sizeof (presets);
407 OSStatus err;
409 TRACE_API ("get property FactoryPresets in global scope\n");
410 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
411 cerr << "cannot get factory preset info: " << err << endl;
412 return;
415 if (!presets) {
416 return;
419 CFIndex cnt = CFArrayGetCount (presets);
421 for (CFIndex i = 0; i < cnt; ++i) {
422 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
424 string name = CFStringRefToStdString (preset->presetName);
425 factory_preset_map[name] = preset->presetNumber;
428 CFRelease (presets);
431 void
432 AUPlugin::init ()
434 OSErr err;
436 try {
437 TRACE_API ("opening AudioUnit\n");
438 err = CAAudioUnit::Open (*(comp.get()), *unit);
439 } catch (...) {
440 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
441 throw failed_constructor();
444 if (err != noErr) {
445 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
446 throw failed_constructor ();
449 AURenderCallbackStruct renderCallbackInfo;
451 renderCallbackInfo.inputProc = _render_callback;
452 renderCallbackInfo.inputProcRefCon = this;
454 TRACE_API ("set render callback in input scope\n");
455 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
456 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
457 cerr << "cannot install render callback (err = " << err << ')' << endl;
458 throw failed_constructor();
461 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
463 HostCallbackInfo info;
464 memset (&info, 0, sizeof (HostCallbackInfo));
465 info.hostUserData = this;
466 info.beatAndTempoProc = _get_beat_and_tempo_callback;
467 info.musicalTimeLocationProc = _get_musical_time_location_callback;
468 info.transportStateProc = _get_transport_state_callback;
470 //ignore result of this - don't care if the property isn't supported
471 TRACE_API ("set host callbacks in global scope\n");
472 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
473 kAudioUnitScope_Global,
474 0, //elementID
475 &info,
476 sizeof (HostCallbackInfo));
478 TRACE_API ("count global elements\n");
479 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
480 TRACE_API ("count input elements\n");
481 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
482 TRACE_API ("count output elements\n");
483 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
485 /* these keep track of *configured* channel set up,
486 not potential set ups.
489 input_channels = -1;
490 output_channels = -1;
492 if (set_block_size (_session.get_block_size())) {
493 error << _("AUPlugin: cannot set processing block size") << endmsg;
494 throw failed_constructor();
497 discover_parameters ();
498 discover_factory_presets ();
500 Plugin::setup_controls ();
503 void
504 AUPlugin::discover_parameters ()
506 /* discover writable parameters */
508 AudioUnitScope scopes[] = {
509 kAudioUnitScope_Global,
510 kAudioUnitScope_Output,
511 kAudioUnitScope_Input
514 descriptors.clear ();
516 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
518 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
520 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
522 AUParameterDescriptor d;
524 d.id = param_info.ParamID (i);
526 const CAAUParameter* param = param_info.GetParamInfo (d.id);
527 const AudioUnitParameterInfo& info (param->ParamInfo());
529 const int len = CFStringGetLength (param->GetName());;
530 char local_buffer[len*2];
531 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
532 if (!good) {
533 d.label = "???";
534 } else {
535 d.label = local_buffer;
538 d.scope = param_info.GetScope ();
539 d.element = param_info.GetElement ();
541 /* info.units to consider */
543 kAudioUnitParameterUnit_Generic = 0
544 kAudioUnitParameterUnit_Indexed = 1
545 kAudioUnitParameterUnit_Boolean = 2
546 kAudioUnitParameterUnit_Percent = 3
547 kAudioUnitParameterUnit_Seconds = 4
548 kAudioUnitParameterUnit_SampleFrames = 5
549 kAudioUnitParameterUnit_Phase = 6
550 kAudioUnitParameterUnit_Rate = 7
551 kAudioUnitParameterUnit_Hertz = 8
552 kAudioUnitParameterUnit_Cents = 9
553 kAudioUnitParameterUnit_RelativeSemiTones = 10
554 kAudioUnitParameterUnit_MIDINoteNumber = 11
555 kAudioUnitParameterUnit_MIDIController = 12
556 kAudioUnitParameterUnit_Decibels = 13
557 kAudioUnitParameterUnit_LinearGain = 14
558 kAudioUnitParameterUnit_Degrees = 15
559 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
560 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
561 kAudioUnitParameterUnit_Pan = 18
562 kAudioUnitParameterUnit_Meters = 19
563 kAudioUnitParameterUnit_AbsoluteCents = 20
564 kAudioUnitParameterUnit_Octaves = 21
565 kAudioUnitParameterUnit_BPM = 22
566 kAudioUnitParameterUnit_Beats = 23
567 kAudioUnitParameterUnit_Milliseconds = 24
568 kAudioUnitParameterUnit_Ratio = 25
571 /* info.flags to consider */
575 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
576 kAudioUnitParameterFlag_HasClump = (1L << 20)
577 kAudioUnitParameterFlag_HasName = (1L << 21)
578 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
579 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
580 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
581 kAudioUnitParameterFlag_CanRamp = (1L << 25)
582 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
583 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
584 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
585 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
586 kAudioUnitParameterFlag_IsReadable = (1L << 30)
587 kAudioUnitParameterFlag_IsWritable = (1L << 31)
590 d.lower = info.minValue;
591 d.upper = info.maxValue;
592 d.default_value = info.defaultValue;
594 d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
595 d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean) ||
596 (d.integer_step && ((d.upper - d.lower) == 1.0));
597 d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
598 d.automatable = !d.toggled &&
599 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
600 (info.flags & kAudioUnitParameterFlag_IsWritable);
602 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
603 d.unit = info.unit;
605 d.step = 1.0;
606 d.smallstep = 0.1;
607 d.largestep = 10.0;
608 d.min_unbound = 0; // lower is bound
609 d.max_unbound = 0; // upper is bound
611 descriptors.push_back (d);
617 static unsigned int
618 four_ints_to_four_byte_literal (unsigned char n[4])
620 /* this is actually implementation dependent. sigh. this is what gcc
621 and quite a few others do.
623 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
626 std::string
627 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
629 if (isdigit (id[0])) {
630 return id;
633 /* ID format is xxxx-xxxx-xxxx
634 where x maybe \xNN or a printable character.
636 Split at the '-' and and process each part into an integer.
637 Then put it back together.
641 unsigned char nascent[4];
642 const char* cstr = id.c_str();
643 const char* estr = cstr + id.size();
644 uint32_t n[3];
645 int in;
646 int next_int;
647 char short_buf[3];
648 stringstream s;
650 in = 0;
651 next_int = 0;
652 short_buf[2] = '\0';
654 while (*cstr && next_int < 4) {
656 if (*cstr == '\\') {
658 if (estr - cstr < 3) {
660 /* too close to the end for \xNN parsing: treat as literal characters */
662 cerr << "Parse " << cstr << " as a literal \\" << endl;
663 nascent[in] = *cstr;
664 ++cstr;
665 ++in;
667 } else {
669 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
671 /* parse \xNN */
673 memcpy (short_buf, &cstr[2], 2);
674 nascent[in] = strtol (short_buf, NULL, 16);
675 cstr += 4;
676 ++in;
678 } else {
680 /* treat as literal characters */
681 cerr << "Parse " << cstr << " as a literal \\" << endl;
682 nascent[in] = *cstr;
683 ++cstr;
684 ++in;
688 } else {
690 nascent[in] = *cstr;
691 ++cstr;
692 ++in;
695 if (in && (in % 4 == 0)) {
696 /* nascent is ready */
697 n[next_int] = four_ints_to_four_byte_literal (nascent);
698 in = 0;
699 next_int++;
701 /* swallow space-hyphen-space */
703 if (next_int < 3) {
704 ++cstr;
705 ++cstr;
706 ++cstr;
711 if (next_int != 3) {
712 goto err;
715 s << n[0] << '-' << n[1] << '-' << n[2];
717 return s.str();
719 err:
720 return string();
723 string
724 AUPlugin::unique_id () const
726 return AUPluginInfo::stringify_descriptor (comp->Desc());
729 const char *
730 AUPlugin::label () const
732 return _info->name.c_str();
735 uint32_t
736 AUPlugin::parameter_count () const
738 return descriptors.size();
741 float
742 AUPlugin::default_value (uint32_t port)
744 if (port < descriptors.size()) {
745 return descriptors[port].default_value;
748 return 0;
751 nframes_t
752 AUPlugin::latency () const
754 return unit->Latency() * _session.frame_rate();
757 void
758 AUPlugin::set_parameter (uint32_t which, float val)
760 if (which < descriptors.size()) {
761 const AUParameterDescriptor& d (descriptors[which]);
762 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d.id, d.scope, d.element, val);
763 unit->SetParameter (d.id, d.scope, d.element, val);
765 /* tell the world what we did */
767 AudioUnitEvent theEvent;
769 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
770 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
771 theEvent.mArgument.mParameter.mParameterID = d.id;
772 theEvent.mArgument.mParameter.mScope = d.scope;
773 theEvent.mArgument.mParameter.mElement = d.element;
775 TRACE_API ("notify about parameter change\n");
776 AUEventListenerNotify (NULL, NULL, &theEvent);
780 float
781 AUPlugin::get_parameter (uint32_t which) const
783 float val = 0.0;
784 if (which < descriptors.size()) {
785 const AUParameterDescriptor& d (descriptors[which]);
786 TRACE_API ("get value of parameter %d in scope %d element %d\n", d.id, d.scope, d.element);
787 unit->GetParameter(d.id, d.scope, d.element, val);
789 return val;
793 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
795 if (which < descriptors.size()) {
796 pd = descriptors[which];
797 return 0;
799 return -1;
802 uint32_t
803 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
805 if (which < descriptors.size()) {
806 ok = true;
807 return which;
809 ok = false;
810 return 0;
813 void
814 AUPlugin::activate ()
816 if (!initialized) {
817 OSErr err;
818 TRACE_API ("call Initialize in activate()\n");
819 if ((err = unit->Initialize()) != noErr) {
820 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
821 } else {
822 frames_processed = 0;
823 initialized = true;
828 void
829 AUPlugin::deactivate ()
831 TRACE_API ("call Uninitialize in deactivate()\n");
832 unit->Uninitialize ();
833 initialized = false;
836 void
837 AUPlugin::flush ()
839 TRACE_API ("call Reset in flush()\n");
840 unit->GlobalReset ();
843 bool
844 AUPlugin::requires_fixed_size_buffers() const
846 return _requires_fixed_size_buffers;
851 AUPlugin::set_block_size (nframes_t nframes)
853 bool was_initialized = initialized;
854 UInt32 numFrames = nframes;
855 OSErr err;
857 if (initialized) {
858 deactivate ();
861 TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
862 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
863 0, &numFrames, sizeof (numFrames))) != noErr) {
864 cerr << "cannot set max frames (err = " << err << ')' << endl;
865 return -1;
868 if (was_initialized) {
869 activate ();
872 _current_block_size = nframes;
874 return 0;
877 int32_t
878 AUPlugin::configure_io (int32_t in, int32_t out)
880 AudioStreamBasicDescription streamFormat;
881 bool was_initialized = initialized;
883 if (initialized) {
884 //if we are already running with the requested i/o config, bail out here
885 if ( (in==input_channels) && (out==output_channels) ) {
886 return 0;
887 } else {
888 deactivate ();
892 streamFormat.mSampleRate = _session.frame_rate();
893 streamFormat.mFormatID = kAudioFormatLinearPCM;
894 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
896 #ifdef __LITTLE_ENDIAN__
897 /* relax */
898 #else
899 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
900 #endif
902 streamFormat.mBitsPerChannel = 32;
903 streamFormat.mFramesPerPacket = 1;
905 /* apple says that for non-interleaved data, these
906 values always refer to a single channel.
908 streamFormat.mBytesPerPacket = 4;
909 streamFormat.mBytesPerFrame = 4;
911 streamFormat.mChannelsPerFrame = in;
913 if (set_input_format (streamFormat) != 0) {
914 return -1;
917 streamFormat.mChannelsPerFrame = out;
919 if (set_output_format (streamFormat) != 0) {
920 return -1;
923 int ret = Plugin::configure_io (in, out);
925 if (ret == 0) {
926 if (was_initialized) {
927 activate ();
931 return ret;
934 int32_t
935 AUPlugin::can_do (int32_t in, int32_t& out)
937 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
938 // attempt to multiply-instantiate plugins to meet io configurations.
940 int32_t plugcnt = -1;
941 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
943 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
945 if (debug_io_config) {
946 cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
949 //Ardour expects the plugin to tell it the output configuration
950 //but AU plugins can have multiple I/O configurations
951 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
952 //so first lets see if there's a configuration that keeps out==in
953 out = in;
954 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
955 int32_t possible_in = i->first;
956 int32_t possible_out = i->second;
958 if (possible_in == in && possible_out== out) {
959 cerr << "\tCHOSEN: in " << in << " out " << out << endl;
960 return 1;
964 /* now allow potentially "imprecise" matches */
965 out = -1;
966 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
968 int32_t possible_in = i->first;
969 int32_t possible_out = i->second;
971 if (debug_io_config) {
972 cerr << "\tin " << possible_in << " out " << possible_out << endl;
975 if (possible_out == 0) {
976 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
977 continue;
980 if (possible_in == 0) {
982 /* instrument plugin, always legal but throws away inputs ...
985 if (possible_out == -1) {
986 /* out much match in (UNLIKELY!!) */
987 out = in;
988 plugcnt = 1;
989 } else if (possible_out == -2) {
990 /* any configuration possible, pick matching */
991 out = in;
992 plugcnt = 1;
993 } else if (possible_out < -2) {
994 /* explicit variable number of outputs, pick maximum */
995 out = -possible_out;
996 plugcnt = 1;
997 } else {
998 /* exact number of outputs */
999 out = possible_out;
1000 plugcnt = 1;
1004 if (possible_in == -1) {
1006 /* wildcard for input */
1008 if (possible_out == -1) {
1009 /* out much match in */
1010 out = in;
1011 plugcnt = 1;
1012 } else if (possible_out == -2) {
1013 /* any configuration possible, pick matching */
1014 out = in;
1015 plugcnt = 1;
1016 } else if (possible_out < -2) {
1017 /* explicit variable number of outputs, pick maximum */
1018 out = -possible_out;
1019 plugcnt = 1;
1020 } else {
1021 /* exact number of outputs */
1022 out = possible_out;
1023 plugcnt = 1;
1027 if (possible_in == -2) {
1029 if (possible_out == -1) {
1030 /* any configuration possible, pick matching */
1031 out = in;
1032 plugcnt = 1;
1033 } else if (possible_out == -2) {
1034 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1035 << endmsg;
1036 plugcnt = -1;
1037 } else if (possible_out < -2) {
1038 /* explicit variable number of outputs, pick maximum */
1039 out = -possible_out;
1040 plugcnt = 1;
1041 } else {
1042 /* exact number of outputs */
1043 out = possible_out;
1044 plugcnt = 1;
1048 if (possible_in < -2) {
1050 /* explicit variable number of inputs */
1052 if (in > -possible_in) {
1053 /* request is too large */
1054 plugcnt = -1;
1057 if (possible_out == -1) {
1058 /* out must match in */
1059 out = in;
1060 plugcnt = 1;
1061 } else if (possible_out == -2) {
1062 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1063 << endmsg;
1064 plugcnt = -1;
1065 } else if (possible_out < -2) {
1066 /* explicit variable number of outputs, pick maximum */
1067 out = -possible_out;
1068 plugcnt = 1;
1069 } else {
1070 /* exact number of outputs */
1071 out = possible_out;
1072 plugcnt = 1;
1076 if (possible_in == in) {
1078 /* exact number of inputs ... must match obviously */
1080 if (possible_out == -1) {
1081 /* out must match in */
1082 out = in;
1083 plugcnt = 1;
1084 } else if (possible_out == -2) {
1085 /* any output configuration, pick matching */
1086 out = in;
1087 plugcnt = -1;
1088 } else if (possible_out < -2) {
1089 /* explicit variable number of outputs, pick maximum */
1090 out = -possible_out;
1091 plugcnt = 1;
1092 } else {
1093 /* exact number of outputs */
1094 out = possible_out;
1095 plugcnt = 1;
1099 if (plugcnt == 1) {
1100 break;
1105 if (debug_io_config) {
1106 if (plugcnt > 0) {
1107 cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
1108 } else {
1109 cerr << "\tFAIL: no configs match requested in " << in << endl;
1113 return plugcnt;
1117 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1119 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1123 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1125 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1126 return -1;
1129 if (buffers) {
1130 free (buffers);
1131 buffers = 0;
1134 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1135 fmt.mChannelsPerFrame * sizeof(AudioBuffer));
1137 Glib::Mutex::Lock em (_session.engine().process_lock());
1138 IO::MoreOutputs (fmt.mChannelsPerFrame);
1140 return 0;
1144 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1146 OSErr result;
1148 for (uint32_t i = 0; i < cnt; ++i) {
1149 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1150 (scope == kAudioUnitScope_Input ? "input" : "output"),
1151 scope, cnt);
1152 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1153 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1154 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1155 return -1;
1159 if (scope == kAudioUnitScope_Input) {
1160 input_channels = fmt.mChannelsPerFrame;
1161 } else {
1162 output_channels = fmt.mChannelsPerFrame;
1165 return 0;
1168 uint32_t
1169 AUPlugin::input_streams() const
1171 if (input_channels < 0) {
1172 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
1173 return 1;
1175 return input_channels;
1179 uint32_t
1180 AUPlugin::output_streams() const
1182 if (output_channels < 0) {
1183 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
1184 return 1;
1186 return output_channels;
1189 OSStatus
1190 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
1191 const AudioTimeStamp *inTimeStamp,
1192 UInt32 inBusNumber,
1193 UInt32 inNumberFrames,
1194 AudioBufferList* ioData)
1196 /* not much to do - the data is already in the buffers given to us in connect_and_run() */
1198 if (current_maxbuf == 0) {
1199 error << _("AUPlugin: render callback called illegally!") << endmsg;
1200 return kAudioUnitErr_CannotDoInCurrentContext;
1202 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
1203 for (uint32_t i = 0; i < limit; ++i) {
1204 ioData->mBuffers[i].mNumberChannels = 1;
1205 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1206 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
1207 // cerr << "chn " << i << " rendering from " << ioData->mBuffers[i].mData << endl;
1210 cb_offset += inNumberFrames;
1212 return noErr;
1216 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
1218 AudioUnitRenderActionFlags flags = 0;
1219 AudioTimeStamp ts;
1220 OSErr err;
1222 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1223 unit->GlobalReset();
1224 _last_nframes = nframes;
1227 current_buffers = &bufs;
1228 current_maxbuf = maxbuf;
1229 current_offset = offset;
1230 cb_offset = 0;
1232 buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
1234 for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
1235 buffers->mBuffers[i].mNumberChannels = 1;
1236 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1237 buffers->mBuffers[i].mData = 0;
1240 ts.mSampleTime = frames_processed;
1241 ts.mFlags = kAudioTimeStampSampleTimeValid;
1243 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1245 current_maxbuf = 0;
1246 frames_processed += nframes;
1248 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1249 uint32_t i;
1251 for (i = 0; i < limit; ++i) {
1252 if (bufs[i] + offset != buffers->mBuffers[i].mData) {
1253 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1254 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1258 /* now silence any buffers that were passed in but the that the plugin
1259 did not fill/touch/use.
1262 for (;i < maxbuf; ++i) {
1263 memset (bufs[i]+offset, 0, nframes * sizeof (Sample));
1266 return 0;
1269 // cerr << name() << " render error " << err << endl;
1271 return -1;
1274 OSStatus
1275 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1276 Float64* outCurrentTempo)
1278 TempoMap& tmap (_session.tempo_map());
1280 TRACE_API ("AU calls ardour beat&tempo callback\n");
1282 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1283 (and interpretation) of a beat position will be incorrect. So refuse to
1284 offer the value.
1287 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1288 return kAudioUnitErr_CannotDoInCurrentContext;
1291 BBT_Time bbt;
1292 TempoMap::Metric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1293 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1295 if (outCurrentBeat) {
1296 float beat;
1297 beat = metric.meter().beats_per_bar() * bbt.bars;
1298 beat += bbt.beats;
1299 beat += bbt.ticks / Meter::ticks_per_beat;
1300 *outCurrentBeat = beat;
1303 if (outCurrentTempo) {
1304 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1307 return noErr;
1311 OSStatus
1312 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1313 Float32* outTimeSig_Numerator,
1314 UInt32* outTimeSig_Denominator,
1315 Float64* outCurrentMeasureDownBeat)
1317 TempoMap& tmap (_session.tempo_map());
1319 TRACE_API ("AU calls ardour music time location callback\n");
1321 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1322 (and interpretation) of a beat position will be incorrect. So refuse to
1323 offer the value.
1326 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1327 return kAudioUnitErr_CannotDoInCurrentContext;
1330 BBT_Time bbt;
1331 TempoMap::Metric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1332 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1334 if (outDeltaSampleOffsetToNextBeat) {
1335 if (bbt.ticks == 0) {
1336 /* on the beat */
1337 *outDeltaSampleOffsetToNextBeat = 0;
1338 } else {
1339 *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((Meter::ticks_per_beat - bbt.ticks)/Meter::ticks_per_beat) * // fraction of a beat to next beat
1340 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1344 if (outTimeSig_Numerator) {
1345 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1347 if (outTimeSig_Denominator) {
1348 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1351 if (outCurrentMeasureDownBeat) {
1353 /* beat for the start of the bar.
1354 1|1|0 -> 1
1355 2|1|0 -> 1 + beats_per_bar
1356 3|1|0 -> 1 + (2 * beats_per_bar)
1357 etc.
1360 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1363 return noErr;
1366 OSStatus
1367 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1368 Boolean* outTransportStateChanged,
1369 Float64* outCurrentSampleInTimeLine,
1370 Boolean* outIsCycling,
1371 Float64* outCycleStartBeat,
1372 Float64* outCycleEndBeat)
1374 bool rolling;
1375 float speed;
1377 TRACE_API ("AU calls ardour transport state callback\n");
1379 rolling = _session.transport_rolling();
1380 speed = _session.transport_speed ();
1382 if (outIsPlaying) {
1383 *outIsPlaying = _session.transport_rolling();
1386 if (outTransportStateChanged) {
1387 if (rolling != last_transport_rolling) {
1388 *outTransportStateChanged = true;
1389 } else if (speed != last_transport_speed) {
1390 *outTransportStateChanged = true;
1391 } else {
1392 *outTransportStateChanged = false;
1396 if (outCurrentSampleInTimeLine) {
1397 /* this assumes that the AU can only call this host callback from render context,
1398 where current_offset is valid.
1400 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1403 if (outIsCycling) {
1404 Location* loc = _session.locations()->auto_loop_location();
1406 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1408 if (*outIsCycling) {
1410 if (outCycleStartBeat || outCycleEndBeat) {
1412 TempoMap& tmap (_session.tempo_map());
1414 /* more than 1 meter means that a simplistic computation (and interpretation) of
1415 a beat position will be incorrect. so refuse to offer the value.
1418 if (tmap.n_meters() > 1) {
1419 return kAudioUnitErr_CannotDoInCurrentContext;
1422 BBT_Time bbt;
1424 if (outCycleStartBeat) {
1425 TempoMap::Metric metric = tmap.metric_at (loc->start() + current_offset);
1426 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1428 float beat;
1429 beat = metric.meter().beats_per_bar() * bbt.bars;
1430 beat += bbt.beats;
1431 beat += bbt.ticks / Meter::ticks_per_beat;
1433 *outCycleStartBeat = beat;
1436 if (outCycleEndBeat) {
1437 TempoMap::Metric metric = tmap.metric_at (loc->end() + current_offset);
1438 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1440 float beat;
1441 beat = metric.meter().beats_per_bar() * bbt.bars;
1442 beat += bbt.beats;
1443 beat += bbt.ticks / Meter::ticks_per_beat;
1445 *outCycleEndBeat = beat;
1451 last_transport_rolling = rolling;
1452 last_transport_speed = speed;
1454 return noErr;
1457 set<uint32_t>
1458 AUPlugin::automatable() const
1460 set<uint32_t> automates;
1462 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1463 if (descriptors[i].automatable) {
1464 automates.insert (i);
1468 return automates;
1471 string
1472 AUPlugin::describe_parameter (uint32_t param)
1474 return descriptors[param].label;
1477 void
1478 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
1480 // NameValue stuff here
1483 bool
1484 AUPlugin::parameter_is_audio (uint32_t) const
1486 return false;
1489 bool
1490 AUPlugin::parameter_is_control (uint32_t) const
1492 return true;
1495 bool
1496 AUPlugin::parameter_is_input (uint32_t) const
1498 return false;
1501 bool
1502 AUPlugin::parameter_is_output (uint32_t) const
1504 return false;
1507 XMLNode&
1508 AUPlugin::get_state()
1510 LocaleGuard lg (X_("POSIX"));
1511 XMLNode *root = new XMLNode (state_node_name());
1513 #ifdef AU_STATE_SUPPORT
1514 CFDataRef xmlData;
1515 CFPropertyListRef propertyList;
1517 TRACE_API ("get preset state\n");
1518 if (unit->GetAUPreset (propertyList) != noErr) {
1519 return *root;
1522 // Convert the property list into XML data.
1524 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1526 if (!xmlData) {
1527 error << _("Could not create XML version of property list") << endmsg;
1528 return *root;
1531 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1532 our state node. GACK!
1535 XMLTree t;
1537 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1538 if (t.root()) {
1539 root->add_child_copy (*t.root());
1543 CFRelease (xmlData);
1544 CFRelease (propertyList);
1545 #else
1546 if (!seen_get_state_message) {
1547 info << _("Saving AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1548 << endmsg;
1549 seen_get_state_message = true;
1551 #endif
1553 return *root;
1557 AUPlugin::set_state(const XMLNode& node)
1559 #ifdef AU_STATE_SUPPORT
1560 int ret = -1;
1561 CFPropertyListRef propertyList;
1562 LocaleGuard lg (X_("POSIX"));
1564 if (node.name() != state_node_name()) {
1565 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1566 return -1;
1569 if (node.children().empty()) {
1570 return -1;
1573 XMLNode* top = node.children().front();
1574 XMLNode* copy = new XMLNode (*top);
1576 XMLTree t;
1577 t.set_root (copy);
1579 const string& xml = t.write_buffer ();
1580 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1581 CFStringRef errorString;
1583 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1584 xmlData,
1585 kCFPropertyListImmutable,
1586 &errorString);
1588 CFRelease (xmlData);
1590 if (propertyList) {
1591 TRACE_API ("set preset\n");
1592 if (unit->SetAUPreset (propertyList) == noErr) {
1593 ret = 0;
1595 /* tell the world */
1597 AudioUnitParameter changedUnit;
1598 changedUnit.mAudioUnit = unit->AU();
1599 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1600 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1602 CFRelease (propertyList);
1605 return ret;
1606 #else
1607 if (!seen_set_state_message) {
1608 info << _("Restoring AudioUnit settings is not supported in this build of Ardour. Consider paying for a newer version")
1609 << endmsg;
1611 return 0;
1612 #endif
1615 bool
1616 AUPlugin::load_preset (const string preset_label)
1618 #ifdef AU_STATE_SUPPORT
1619 bool ret = false;
1620 CFPropertyListRef propertyList;
1621 Glib::ustring path;
1622 UserPresetMap::iterator ux;
1623 FactoryPresetMap::iterator fx;
1625 /* look first in "user" presets */
1627 if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
1629 if ((propertyList = load_property_list (ux->second)) != 0) {
1630 TRACE_API ("set preset from user presets\n");
1631 if (unit->SetAUPreset (propertyList) == noErr) {
1632 ret = true;
1634 /* tell the world */
1636 AudioUnitParameter changedUnit;
1637 changedUnit.mAudioUnit = unit->AU();
1638 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1639 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1641 CFRelease(propertyList);
1644 } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
1646 AUPreset preset;
1648 preset.presetNumber = fx->second;
1649 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1651 TRACE_API ("set preset from factory presets\n");
1653 if (unit->SetPresentPreset (preset) == 0) {
1654 ret = true;
1656 /* tell the world */
1658 AudioUnitParameter changedUnit;
1659 changedUnit.mAudioUnit = unit->AU();
1660 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1661 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1665 return ret;
1666 #else
1667 if (!seen_loading_message) {
1668 info << _("Loading AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1669 << endmsg;
1670 seen_loading_message = true;
1672 return true;
1673 #endif
1676 bool
1677 AUPlugin::save_preset (string preset_name)
1679 #ifdef AU_STATE_SUPPORT
1680 CFPropertyListRef propertyList;
1681 vector<Glib::ustring> v;
1682 Glib::ustring user_preset_path;
1683 bool ret = true;
1685 std::string m = maker();
1686 std::string n = name();
1688 strip_whitespace_edges (m);
1689 strip_whitespace_edges (n);
1691 v.push_back (Glib::get_home_dir());
1692 v.push_back ("Library");
1693 v.push_back ("Audio");
1694 v.push_back ("Presets");
1695 v.push_back (m);
1696 v.push_back (n);
1698 user_preset_path = Glib::build_filename (v);
1700 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1701 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1702 return false;
1705 TRACE_API ("get current preset\n");
1706 if (unit->GetAUPreset (propertyList) != noErr) {
1707 return false;
1710 // add the actual preset name */
1712 v.push_back (preset_name + preset_suffix);
1714 // rebuild
1716 user_preset_path = Glib::build_filename (v);
1718 set_preset_name_in_plist (propertyList, preset_name);
1720 if (save_property_list (propertyList, user_preset_path)) {
1721 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1722 ret = false;
1725 CFRelease(propertyList);
1727 return ret;
1728 #else
1729 if (!seen_saving_message) {
1730 info << _("Saving AudioUnit presets is not supported in this build of Ardour. Consider paying for a newer version")
1731 << endmsg;
1732 seen_saving_message = true;
1734 return false;
1735 #endif
1738 //-----------------------------------------------------------------------------
1739 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1740 static SInt32
1741 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1743 CFNumberRef cfNumber;
1744 SInt32 numberValue = 0;
1745 Boolean dummySuccess;
1747 if (outSuccess == NULL)
1748 outSuccess = &dummySuccess;
1749 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1751 *outSuccess = FALSE;
1752 return 0;
1755 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1756 if (cfNumber == NULL)
1758 *outSuccess = FALSE;
1759 return 0;
1761 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1762 if (*outSuccess)
1763 return numberValue;
1764 else
1765 return 0;
1768 static OSStatus
1769 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1771 CFDictionaryRef auStateDictionary;
1772 ComponentDescription tempDesc = {0};
1773 SInt32 versionValue;
1774 Boolean gotValue;
1776 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1777 return paramErr;
1779 // the property list for AU state data must be of the dictionary type
1780 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1781 return kAudioUnitErr_InvalidPropertyValue;
1784 auStateDictionary = (CFDictionaryRef)inAUStateData;
1786 // first check to make sure that the version of the AU state data is one that we know understand
1787 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1788 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1790 if (!gotValue) {
1791 return kAudioUnitErr_InvalidPropertyValue;
1793 #define kCurrentSavedStateVersion 0
1794 if (versionValue != kCurrentSavedStateVersion) {
1795 return kAudioUnitErr_InvalidPropertyValue;
1798 // grab the ComponentDescription values from the AU state data
1799 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1800 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1801 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1802 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1803 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1804 return kAudioUnitErr_InvalidPropertyValue;
1806 *outComponentDescription = tempDesc;
1807 return noErr;
1811 static bool au_preset_filter (const string& str, void* arg)
1813 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1815 bool ret;
1817 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1819 if (ret && arg) {
1821 /* check the preset file path name against this plugin
1822 ID. The idea is that all preset files for this plugin
1823 include "<manufacturer>/<plugin-name>" in their path.
1826 Plugin* p = (Plugin *) arg;
1827 string match = p->maker();
1828 match += '/';
1829 match += p->name();
1831 ret = str.find (match) != string::npos;
1833 if (ret == false) {
1834 string m = p->maker ();
1835 string n = p->name ();
1836 strip_whitespace_edges (m);
1837 strip_whitespace_edges (n);
1838 match = m;
1839 match += '/';
1840 match += n;
1842 ret = str.find (match) != string::npos;
1846 return ret;
1849 bool
1850 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1852 OSStatus status;
1853 CFPropertyListRef plist;
1854 ComponentDescription presetDesc;
1855 bool ret = false;
1857 plist = load_property_list (pathstr);
1859 if (!plist) {
1860 return ret;
1863 // get the ComponentDescription from the AU preset file
1865 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1867 if (status == noErr) {
1868 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1870 /* try to get the preset name from the property list */
1872 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1874 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1876 if (psk) {
1878 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1880 if (!p) {
1881 char buf[PATH_MAX+1];
1883 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1884 preset_name = buf;
1892 CFRelease (plist);
1894 return true;
1897 std::string
1898 AUPlugin::current_preset() const
1900 string preset_name;
1902 #ifdef AU_STATE_SUPPORT
1903 CFPropertyListRef propertyList;
1905 TRACE_API ("get current preset for current_preset()\n");
1906 if (unit->GetAUPreset (propertyList) == noErr) {
1907 preset_name = get_preset_name_in_plist (propertyList);
1908 CFRelease(propertyList);
1910 #endif
1911 return preset_name;
1914 vector<string>
1915 AUPlugin::get_presets ()
1917 vector<string> presets;
1919 #ifdef AU_STATE_SUPPORT
1920 vector<string*>* preset_files;
1921 PathScanner scanner;
1923 user_preset_map.clear ();
1925 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1927 if (!preset_files) {
1928 return presets;
1931 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1933 string path = *(*x);
1934 string preset_name;
1936 /* make an initial guess at the preset name using the path */
1938 preset_name = Glib::path_get_basename (path);
1939 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1941 /* check that this preset file really matches this plugin
1942 and potentially get the "real" preset name from
1943 within the file.
1946 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
1947 user_preset_map[preset_name] = path;
1950 delete *x;
1953 delete preset_files;
1955 /* now fill the vector<string> with the names we have */
1957 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
1958 presets.push_back (i->first);
1961 /* add factory presets */
1963 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
1964 presets.push_back (i->first);
1967 #endif
1969 return presets;
1972 bool
1973 AUPlugin::has_editor () const
1975 // even if the plugin doesn't have its own editor, the AU API can be used
1976 // to create one that looks native.
1977 return true;
1980 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
1981 : descriptor (d)
1983 type = ARDOUR::AudioUnit;
1986 AUPluginInfo::~AUPluginInfo ()
1988 type = ARDOUR::AudioUnit;
1991 PluginPtr
1992 AUPluginInfo::load (Session& session)
1994 try {
1995 PluginPtr plugin;
1997 TRACE_API ("load AU as a component\n");
1998 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2000 if (!comp->IsValid()) {
2001 error << ("AudioUnit: not a valid Component") << endmsg;
2002 } else {
2003 plugin.reset (new AUPlugin (session.engine(), session, comp));
2006 AUPluginInfo *aup = new AUPluginInfo (*this);
2007 plugin->set_info (PluginInfoPtr (aup));
2008 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2009 return plugin;
2012 catch (failed_constructor &err) {
2013 return PluginPtr ();
2017 Glib::ustring
2018 AUPluginInfo::au_cache_path ()
2020 return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
2023 PluginInfoList
2024 AUPluginInfo::discover ()
2026 XMLTree tree;
2028 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2029 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2032 PluginInfoList plugs;
2034 discover_fx (plugs);
2035 discover_music (plugs);
2036 discover_generators (plugs);
2038 return plugs;
2041 void
2042 AUPluginInfo::discover_music (PluginInfoList& plugs)
2044 CAComponentDescription desc;
2045 desc.componentFlags = 0;
2046 desc.componentFlagsMask = 0;
2047 desc.componentSubType = 0;
2048 desc.componentManufacturer = 0;
2049 desc.componentType = kAudioUnitType_MusicEffect;
2051 discover_by_description (plugs, desc);
2054 void
2055 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2057 CAComponentDescription desc;
2058 desc.componentFlags = 0;
2059 desc.componentFlagsMask = 0;
2060 desc.componentSubType = 0;
2061 desc.componentManufacturer = 0;
2062 desc.componentType = kAudioUnitType_Effect;
2064 discover_by_description (plugs, desc);
2067 void
2068 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2070 CAComponentDescription desc;
2071 desc.componentFlags = 0;
2072 desc.componentFlagsMask = 0;
2073 desc.componentSubType = 0;
2074 desc.componentManufacturer = 0;
2075 desc.componentType = kAudioUnitType_Generator;
2077 discover_by_description (plugs, desc);
2080 void
2081 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2083 Component comp = 0;
2085 comp = FindNextComponent (NULL, &desc);
2087 while (comp != NULL) {
2088 CAComponentDescription temp;
2089 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2091 AUPluginInfoPtr info (new AUPluginInfo
2092 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2094 /* although apple designed the subtype field to be a "category" indicator,
2095 its really turned into a plugin ID field for a given manufacturer. Hence
2096 there are no categories for AudioUnits. However, to keep the plugins
2097 showing up under "categories", we'll use the "type" as a high level
2098 selector.
2100 NOTE: no panners, format converters or i/o AU's for our purposes
2103 switch (info->descriptor->Type()) {
2104 case kAudioUnitType_Panner:
2105 case kAudioUnitType_OfflineEffect:
2106 case kAudioUnitType_FormatConverter:
2107 continue;
2109 case kAudioUnitType_Output:
2110 info->category = _("AudioUnit Outputs");
2111 break;
2112 case kAudioUnitType_MusicDevice:
2113 info->category = _("AudioUnit Instruments");
2114 break;
2115 case kAudioUnitType_MusicEffect:
2116 info->category = _("AudioUnit MusicEffects");
2117 break;
2118 case kAudioUnitType_Effect:
2119 info->category = _("AudioUnit Effects");
2120 break;
2121 case kAudioUnitType_Mixer:
2122 info->category = _("AudioUnit Mixers");
2123 break;
2124 case kAudioUnitType_Generator:
2125 info->category = _("AudioUnit Generators");
2126 break;
2127 default:
2128 info->category = _("AudioUnit (Unknown)");
2129 break;
2132 AUPluginInfo::get_names (temp, info->name, info->creator);
2134 info->type = ARDOUR::AudioUnit;
2135 info->unique_id = stringify_descriptor (*info->descriptor);
2137 /* XXX not sure of the best way to handle plugin versioning yet
2140 CAComponent cacomp (*info->descriptor);
2142 if (cacomp.GetResourceVersion (info->version) != noErr) {
2143 info->version = 0;
2146 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2148 /* here we have to map apple's wildcard system to a simple pair
2149 of values. in ::can_do() we use the whole system, but here
2150 we need a single pair of values. XXX probably means we should
2151 remove any use of these values.
2154 info->n_inputs = info->cache.io_configs.front().first;
2155 info->n_outputs = info->cache.io_configs.front().second;
2157 cerr << "detected AU: " << info->name.c_str() << " (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
2159 plugs.push_back (info);
2161 } else {
2162 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2165 comp = FindNextComponent (comp, &desc);
2169 bool
2170 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2171 UInt32 version,
2172 CAComponent& comp,
2173 AUPluginCachedInfo& cinfo,
2174 const std::string& name)
2176 std::string id;
2177 char buf[32];
2179 /* concatenate unique ID with version to provide a key for cached info lookup.
2180 this ensures we don't get stale information, or should if plugin developers
2181 follow Apple "guidelines".
2184 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2185 id = unique_id;
2186 id += '/';
2187 id += buf;
2189 CachedInfoMap::iterator cim = cached_info.find (id);
2191 if (cim != cached_info.end()) {
2192 cinfo = cim->second;
2193 return true;
2196 CAAudioUnit unit;
2197 AUChannelInfo* channel_info;
2198 UInt32 cnt;
2199 int ret;
2201 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2203 try {
2205 if (CAAudioUnit::Open (comp, unit) != noErr) {
2206 return false;
2209 } catch (...) {
2211 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2212 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
2213 return false;
2217 TRACE_API ("get AU channel info\n");
2218 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2219 return false;
2222 if (ret > 0) {
2223 /* no explicit info available */
2225 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2227 } else {
2229 /* store each configuration */
2231 for (uint32_t n = 0; n < cnt; ++n) {
2232 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2233 channel_info[n].outChannels));
2236 free (channel_info);
2239 add_cached_info (id, cinfo);
2240 save_cached_info ();
2242 return true;
2245 void
2246 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2248 cached_info[id] = cinfo;
2251 #define AU_CACHE_VERSION "2.0"
2253 void
2254 AUPluginInfo::save_cached_info ()
2256 XMLNode* node;
2258 node = new XMLNode (X_("AudioUnitPluginCache"));
2259 node->add_property( "version", AU_CACHE_VERSION );
2261 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2262 XMLNode* parent = new XMLNode (X_("plugin"));
2263 parent->add_property ("id", i->first);
2264 node->add_child_nocopy (*parent);
2266 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2268 XMLNode* child = new XMLNode (X_("io"));
2269 char buf[32];
2271 snprintf (buf, sizeof (buf), "%d", j->first);
2272 child->add_property (X_("in"), buf);
2273 snprintf (buf, sizeof (buf), "%d", j->second);
2274 child->add_property (X_("out"), buf);
2275 parent->add_child_nocopy (*child);
2280 Glib::ustring path = au_cache_path ();
2281 XMLTree tree;
2283 tree.set_root (node);
2285 if (!tree.write (path)) {
2286 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2287 unlink (path.c_str());
2292 AUPluginInfo::load_cached_info ()
2294 Glib::ustring path = au_cache_path ();
2295 XMLTree tree;
2297 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2298 return 0;
2301 if ( !tree.read (path) ) {
2302 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2303 return -1;
2306 const XMLNode* root (tree.root());
2308 if (root->name() != X_("AudioUnitPluginCache")) {
2309 return -1;
2312 //initial version has incorrectly stored i/o info, and/or garbage chars.
2313 const XMLProperty* version = root->property(X_("version"));
2314 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2315 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2316 return -1;
2319 cached_info.clear ();
2321 const XMLNodeList children = root->children();
2323 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2325 const XMLNode* child = *iter;
2327 if (child->name() == X_("plugin")) {
2329 const XMLNode* gchild;
2330 const XMLNodeList gchildren = child->children();
2331 const XMLProperty* prop = child->property (X_("id"));
2333 if (!prop) {
2334 continue;
2337 string id = prop->value();
2338 string fixed;
2339 string version;
2341 string::size_type slash = id.find_last_of ('/');
2343 if (slash == string::npos) {
2344 continue;
2347 version = id.substr (slash);
2348 id = id.substr (0, slash);
2349 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2351 if (fixed.empty()) {
2352 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2353 continue;
2356 id = fixed;
2357 id += version;
2359 AUPluginCachedInfo cinfo;
2361 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2363 gchild = *giter;
2365 if (gchild->name() == X_("io")) {
2367 int in;
2368 int out;
2369 const XMLProperty* iprop;
2370 const XMLProperty* oprop;
2372 if (((iprop = gchild->property (X_("in"))) != 0) &&
2373 ((oprop = gchild->property (X_("out"))) != 0)) {
2374 in = atoi (iprop->value());
2375 out = atoi (oprop->value());
2377 cinfo.io_configs.push_back (pair<int,int> (in, out));
2382 if (cinfo.io_configs.size()) {
2383 add_cached_info (id, cinfo);
2388 return 0;
2391 void
2392 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
2394 CFStringRef itemName = NULL;
2396 // Marc Poirier-style item name
2397 CAComponent auComponent (comp_desc);
2398 if (auComponent.IsValid()) {
2399 CAComponentDescription dummydesc;
2400 Handle nameHandle = NewHandle(sizeof(void*));
2401 if (nameHandle != NULL) {
2402 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2403 if (err == noErr) {
2404 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2405 if (nameString != NULL) {
2406 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2409 DisposeHandle(nameHandle);
2413 // if Marc-style fails, do the original way
2414 if (itemName == NULL) {
2415 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2416 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2417 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2419 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2420 compTypeString, compManufacturerString, compSubTypeString);
2422 if (compTypeString != NULL)
2423 CFRelease(compTypeString);
2424 if (compSubTypeString != NULL)
2425 CFRelease(compSubTypeString);
2426 if (compManufacturerString != NULL)
2427 CFRelease(compManufacturerString);
2430 string str = CFStringRefToStdString(itemName);
2431 string::size_type colon = str.find (':');
2433 if (colon) {
2434 name = str.substr (colon+1);
2435 maker = str.substr (0, colon);
2436 strip_whitespace_edges (maker);
2437 strip_whitespace_edges (name);
2438 } else {
2439 name = str;
2440 maker = "unknown";
2441 strip_whitespace_edges (name);
2445 std::string
2446 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2448 stringstream s;
2450 /* note: OSType is a compiler-implemenation-defined value,
2451 historically a 32 bit integer created with a multi-character
2452 constant such as 'abcd'. It is, fundamentally, an abomination.
2455 s << desc.Type();
2456 s << '-';
2457 s << desc.SubType();
2458 s << '-';
2459 s << desc.Manu();
2461 return s.str();