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.
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
34 #include <glibmm/thread.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/midi_buffer.h"
42 #include "ardour/filesystem_paths.h"
43 #include "ardour/io.h"
44 #include "ardour/audio_unit.h"
45 #include "ardour/session.h"
46 #include "ardour/tempo.h"
47 #include "ardour/utils.h"
49 #include "appleutility/CAAudioUnit.h"
50 #include "appleutility/CAAUParameter.h"
52 #include <CoreFoundation/CoreFoundation.h>
53 #include <CoreServices/CoreServices.h>
54 #include <AudioUnit/AudioUnit.h>
55 #include <AudioToolbox/AudioUnitUtilities.h>
61 using namespace ARDOUR
;
63 //#define TRACE_AU_API
65 #define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
67 #define TRACE_API(fmt,...)
70 #ifndef AU_STATE_SUPPORT
71 static bool seen_get_state_message
= false;
72 static bool seen_set_state_message
= false;
73 static bool seen_loading_message
= false;
74 static bool seen_saving_message
= false;
77 AUPluginInfo::CachedInfoMap
AUPluginInfo::cached_info
;
79 static string preset_search_path
= "/Library/Audio/Presets:/Network/Library/Audio/Presets";
80 static string preset_suffix
= ".aupreset";
81 static bool preset_search_path_initialized
= false;
82 static bool debug_io_config
= true;
85 _render_callback(void *userData
,
86 AudioUnitRenderActionFlags
*ioActionFlags
,
87 const AudioTimeStamp
*inTimeStamp
,
89 UInt32 inNumberFrames
,
90 AudioBufferList
* ioData
)
93 return ((AUPlugin
*)userData
)->render_callback (ioActionFlags
, inTimeStamp
, inBusNumber
, inNumberFrames
, ioData
);
99 _get_beat_and_tempo_callback (void* userData
,
100 Float64
* outCurrentBeat
,
101 Float64
* outCurrentTempo
)
104 return ((AUPlugin
*)userData
)->get_beat_and_tempo_callback (outCurrentBeat
, outCurrentTempo
);
111 _get_musical_time_location_callback (void * userData
,
112 UInt32
* outDeltaSampleOffsetToNextBeat
,
113 Float32
* outTimeSig_Numerator
,
114 UInt32
* outTimeSig_Denominator
,
115 Float64
* outCurrentMeasureDownBeat
)
118 return ((AUPlugin
*)userData
)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat
,
119 outTimeSig_Numerator
,
120 outTimeSig_Denominator
,
121 outCurrentMeasureDownBeat
);
127 _get_transport_state_callback (void* userData
,
128 Boolean
* outIsPlaying
,
129 Boolean
* outTransportStateChanged
,
130 Float64
* outCurrentSampleInTimeLine
,
131 Boolean
* outIsCycling
,
132 Float64
* outCycleStartBeat
,
133 Float64
* outCycleEndBeat
)
136 return ((AUPlugin
*)userData
)->get_transport_state_callback (outIsPlaying
, outTransportStateChanged
,
137 outCurrentSampleInTimeLine
, outIsCycling
,
138 outCycleStartBeat
, outCycleEndBeat
);
145 save_property_list (CFPropertyListRef propertyList
, Glib::ustring path
)
151 // Convert the property list into XML data.
153 xmlData
= CFPropertyListCreateXMLData( kCFAllocatorDefault
, propertyList
);
156 error
<< _("Could not create XML version of property list") << endmsg
;
160 // Write the XML data to the file.
162 fd
= open (path
.c_str(), O_WRONLY
|O_CREAT
|O_EXCL
, 0664);
164 if (errno
== EEXIST
) {
165 error
<< string_compose (_("Preset file %1 exists; not overwriting"), path
);
167 error
<< string_compose (_("Cannot open preset file %1 (%2)"), path
, strerror (errno
)) << endmsg
;
173 size_t cnt
= CFDataGetLength (xmlData
);
175 if (write (fd
, CFDataGetBytePtr (xmlData
), cnt
) != (ssize_t
) cnt
) {
186 static CFPropertyListRef
187 load_property_list (Glib::ustring path
)
190 CFPropertyListRef propertyList
= 0;
192 CFStringRef errorString
;
194 // Read the XML file.
196 if ((fd
= open (path
.c_str(), O_RDONLY
)) < 0) {
201 off_t len
= lseek (fd
, 0, SEEK_END
);
202 char* buf
= new char[len
];
203 lseek (fd
, 0, SEEK_SET
);
205 if (read (fd
, buf
, len
) != len
) {
213 xmlData
= CFDataCreateWithBytesNoCopy (kCFAllocatorDefault
, (UInt8
*) buf
, len
, kCFAllocatorNull
);
215 // Reconstitute the dictionary using the XML data.
217 propertyList
= CFPropertyListCreateFromXMLData( kCFAllocatorDefault
,
219 kCFPropertyListImmutable
,
228 //-----------------------------------------------------------------------------
230 set_preset_name_in_plist (CFPropertyListRef plist
, string preset_name
)
235 CFStringRef pn
= CFStringCreateWithCString (kCFAllocatorDefault
, preset_name
.c_str(), kCFStringEncodingUTF8
);
237 if (CFGetTypeID (plist
) == CFDictionaryGetTypeID()) {
238 CFDictionarySetValue ((CFMutableDictionaryRef
)plist
, CFSTR(kAUPresetNameKey
), pn
);
244 //-----------------------------------------------------------------------------
246 get_preset_name_in_plist (CFPropertyListRef plist
)
254 if (CFGetTypeID (plist
) == CFDictionaryGetTypeID()) {
255 const void *p
= CFDictionaryGetValue ((CFMutableDictionaryRef
)plist
, CFSTR(kAUPresetNameKey
));
257 CFStringRef str
= (CFStringRef
) p
;
258 int len
= CFStringGetLength(str
);
260 char local_buffer
[len
];
261 if (CFStringGetCString (str
, local_buffer
, len
, kCFStringEncodingUTF8
)) {
269 //--------------------------------------------------------------------------
270 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
271 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
272 Boolean
ComponentDescriptionsMatch_General(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
, Boolean inIgnoreType
);
273 Boolean
ComponentDescriptionsMatch_General(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
, Boolean inIgnoreType
)
275 if ( (inComponentDescription1
== NULL
) || (inComponentDescription2
== NULL
) )
278 if ( (inComponentDescription1
->componentSubType
== inComponentDescription2
->componentSubType
)
279 && (inComponentDescription1
->componentManufacturer
== inComponentDescription2
->componentManufacturer
) )
281 // only sub-type and manufacturer IDs need to be equal
284 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
285 else if (inComponentDescription1
->componentType
== inComponentDescription2
->componentType
)
292 //--------------------------------------------------------------------------
293 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
294 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
295 Boolean
ComponentAndDescriptionMatch_General(Component inComponent
, const ComponentDescription
* inComponentDescription
, Boolean inIgnoreType
);
296 Boolean
ComponentAndDescriptionMatch_General(Component inComponent
, const ComponentDescription
* inComponentDescription
, Boolean inIgnoreType
)
299 ComponentDescription desc
;
301 if ( (inComponent
== NULL
) || (inComponentDescription
== NULL
) )
304 // get the ComponentDescription of the input Component
305 status
= GetComponentInfo(inComponent
, &desc
, NULL
, NULL
, NULL
);
309 // check if the Component's ComponentDescription matches the input ComponentDescription
310 return ComponentDescriptionsMatch_General(&desc
, inComponentDescription
, inIgnoreType
);
313 //--------------------------------------------------------------------------
314 // determine if 2 ComponentDescriptions are basically equal
315 // (by that, I mean that the important identifying values are compared,
316 // but not the ComponentDescription flags)
317 Boolean
ComponentDescriptionsMatch(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
)
319 return ComponentDescriptionsMatch_General(inComponentDescription1
, inComponentDescription2
, FALSE
);
322 //--------------------------------------------------------------------------
323 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
324 Boolean
ComponentDescriptionsMatch_Loose(const ComponentDescription
* inComponentDescription1
, const ComponentDescription
* inComponentDescription2
)
326 return ComponentDescriptionsMatch_General(inComponentDescription1
, inComponentDescription2
, TRUE
);
329 //--------------------------------------------------------------------------
330 // determine if a ComponentDescription basically matches that of a particular Component
331 Boolean
ComponentAndDescriptionMatch(Component inComponent
, const ComponentDescription
* inComponentDescription
)
333 return ComponentAndDescriptionMatch_General(inComponent
, inComponentDescription
, FALSE
);
336 //--------------------------------------------------------------------------
337 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
338 Boolean
ComponentAndDescriptionMatch_Loosely(Component inComponent
, const ComponentDescription
* inComponentDescription
)
340 return ComponentAndDescriptionMatch_General(inComponent
, inComponentDescription
, TRUE
);
344 AUPlugin::AUPlugin (AudioEngine
& engine
, Session
& session
, boost::shared_ptr
<CAComponent
> _comp
)
345 : Plugin (engine
, session
)
347 , unit (new CAAudioUnit
)
348 , initialized (false)
349 , _current_block_size (0)
350 , _requires_fixed_size_buffers (false)
354 , current_buffers (0)
355 , frames_processed (0)
356 , last_transport_rolling (false)
357 , last_transport_speed (0.0)
359 if (!preset_search_path_initialized
) {
360 Glib::ustring p
= Glib::get_home_dir();
361 p
+= "/Library/Audio/Presets:";
362 p
+= preset_search_path
;
363 preset_search_path
= p
;
364 preset_search_path_initialized
= true;
370 AUPlugin::AUPlugin (const AUPlugin
& other
)
372 , comp (other
.get_comp())
373 , unit (new CAAudioUnit
)
374 , initialized (false)
375 , _current_block_size (0)
377 , _requires_fixed_size_buffers (false)
381 , current_buffers (0)
382 , frames_processed (0)
388 AUPlugin::~AUPlugin ()
391 TRACE_API ("about to call uninitialize in plugin destructor\n");
392 unit
->Uninitialize ();
401 AUPlugin::discover_factory_presets ()
404 UInt32 dataSize
= sizeof (presets
);
407 TRACE_API ("get property FactoryPresets in global scope\n");
408 if ((err
= unit
->GetProperty (kAudioUnitProperty_FactoryPresets
, kAudioUnitScope_Global
, 0, (void*) &presets
, &dataSize
)) != 0) {
409 cerr
<< "cannot get factory preset info: " << err
<< endl
;
417 CFIndex cnt
= CFArrayGetCount (presets
);
419 for (CFIndex i
= 0; i
< cnt
; ++i
) {
420 AUPreset
* preset
= (AUPreset
*) CFArrayGetValueAtIndex (presets
, i
);
422 string name
= CFStringRefToStdString (preset
->presetName
);
423 factory_preset_map
[name
] = preset
->presetNumber
;
435 TRACE_API ("opening AudioUnit\n");
436 err
= CAAudioUnit::Open (*(comp
.get()), *unit
);
438 error
<< _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg
;
439 throw failed_constructor();
443 error
<< _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg
;
444 throw failed_constructor ();
447 TRACE_API ("count global elements\n");
448 unit
->GetElementCount (kAudioUnitScope_Global
, global_elements
);
449 TRACE_API ("count input elements\n");
450 unit
->GetElementCount (kAudioUnitScope_Input
, input_elements
);
451 TRACE_API ("count output elements\n");
452 unit
->GetElementCount (kAudioUnitScope_Output
, output_elements
);
454 if (input_elements
> 0) {
455 AURenderCallbackStruct renderCallbackInfo
;
457 renderCallbackInfo
.inputProc
= _render_callback
;
458 renderCallbackInfo
.inputProcRefCon
= this;
460 TRACE_API ("set render callback in input scope\n");
461 if ((err
= unit
->SetProperty (kAudioUnitProperty_SetRenderCallback
, kAudioUnitScope_Input
,
462 0, (void*) &renderCallbackInfo
, sizeof(renderCallbackInfo
))) != 0) {
463 cerr
<< "cannot install render callback (err = " << err
<< ')' << endl
;
464 throw failed_constructor();
468 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
470 HostCallbackInfo info
;
471 memset (&info
, 0, sizeof (HostCallbackInfo
));
472 info
.hostUserData
= this;
473 info
.beatAndTempoProc
= _get_beat_and_tempo_callback
;
474 info
.musicalTimeLocationProc
= _get_musical_time_location_callback
;
475 info
.transportStateProc
= _get_transport_state_callback
;
477 //ignore result of this - don't care if the property isn't supported
478 TRACE_API ("set host callbacks in global scope\n");
479 unit
->SetProperty (kAudioUnitProperty_HostCallbacks
,
480 kAudioUnitScope_Global
,
483 sizeof (HostCallbackInfo
));
485 /* these keep track of *configured* channel set up,
486 not potential set ups.
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 AUPluginInfoPtr pinfo
= boost::dynamic_pointer_cast
<AUPluginInfo
>(get_info());
498 _has_midi_input
= pinfo
->needs_midi_input ();
499 _has_midi_output
= false;
501 discover_parameters ();
502 discover_factory_presets ();
504 // Plugin::setup_controls ();
508 AUPlugin::discover_parameters ()
510 /* discover writable parameters */
512 AudioUnitScope scopes
[] = {
513 kAudioUnitScope_Global
,
514 kAudioUnitScope_Output
,
515 kAudioUnitScope_Input
518 descriptors
.clear ();
520 for (uint32_t i
= 0; i
< sizeof (scopes
) / sizeof (scopes
[0]); ++i
) {
522 AUParamInfo
param_info (unit
->AU(), false, false, scopes
[i
]);
524 for (uint32_t i
= 0; i
< param_info
.NumParams(); ++i
) {
526 AUParameterDescriptor d
;
528 d
.id
= param_info
.ParamID (i
);
530 const CAAUParameter
* param
= param_info
.GetParamInfo (d
.id
);
531 const AudioUnitParameterInfo
& info (param
->ParamInfo());
533 const int len
= CFStringGetLength (param
->GetName());;
534 char local_buffer
[len
*2];
535 Boolean good
= CFStringGetCString(param
->GetName(),local_buffer
,len
*2,kCFStringEncodingMacRoman
);
539 d
.label
= local_buffer
;
542 d
.scope
= param_info
.GetScope ();
543 d
.element
= param_info
.GetElement ();
545 /* info.units to consider */
547 kAudioUnitParameterUnit_Generic = 0
548 kAudioUnitParameterUnit_Indexed = 1
549 kAudioUnitParameterUnit_Boolean = 2
550 kAudioUnitParameterUnit_Percent = 3
551 kAudioUnitParameterUnit_Seconds = 4
552 kAudioUnitParameterUnit_SampleFrames = 5
553 kAudioUnitParameterUnit_Phase = 6
554 kAudioUnitParameterUnit_Rate = 7
555 kAudioUnitParameterUnit_Hertz = 8
556 kAudioUnitParameterUnit_Cents = 9
557 kAudioUnitParameterUnit_RelativeSemiTones = 10
558 kAudioUnitParameterUnit_MIDINoteNumber = 11
559 kAudioUnitParameterUnit_MIDIController = 12
560 kAudioUnitParameterUnit_Decibels = 13
561 kAudioUnitParameterUnit_LinearGain = 14
562 kAudioUnitParameterUnit_Degrees = 15
563 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
564 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
565 kAudioUnitParameterUnit_Pan = 18
566 kAudioUnitParameterUnit_Meters = 19
567 kAudioUnitParameterUnit_AbsoluteCents = 20
568 kAudioUnitParameterUnit_Octaves = 21
569 kAudioUnitParameterUnit_BPM = 22
570 kAudioUnitParameterUnit_Beats = 23
571 kAudioUnitParameterUnit_Milliseconds = 24
572 kAudioUnitParameterUnit_Ratio = 25
575 /* info.flags to consider */
579 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
580 kAudioUnitParameterFlag_HasClump = (1L << 20)
581 kAudioUnitParameterFlag_HasName = (1L << 21)
582 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
583 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
584 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
585 kAudioUnitParameterFlag_CanRamp = (1L << 25)
586 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
587 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
588 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
589 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
590 kAudioUnitParameterFlag_IsReadable = (1L << 30)
591 kAudioUnitParameterFlag_IsWritable = (1L << 31)
594 d
.lower
= info
.minValue
;
595 d
.upper
= info
.maxValue
;
596 d
.default_value
= info
.defaultValue
;
598 d
.integer_step
= (info
.unit
== kAudioUnitParameterUnit_Indexed
);
599 d
.toggled
= (info
.unit
== kAudioUnitParameterUnit_Boolean
) ||
600 (d
.integer_step
&& ((d
.upper
- d
.lower
) == 1.0));
601 d
.sr_dependent
= (info
.unit
== kAudioUnitParameterUnit_SampleFrames
);
602 d
.automatable
= !d
.toggled
&&
603 !(info
.flags
& kAudioUnitParameterFlag_NonRealTime
) &&
604 (info
.flags
& kAudioUnitParameterFlag_IsWritable
);
606 d
.logarithmic
= (info
.flags
& kAudioUnitParameterFlag_DisplayLogarithmic
);
612 d
.min_unbound
= 0; // lower is bound
613 d
.max_unbound
= 0; // upper is bound
615 descriptors
.push_back (d
);
622 four_ints_to_four_byte_literal (unsigned char n
[4])
624 /* this is actually implementation dependent. sigh. this is what gcc
625 and quite a few others do.
627 return ((n
[0] << 24) + (n
[1] << 16) + (n
[2] << 8) + n
[3]);
631 AUPlugin::maybe_fix_broken_au_id (const std::string
& id
)
633 if (isdigit (id
[0])) {
637 /* ID format is xxxx-xxxx-xxxx
638 where x maybe \xNN or a printable character.
640 Split at the '-' and and process each part into an integer.
641 Then put it back together.
645 unsigned char nascent
[4];
646 const char* cstr
= id
.c_str();
647 const char* estr
= cstr
+ id
.size();
658 while (*cstr
&& next_int
< 4) {
662 if (estr
- cstr
< 3) {
664 /* too close to the end for \xNN parsing: treat as literal characters */
666 cerr
<< "Parse " << cstr
<< " as a literal \\" << endl
;
673 if (cstr
[1] == 'x' && isxdigit (cstr
[2]) && isxdigit (cstr
[3])) {
677 memcpy (short_buf
, &cstr
[2], 2);
678 nascent
[in
] = strtol (short_buf
, NULL
, 16);
684 /* treat as literal characters */
685 cerr
<< "Parse " << cstr
<< " as a literal \\" << endl
;
699 if (in
&& (in
% 4 == 0)) {
700 /* nascent is ready */
701 n
[next_int
] = four_ints_to_four_byte_literal (nascent
);
705 /* swallow space-hyphen-space */
719 s
<< n
[0] << '-' << n
[1] << '-' << n
[2];
728 AUPlugin::unique_id () const
730 return AUPluginInfo::stringify_descriptor (comp
->Desc());
734 AUPlugin::label () const
736 return _info
->name
.c_str();
740 AUPlugin::parameter_count () const
742 return descriptors
.size();
746 AUPlugin::default_value (uint32_t port
)
748 if (port
< descriptors
.size()) {
749 return descriptors
[port
].default_value
;
756 AUPlugin::signal_latency () const
758 return unit
->Latency() * _session
.frame_rate();
762 AUPlugin::set_parameter (uint32_t which
, float val
)
764 if (which
>= descriptors
.size()) {
768 const AUParameterDescriptor
& d (descriptors
[which
]);
769 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d
.id
, d
.scope
, d
.element
, val
);
770 unit
->SetParameter (d
.id
, d
.scope
, d
.element
, val
);
772 /* tell the world what we did */
774 AudioUnitEvent theEvent
;
776 theEvent
.mEventType
= kAudioUnitEvent_ParameterValueChange
;
777 theEvent
.mArgument
.mParameter
.mAudioUnit
= unit
->AU();
778 theEvent
.mArgument
.mParameter
.mParameterID
= d
.id
;
779 theEvent
.mArgument
.mParameter
.mScope
= d
.scope
;
780 theEvent
.mArgument
.mParameter
.mElement
= d
.element
;
782 TRACE_API ("notify about parameter change\n");
783 AUEventListenerNotify (NULL
, NULL
, &theEvent
);
785 Plugin::set_parameter (which
, val
);
789 AUPlugin::get_parameter (uint32_t which
) const
792 if (which
< descriptors
.size()) {
793 const AUParameterDescriptor
& d (descriptors
[which
]);
794 TRACE_API ("get value of parameter %d in scope %d element %d\n", d
.id
, d
.scope
, d
.element
);
795 unit
->GetParameter(d
.id
, d
.scope
, d
.element
, val
);
801 AUPlugin::get_parameter_descriptor (uint32_t which
, ParameterDescriptor
& pd
) const
803 if (which
< descriptors
.size()) {
804 pd
= descriptors
[which
];
811 AUPlugin::nth_parameter (uint32_t which
, bool& ok
) const
813 if (which
< descriptors
.size()) {
822 AUPlugin::activate ()
826 TRACE_API ("call Initialize in activate()\n");
827 if ((err
= unit
->Initialize()) != noErr
) {
828 error
<< string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err
) << endmsg
;
830 frames_processed
= 0;
837 AUPlugin::deactivate ()
839 TRACE_API ("call Uninitialize in deactivate()\n");
840 unit
->Uninitialize ();
847 TRACE_API ("call Reset in flush()\n");
848 unit
->GlobalReset ();
852 AUPlugin::requires_fixed_size_buffers() const
854 return _requires_fixed_size_buffers
;
859 AUPlugin::set_block_size (pframes_t nframes
)
861 bool was_initialized
= initialized
;
862 UInt32 numFrames
= nframes
;
869 TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames
);
870 if ((err
= unit
->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice
, kAudioUnitScope_Global
,
871 0, &numFrames
, sizeof (numFrames
))) != noErr
) {
872 cerr
<< "cannot set max frames (err = " << err
<< ')' << endl
;
876 if (was_initialized
) {
880 _current_block_size
= nframes
;
886 AUPlugin::configure_io (ChanCount in
, ChanCount out
)
888 AudioStreamBasicDescription streamFormat
;
889 bool was_initialized
= initialized
;
890 int32_t audio_in
= in
.n_audio();
891 int32_t audio_out
= out
.n_audio();
894 //if we are already running with the requested i/o config, bail out here
895 if ( (audio_in
==input_channels
) && (audio_out
==output_channels
) ) {
902 streamFormat
.mSampleRate
= _session
.frame_rate();
903 streamFormat
.mFormatID
= kAudioFormatLinearPCM
;
904 streamFormat
.mFormatFlags
= kAudioFormatFlagIsFloat
|kAudioFormatFlagIsPacked
|kAudioFormatFlagIsNonInterleaved
;
906 #ifdef __LITTLE_ENDIAN__
909 streamFormat
.mFormatFlags
|= kAudioFormatFlagIsBigEndian
;
912 streamFormat
.mBitsPerChannel
= 32;
913 streamFormat
.mFramesPerPacket
= 1;
915 /* apple says that for non-interleaved data, these
916 values always refer to a single channel.
918 streamFormat
.mBytesPerPacket
= 4;
919 streamFormat
.mBytesPerFrame
= 4;
921 streamFormat
.mChannelsPerFrame
= audio_in
;
923 if (set_input_format (streamFormat
) != 0) {
927 streamFormat
.mChannelsPerFrame
= audio_out
;
929 if (set_output_format (streamFormat
) != 0) {
933 if (was_initialized
) {
941 AUPlugin::can_support_io_configuration (const ChanCount
& in
, ChanCount
& out
) const
943 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
944 // attempt to multiply-instantiate plugins to meet io configurations.
946 int32_t audio_in
= in
.n_audio();
948 int32_t plugcnt
= -1;
949 AUPluginInfoPtr pinfo
= boost::dynamic_pointer_cast
<AUPluginInfo
>(get_info());
951 /* lets check MIDI first */
953 if (in
.n_midi() > 0) {
954 if (!_has_midi_input
) {
959 vector
<pair
<int,int> >& io_configs
= pinfo
->cache
.io_configs
;
961 if (debug_io_config
) {
962 cerr
<< name() << " has " << io_configs
.size() << " IO Configurations\n";
965 //Ardour expects the plugin to tell it the output configuration
966 //but AU plugins can have multiple I/O configurations
967 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
968 //so first lets see if there's a configuration that keeps out==in
970 audio_out
= audio_in
;
972 for (vector
<pair
<int,int> >::iterator i
= io_configs
.begin(); i
!= io_configs
.end(); ++i
) {
973 int32_t possible_in
= i
->first
;
974 int32_t possible_out
= i
->second
;
976 if (possible_in
== audio_in
&& possible_out
== audio_out
) {
977 cerr
<< "\tCHOSEN: in " << in
<< " out " << out
<< endl
;
982 /* now allow potentially "imprecise" matches */
984 for (vector
<pair
<int,int> >::iterator i
= io_configs
.begin(); i
!= io_configs
.end(); ++i
) {
986 int32_t possible_in
= i
->first
;
987 int32_t possible_out
= i
->second
;
989 if (debug_io_config
) {
990 cerr
<< "\tin " << possible_in
<< " out " << possible_out
<< endl
;
993 if (possible_out
== 0) {
994 warning
<< string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg
;
998 if (possible_in
== 0) {
1000 /* instrument plugin, always legal but throws away inputs ...
1003 if (possible_out
== -1) {
1004 /* out much match in (UNLIKELY!!) */
1005 audio_out
= audio_in
;
1007 } else if (possible_out
== -2) {
1008 /* any configuration possible, pick matching */
1009 audio_out
= audio_in
;
1011 } else if (possible_out
< -2) {
1012 /* explicit variable number of outputs, pick maximum */
1013 audio_out
= -possible_out
;
1016 /* exact number of outputs */
1017 audio_out
= possible_out
;
1022 if (possible_in
== -1) {
1024 /* wildcard for input */
1026 if (possible_out
== -1) {
1027 /* out much match in */
1028 audio_out
= audio_in
;
1030 } else if (possible_out
== -2) {
1031 /* any configuration possible, pick matching */
1032 audio_out
= audio_in
;
1034 } else if (possible_out
< -2) {
1035 /* explicit variable number of outputs, pick maximum */
1036 audio_out
= -possible_out
;
1039 /* exact number of outputs */
1040 audio_out
= possible_out
;
1045 if (possible_in
== -2) {
1047 if (possible_out
== -1) {
1048 /* any configuration possible, pick matching */
1049 audio_out
= audio_in
;
1051 } else if (possible_out
== -2) {
1052 error
<< string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1055 } else if (possible_out
< -2) {
1056 /* explicit variable number of outputs, pick maximum */
1057 audio_out
= -possible_out
;
1060 /* exact number of outputs */
1061 audio_out
= possible_out
;
1066 if (possible_in
< -2) {
1068 /* explicit variable number of inputs */
1070 if (audio_in
> -possible_in
) {
1071 /* request is too large */
1075 if (possible_out
== -1) {
1076 /* out must match in */
1077 audio_out
= audio_in
;
1079 } else if (possible_out
== -2) {
1080 error
<< string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1083 } else if (possible_out
< -2) {
1084 /* explicit variable number of outputs, pick maximum */
1085 audio_out
= -possible_out
;
1088 /* exact number of outputs */
1089 audio_out
= possible_out
;
1094 if (possible_in
== audio_in
) {
1096 /* exact number of inputs ... must match obviously */
1098 if (possible_out
== -1) {
1099 /* out must match in */
1100 audio_out
= audio_in
;
1102 } else if (possible_out
== -2) {
1103 /* any output configuration, pick matching */
1104 audio_out
= audio_in
;
1106 } else if (possible_out
< -2) {
1107 /* explicit variable number of outputs, pick maximum */
1108 audio_out
= -possible_out
;
1111 /* exact number of outputs */
1112 audio_out
= possible_out
;
1123 if (debug_io_config
) {
1125 cerr
<< "\tCHOSEN: in " << in
<< " out " << out
<< " plugcnt will be " << plugcnt
<< endl
;
1127 cerr
<< "\tFAIL: no configs match requested in " << in
<< endl
;
1131 out
.set (DataType::MIDI
, 0);
1132 out
.set (DataType::AUDIO
, audio_out
);
1138 AUPlugin::set_input_format (AudioStreamBasicDescription
& fmt
)
1140 return set_stream_format (kAudioUnitScope_Input
, input_elements
, fmt
);
1144 AUPlugin::set_output_format (AudioStreamBasicDescription
& fmt
)
1146 if (set_stream_format (kAudioUnitScope_Output
, output_elements
, fmt
) != 0) {
1155 buffers
= (AudioBufferList
*) malloc (offsetof(AudioBufferList
, mBuffers
) +
1156 fmt
.mChannelsPerFrame
* sizeof(::AudioBuffer
));
1158 Glib::Mutex::Lock
em (_session
.engine().process_lock());
1159 IO::PortCountChanged (ChanCount(DataType::AUDIO
, fmt
.mChannelsPerFrame
));
1165 AUPlugin::set_stream_format (int scope
, uint32_t cnt
, AudioStreamBasicDescription
& fmt
)
1169 for (uint32_t i
= 0; i
< cnt
; ++i
) {
1170 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1171 (scope
== kAudioUnitScope_Input
? "input" : "output"),
1173 if ((result
= unit
->SetFormat (scope
, i
, fmt
)) != 0) {
1174 error
<< string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1175 (scope
== kAudioUnitScope_Input
? "input" : "output"), i
, result
) << endmsg
;
1180 if (scope
== kAudioUnitScope_Input
) {
1181 input_channels
= fmt
.mChannelsPerFrame
;
1183 output_channels
= fmt
.mChannelsPerFrame
;
1190 AUPlugin::render_callback(AudioUnitRenderActionFlags
*,
1191 const AudioTimeStamp
*,
1193 UInt32 inNumberFrames
,
1194 AudioBufferList
* ioData
)
1196 if (_has_midi_input
) {
1197 assert (current_buffers
->count().n_midi() > 0);
1199 /* deliver the first (and assumed only) MIDI buffer's data
1203 MidiBuffer
& mb (current_buffers
->get_midi(0));
1205 for (MidiBuffer::iterator i
= mb
.begin(); i
!= mb
.end(); ++i
) {
1206 Evoral::MIDIEvent
<MidiBuffer::TimeType
> ev
= *i
;
1207 switch (ev
.type()) {
1208 case MIDI_CMD_NOTE_ON
:
1209 case MIDI_CMD_NOTE_OFF
:
1210 case MIDI_CMD_CONTROL
:
1211 case MIDI_CMD_BENDER
:
1212 case MIDI_CMD_PGM_CHANGE
:
1213 case MIDI_CMD_CHANNEL_PRESSURE
:
1215 const uint8_t* b
= ev
.buffer();
1216 unit
->MIDIEvent (b
[0], b
[1], b
[2], ev
.time());
1221 /* plugins do not get other stuff by default */
1227 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1229 if (current_maxbuf
== 0) {
1230 error
<< _("AUPlugin: render callback called illegally!") << endmsg
;
1231 return kAudioUnitErr_CannotDoInCurrentContext
;
1233 uint32_t limit
= min ((uint32_t) ioData
->mNumberBuffers
, current_maxbuf
);
1235 for (uint32_t i
= 0; i
< limit
; ++i
) {
1236 ioData
->mBuffers
[i
].mNumberChannels
= 1;
1237 ioData
->mBuffers
[i
].mDataByteSize
= sizeof (Sample
) * inNumberFrames
;
1239 /* we don't use the channel mapping because audiounits are
1240 never replicated. one plugin instance uses all channels/buffers
1241 passed to PluginInsert::connect_and_run()
1244 ioData
->mBuffers
[i
].mData
= current_buffers
->get_audio (i
).data (cb_offset
+ current_offset
);
1247 cb_offset
+= inNumberFrames
;
1253 AUPlugin::connect_and_run (BufferSet
& bufs
, ChanMapping in_map
, ChanMapping out_map
, pframes_t nframes
, framecnt_t offset
)
1255 Plugin::connect_and_run (bufs
, in_map
, out_map
, nframes
, offset
);
1257 AudioUnitRenderActionFlags flags
= 0;
1260 uint32_t maxbuf
= bufs
.count().n_audio();
1262 if (requires_fixed_size_buffers() && (nframes
!= _last_nframes
)) {
1263 unit
->GlobalReset();
1264 _last_nframes
= nframes
;
1267 current_buffers
= &bufs
;
1268 current_maxbuf
= maxbuf
;
1269 current_offset
= offset
;
1272 buffers
->mNumberBuffers
= min ((uint32_t) output_channels
, maxbuf
);
1274 for (uint32_t i
= 0; i
< buffers
->mNumberBuffers
; ++i
) {
1275 buffers
->mBuffers
[i
].mNumberChannels
= 1;
1276 buffers
->mBuffers
[i
].mDataByteSize
= nframes
* sizeof (Sample
);
1277 buffers
->mBuffers
[i
].mData
= 0;
1280 ts
.mSampleTime
= frames_processed
;
1281 ts
.mFlags
= kAudioTimeStampSampleTimeValid
;
1283 if ((err
= unit
->Render (&flags
, &ts
, 0, nframes
, buffers
)) == noErr
) {
1286 frames_processed
+= nframes
;
1288 uint32_t limit
= min ((uint32_t) buffers
->mNumberBuffers
, maxbuf
);
1291 for (i
= 0; i
< limit
; ++i
) {
1292 Sample
* expected_buffer_address
= bufs
.get_audio (i
).data (offset
);
1293 if (expected_buffer_address
!= buffers
->mBuffers
[i
].mData
) {
1294 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1295 memcpy (expected_buffer_address
, buffers
->mBuffers
[i
].mData
, nframes
* sizeof (Sample
));
1299 /* now silence any buffers that were passed in but the that the plugin
1300 did not fill/touch/use.
1303 for (;i
< maxbuf
; ++i
) {
1304 Sample
* buffer_address
= bufs
.get_audio (i
).data (offset
);
1305 memset (buffer_address
, 0, nframes
* sizeof (Sample
));
1311 cerr
<< name() << " render status " << err
<< endl
;
1316 AUPlugin::get_beat_and_tempo_callback (Float64
* outCurrentBeat
,
1317 Float64
* outCurrentTempo
)
1319 TempoMap
& tmap (_session
.tempo_map());
1321 TRACE_API ("AU calls ardour beat&tempo callback\n");
1323 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1324 (and interpretation) of a beat position will be incorrect. So refuse to
1328 if (tmap
.n_tempos() > 1 || tmap
.n_meters() > 1) {
1329 return kAudioUnitErr_CannotDoInCurrentContext
;
1332 Timecode::BBT_Time bbt
;
1333 TempoMetric metric
= tmap
.metric_at (_session
.transport_frame() + current_offset
);
1334 tmap
.bbt_time_with_metric (_session
.transport_frame() + current_offset
, bbt
, metric
);
1336 if (outCurrentBeat
) {
1338 beat
= metric
.meter().beats_per_bar() * bbt
.bars
;
1340 beat
+= bbt
.ticks
/ BBT_Time::ticks_per_beat
;
1341 *outCurrentBeat
= beat
;
1344 if (outCurrentTempo
) {
1345 *outCurrentTempo
= floor (metric
.tempo().beats_per_minute());
1353 AUPlugin::get_musical_time_location_callback (UInt32
* outDeltaSampleOffsetToNextBeat
,
1354 Float32
* outTimeSig_Numerator
,
1355 UInt32
* outTimeSig_Denominator
,
1356 Float64
* outCurrentMeasureDownBeat
)
1358 TempoMap
& tmap (_session
.tempo_map());
1360 TRACE_API ("AU calls ardour music time location callback\n");
1362 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1363 (and interpretation) of a beat position will be incorrect. So refuse to
1367 if (tmap
.n_tempos() > 1 || tmap
.n_meters() > 1) {
1368 return kAudioUnitErr_CannotDoInCurrentContext
;
1371 Timecode::BBT_Time bbt
;
1372 TempoMetric metric
= tmap
.metric_at (_session
.transport_frame() + current_offset
);
1373 tmap
.bbt_time_with_metric (_session
.transport_frame() + current_offset
, bbt
, metric
);
1375 if (outDeltaSampleOffsetToNextBeat
) {
1376 if (bbt
.ticks
== 0) {
1378 *outDeltaSampleOffsetToNextBeat
= 0;
1380 *outDeltaSampleOffsetToNextBeat
= (UInt32
) floor (((BBT_Time::ticks_per_beat
- bbt
.ticks
)/BBT_Time::ticks_per_beat
) * // fraction of a beat to next beat
1381 metric
.tempo().frames_per_beat(_session
.frame_rate(), metric
.meter())); // frames per beat
1385 if (outTimeSig_Numerator
) {
1386 *outTimeSig_Numerator
= (UInt32
) lrintf (metric
.meter().beats_per_bar());
1388 if (outTimeSig_Denominator
) {
1389 *outTimeSig_Denominator
= (UInt32
) lrintf (metric
.meter().note_divisor());
1392 if (outCurrentMeasureDownBeat
) {
1394 /* beat for the start of the bar.
1396 2|1|0 -> 1 + beats_per_bar
1397 3|1|0 -> 1 + (2 * beats_per_bar)
1401 *outCurrentMeasureDownBeat
= 1 + metric
.meter().beats_per_bar() * (bbt
.bars
- 1);
1408 AUPlugin::get_transport_state_callback (Boolean
* outIsPlaying
,
1409 Boolean
* outTransportStateChanged
,
1410 Float64
* outCurrentSampleInTimeLine
,
1411 Boolean
* outIsCycling
,
1412 Float64
* outCycleStartBeat
,
1413 Float64
* outCycleEndBeat
)
1418 TRACE_API ("AU calls ardour transport state callback\n");
1420 rolling
= _session
.transport_rolling();
1421 speed
= _session
.transport_speed ();
1424 *outIsPlaying
= _session
.transport_rolling();
1427 if (outTransportStateChanged
) {
1428 if (rolling
!= last_transport_rolling
) {
1429 *outTransportStateChanged
= true;
1430 } else if (speed
!= last_transport_speed
) {
1431 *outTransportStateChanged
= true;
1433 *outTransportStateChanged
= false;
1437 if (outCurrentSampleInTimeLine
) {
1438 /* this assumes that the AU can only call this host callback from render context,
1439 where current_offset is valid.
1441 *outCurrentSampleInTimeLine
= _session
.transport_frame() + current_offset
;
1445 Location
* loc
= _session
.locations()->auto_loop_location();
1447 *outIsCycling
= (loc
&& _session
.transport_rolling() && _session
.get_play_loop());
1449 if (*outIsCycling
) {
1451 if (outCycleStartBeat
|| outCycleEndBeat
) {
1453 TempoMap
& tmap (_session
.tempo_map());
1455 /* more than 1 meter means that a simplistic computation (and interpretation) of
1456 a beat position will be incorrect. so refuse to offer the value.
1459 if (tmap
.n_meters() > 1) {
1460 return kAudioUnitErr_CannotDoInCurrentContext
;
1463 Timecode::BBT_Time bbt
;
1465 if (outCycleStartBeat
) {
1466 TempoMetric metric
= tmap
.metric_at (loc
->start() + current_offset
);
1467 _session
.tempo_map().bbt_time_with_metric (loc
->start(), bbt
, metric
);
1470 beat
= metric
.meter().beats_per_bar() * bbt
.bars
;
1472 beat
+= bbt
.ticks
/ BBT_Time::ticks_per_beat
;
1474 *outCycleStartBeat
= beat
;
1477 if (outCycleEndBeat
) {
1478 TempoMetric metric
= tmap
.metric_at (loc
->end() + current_offset
);
1479 _session
.tempo_map().bbt_time_with_metric (loc
->end(), bbt
, metric
);
1482 beat
= metric
.meter().beats_per_bar() * bbt
.bars
;
1484 beat
+= bbt
.ticks
/ BBT_Time::ticks_per_beat
;
1486 *outCycleEndBeat
= beat
;
1492 last_transport_rolling
= rolling
;
1493 last_transport_speed
= speed
;
1498 set
<Evoral::Parameter
>
1499 AUPlugin::automatable() const
1501 set
<Evoral::Parameter
> automates
;
1503 for (uint32_t i
= 0; i
< descriptors
.size(); ++i
) {
1504 if (descriptors
[i
].automatable
) {
1505 automates
.insert (automates
.end(), Evoral::Parameter (PluginAutomation
, 0, i
));
1513 AUPlugin::describe_parameter (Evoral::Parameter param
)
1515 if (param
.type() == PluginAutomation
&& param
.id() < parameter_count()) {
1516 return descriptors
[param
.id()].label
;
1523 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1525 // NameValue stuff here
1529 AUPlugin::parameter_is_audio (uint32_t) const
1535 AUPlugin::parameter_is_control (uint32_t) const
1541 AUPlugin::parameter_is_input (uint32_t) const
1547 AUPlugin::parameter_is_output (uint32_t) const
1553 AUPlugin::add_state (XMLNode
* root
)
1555 LocaleGuard
lg (X_("POSIX"));
1557 #ifdef AU_STATE_SUPPORT
1559 CFPropertyListRef propertyList
;
1561 TRACE_API ("get preset state\n");
1562 if (unit
->GetAUPreset (propertyList
) != noErr
) {
1566 // Convert the property list into XML data.
1568 xmlData
= CFPropertyListCreateXMLData( kCFAllocatorDefault
, propertyList
);
1571 error
<< _("Could not create XML version of property list") << endmsg
;
1575 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1576 our state node. GACK!
1581 if (t
.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData
), CFDataGetLength (xmlData
)))) {
1583 root
->add_child_copy (*t
.root());
1587 CFRelease (xmlData
);
1588 CFRelease (propertyList
);
1590 if (!seen_get_state_message
) {
1591 info
<< string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1594 seen_get_state_message
= true;
1600 AUPlugin::set_state(const XMLNode
& node
, int version
)
1602 #ifdef AU_STATE_SUPPORT
1604 CFPropertyListRef propertyList
;
1605 LocaleGuard
lg (X_("POSIX"));
1607 if (node
.name() != state_node_name()) {
1608 error
<< _("Bad node sent to AUPlugin::set_state") << endmsg
;
1612 if (node
.children().empty()) {
1616 XMLNode
* top
= node
.children().front();
1617 XMLNode
* copy
= new XMLNode (*top
);
1622 const string
& xml
= t
.write_buffer ();
1623 CFDataRef xmlData
= CFDataCreateWithBytesNoCopy (kCFAllocatorDefault
, (UInt8
*) xml
.data(), xml
.length(), kCFAllocatorNull
);
1624 CFStringRef errorString
;
1626 propertyList
= CFPropertyListCreateFromXMLData( kCFAllocatorDefault
,
1628 kCFPropertyListImmutable
,
1631 CFRelease (xmlData
);
1634 TRACE_API ("set preset\n");
1635 if (unit
->SetAUPreset (propertyList
) == noErr
) {
1638 /* tell the world */
1640 AudioUnitParameter changedUnit
;
1641 changedUnit
.mAudioUnit
= unit
->AU();
1642 changedUnit
.mParameterID
= kAUParameterListener_AnyParameter
;
1643 AUParameterListenerNotify (NULL
, NULL
, &changedUnit
);
1645 CFRelease (propertyList
);
1648 Plugin::set_state (node
, version
);
1651 if (!seen_set_state_message
) {
1652 info
<< string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1656 return Plugin::set_state (node
, version
);
1661 AUPlugin::load_preset (PluginRecord r
)
1663 Plugin::load_preset (r
);
1665 #ifdef AU_STATE_SUPPORT
1667 CFPropertyListRef propertyList
;
1669 UserPresetMap::iterator ux
;
1670 FactoryPresetMap::iterator fx
;
1672 /* look first in "user" presets */
1674 if ((ux
= user_preset_map
.find (preset_label
)) != user_preset_map
.end()) {
1676 if ((propertyList
= load_property_list (ux
->second
)) != 0) {
1677 TRACE_API ("set preset from user presets\n");
1678 if (unit
->SetAUPreset (propertyList
) == noErr
) {
1681 /* tell the world */
1683 AudioUnitParameter changedUnit
;
1684 changedUnit
.mAudioUnit
= unit
->AU();
1685 changedUnit
.mParameterID
= kAUParameterListener_AnyParameter
;
1686 AUParameterListenerNotify (NULL
, NULL
, &changedUnit
);
1688 CFRelease(propertyList
);
1691 } else if ((fx
= factory_preset_map
.find (preset_label
)) != factory_preset_map
.end()) {
1695 preset
.presetNumber
= fx
->second
;
1696 preset
.presetName
= CFStringCreateWithCString (kCFAllocatorDefault
, fx
->first
.c_str(), kCFStringEncodingUTF8
);
1698 TRACE_API ("set preset from factory presets\n");
1700 if (unit
->SetPresentPreset (preset
) == 0) {
1703 /* tell the world */
1705 AudioUnitParameter changedUnit
;
1706 changedUnit
.mAudioUnit
= unit
->AU();
1707 changedUnit
.mParameterID
= kAUParameterListener_AnyParameter
;
1708 AUParameterListenerNotify (NULL
, NULL
, &changedUnit
);
1714 if (!seen_loading_message
) {
1715 info
<< string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1718 seen_loading_message
= true;
1725 AUPlugin::save_preset (string preset_name
)
1727 #ifdef AU_STATE_SUPPORT
1728 CFPropertyListRef propertyList
;
1729 vector
<Glib::ustring
> v
;
1730 Glib::ustring user_preset_path
;
1733 std::string m
= maker();
1734 std::string n
= name();
1736 strip_whitespace_edges (m
);
1737 strip_whitespace_edges (n
);
1739 v
.push_back (Glib::get_home_dir());
1740 v
.push_back ("Library");
1741 v
.push_back ("Audio");
1742 v
.push_back ("Presets");
1746 user_preset_path
= Glib::build_filename (v
);
1748 if (g_mkdir_with_parents (user_preset_path
.c_str(), 0775) < 0) {
1749 error
<< string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path
) << endmsg
;
1753 TRACE_API ("get current preset\n");
1754 if (unit
->GetAUPreset (propertyList
) != noErr
) {
1758 // add the actual preset name */
1760 v
.push_back (preset_name
+ preset_suffix
);
1764 user_preset_path
= Glib::build_filename (v
);
1766 set_preset_name_in_plist (propertyList
, preset_name
);
1768 if (save_property_list (propertyList
, user_preset_path
)) {
1769 error
<< string_compose (_("Saving plugin state to %1 failed"), user_preset_path
) << endmsg
;
1773 CFRelease(propertyList
);
1777 if (!seen_saving_message
) {
1778 info
<< string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1781 seen_saving_message
= true;
1787 //-----------------------------------------------------------------------------
1788 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1790 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary
, CFStringRef inDictionaryKey
, Boolean
* outSuccess
)
1792 CFNumberRef cfNumber
;
1793 SInt32 numberValue
= 0;
1794 Boolean dummySuccess
;
1796 if (outSuccess
== NULL
)
1797 outSuccess
= &dummySuccess
;
1798 if ( (inAUStateDictionary
== NULL
) || (inDictionaryKey
== NULL
) )
1800 *outSuccess
= FALSE
;
1804 cfNumber
= (CFNumberRef
) CFDictionaryGetValue(inAUStateDictionary
, inDictionaryKey
);
1805 if (cfNumber
== NULL
)
1807 *outSuccess
= FALSE
;
1810 *outSuccess
= CFNumberGetValue(cfNumber
, kCFNumberSInt32Type
, &numberValue
);
1818 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData
, ComponentDescription
* outComponentDescription
)
1820 CFDictionaryRef auStateDictionary
;
1821 ComponentDescription tempDesc
= {0,0,0,0,0};
1822 SInt32 versionValue
;
1825 if ( (inAUStateData
== NULL
) || (outComponentDescription
== NULL
) )
1828 // the property list for AU state data must be of the dictionary type
1829 if (CFGetTypeID(inAUStateData
) != CFDictionaryGetTypeID()) {
1830 return kAudioUnitErr_InvalidPropertyValue
;
1833 auStateDictionary
= (CFDictionaryRef
)inAUStateData
;
1835 // first check to make sure that the version of the AU state data is one that we know understand
1836 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1837 versionValue
= GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetVersionKey
), &gotValue
);
1840 return kAudioUnitErr_InvalidPropertyValue
;
1842 #define kCurrentSavedStateVersion 0
1843 if (versionValue
!= kCurrentSavedStateVersion
) {
1844 return kAudioUnitErr_InvalidPropertyValue
;
1847 // grab the ComponentDescription values from the AU state data
1848 tempDesc
.componentType
= (OSType
) GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetTypeKey
), NULL
);
1849 tempDesc
.componentSubType
= (OSType
) GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetSubtypeKey
), NULL
);
1850 tempDesc
.componentManufacturer
= (OSType
) GetDictionarySInt32Value(auStateDictionary
, CFSTR(kAUPresetManufacturerKey
), NULL
);
1851 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1852 if ( (tempDesc
.componentType
== 0) || (tempDesc
.componentSubType
== 0) || (tempDesc
.componentManufacturer
== 0) )
1853 return kAudioUnitErr_InvalidPropertyValue
;
1855 *outComponentDescription
= tempDesc
;
1860 static bool au_preset_filter (const string
& str
, void* arg
)
1862 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1866 ret
= (str
[0] != '.' && str
.length() > 9 && str
.find (preset_suffix
) == (str
.length() - preset_suffix
.length()));
1870 /* check the preset file path name against this plugin
1871 ID. The idea is that all preset files for this plugin
1872 include "<manufacturer>/<plugin-name>" in their path.
1875 Plugin
* p
= (Plugin
*) arg
;
1876 string match
= p
->maker();
1880 ret
= str
.find (match
) != string::npos
;
1883 string m
= p
->maker ();
1884 string n
= p
->name ();
1885 strip_whitespace_edges (m
);
1886 strip_whitespace_edges (n
);
1891 ret
= str
.find (match
) != string::npos
;
1899 check_and_get_preset_name (Component component
, const string
& pathstr
, string
& preset_name
)
1902 CFPropertyListRef plist
;
1903 ComponentDescription presetDesc
;
1906 plist
= load_property_list (pathstr
);
1912 // get the ComponentDescription from the AU preset file
1914 status
= GetAUComponentDescriptionFromStateData(plist
, &presetDesc
);
1916 if (status
== noErr
) {
1917 if (ComponentAndDescriptionMatch_Loosely(component
, &presetDesc
)) {
1919 /* try to get the preset name from the property list */
1921 if (CFGetTypeID(plist
) == CFDictionaryGetTypeID()) {
1923 const void* psk
= CFDictionaryGetValue ((CFMutableDictionaryRef
)plist
, CFSTR(kAUPresetNameKey
));
1927 const char* p
= CFStringGetCStringPtr ((CFStringRef
) psk
, kCFStringEncodingUTF8
);
1930 char buf
[PATH_MAX
+1];
1932 if (CFStringGetCString ((CFStringRef
)psk
, buf
, sizeof (buf
), kCFStringEncodingUTF8
)) {
1947 AUPlugin::current_preset() const
1951 #ifdef AU_STATE_SUPPORT
1952 CFPropertyListRef propertyList
;
1954 TRACE_API ("get current preset for current_preset()\n");
1955 if (unit
->GetAUPreset (propertyList
) == noErr
) {
1956 preset_name
= get_preset_name_in_plist (propertyList
);
1957 CFRelease(propertyList
);
1964 AUPlugin::find_presets ()
1966 #ifdef AU_STATE_SUPPORT
1967 vector
<string
*>* preset_files
;
1968 PathScanner scanner
;
1970 user_preset_map
.clear ();
1972 preset_files
= scanner (preset_search_path
, au_preset_filter
, this, true, true, -1, true);
1974 if (!preset_files
) {
1978 for (vector
<string
*>::iterator x
= preset_files
->begin(); x
!= preset_files
->end(); ++x
) {
1980 string path
= *(*x
);
1983 /* make an initial guess at the preset name using the path */
1985 preset_name
= Glib::path_get_basename (path
);
1986 preset_name
= preset_name
.substr (0, preset_name
.find_last_of ('.'));
1988 /* check that this preset file really matches this plugin
1989 and potentially get the "real" preset name from
1993 if (check_and_get_preset_name (get_comp()->Comp(), path
, preset_name
)) {
1994 user_preset_map
[preset_name
] = path
;
2000 delete preset_files
;
2002 /* now fill the vector<string> with the names we have */
2004 for (UserPresetMap::iterator i
= user_preset_map
.begin(); i
!= user_preset_map
.end(); ++i
) {
2005 _presets
.insert (i
->second
, Plugin::PresetRecord (i
->second
, i
->first
));
2008 /* add factory presets */
2010 for (FactoryPresetMap::iterator i
= factory_preset_map
.begin(); i
!= factory_preset_map
.end(); ++i
) {
2012 string
const uri
= string_compose ("%1", _presets
.size ());
2013 _presets
.push_back (uri
, Plugin::PresetRecord (uri
, i
->first
));
2020 AUPlugin::has_editor () const
2022 // even if the plugin doesn't have its own editor, the AU API can be used
2023 // to create one that looks native.
2027 AUPluginInfo::AUPluginInfo (boost::shared_ptr
<CAComponentDescription
> d
)
2030 type
= ARDOUR::AudioUnit
;
2033 AUPluginInfo::~AUPluginInfo ()
2035 type
= ARDOUR::AudioUnit
;
2039 AUPluginInfo::load (Session
& session
)
2044 TRACE_API ("load AU as a component\n");
2045 boost::shared_ptr
<CAComponent
> comp (new CAComponent(*descriptor
));
2047 if (!comp
->IsValid()) {
2048 error
<< ("AudioUnit: not a valid Component") << endmsg
;
2050 plugin
.reset (new AUPlugin (session
.engine(), session
, comp
));
2053 AUPluginInfo
*aup
= new AUPluginInfo (*this);
2054 plugin
->set_info (PluginInfoPtr (aup
));
2055 boost::dynamic_pointer_cast
<AUPlugin
> (plugin
)->set_fixed_size_buffers (aup
->creator
== "Universal Audio");
2059 catch (failed_constructor
&err
) {
2060 return PluginPtr ();
2065 AUPluginInfo::au_cache_path ()
2067 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2071 AUPluginInfo::discover ()
2075 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS
)) {
2076 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2079 PluginInfoList
* plugs
= new PluginInfoList
;
2081 discover_fx (*plugs
);
2082 discover_music (*plugs
);
2083 discover_generators (*plugs
);
2084 discover_instruments (*plugs
);
2090 AUPluginInfo::discover_music (PluginInfoList
& plugs
)
2092 CAComponentDescription desc
;
2093 desc
.componentFlags
= 0;
2094 desc
.componentFlagsMask
= 0;
2095 desc
.componentSubType
= 0;
2096 desc
.componentManufacturer
= 0;
2097 desc
.componentType
= kAudioUnitType_MusicEffect
;
2099 discover_by_description (plugs
, desc
);
2103 AUPluginInfo::discover_fx (PluginInfoList
& plugs
)
2105 CAComponentDescription desc
;
2106 desc
.componentFlags
= 0;
2107 desc
.componentFlagsMask
= 0;
2108 desc
.componentSubType
= 0;
2109 desc
.componentManufacturer
= 0;
2110 desc
.componentType
= kAudioUnitType_Effect
;
2112 discover_by_description (plugs
, desc
);
2116 AUPluginInfo::discover_generators (PluginInfoList
& plugs
)
2118 CAComponentDescription desc
;
2119 desc
.componentFlags
= 0;
2120 desc
.componentFlagsMask
= 0;
2121 desc
.componentSubType
= 0;
2122 desc
.componentManufacturer
= 0;
2123 desc
.componentType
= kAudioUnitType_Generator
;
2125 discover_by_description (plugs
, desc
);
2129 AUPluginInfo::discover_instruments (PluginInfoList
& plugs
)
2131 CAComponentDescription desc
;
2132 desc
.componentFlags
= 0;
2133 desc
.componentFlagsMask
= 0;
2134 desc
.componentSubType
= 0;
2135 desc
.componentManufacturer
= 0;
2136 desc
.componentType
= kAudioUnitType_MusicDevice
;
2138 discover_by_description (plugs
, desc
);
2142 AUPluginInfo::discover_by_description (PluginInfoList
& plugs
, CAComponentDescription
& desc
)
2146 comp
= FindNextComponent (NULL
, &desc
);
2148 while (comp
!= NULL
) {
2149 CAComponentDescription temp
;
2150 GetComponentInfo (comp
, &temp
, NULL
, NULL
, NULL
);
2152 AUPluginInfoPtr
info (new AUPluginInfo
2153 (boost::shared_ptr
<CAComponentDescription
> (new CAComponentDescription(temp
))));
2155 /* although apple designed the subtype field to be a "category" indicator,
2156 its really turned into a plugin ID field for a given manufacturer. Hence
2157 there are no categories for AudioUnits. However, to keep the plugins
2158 showing up under "categories", we'll use the "type" as a high level
2161 NOTE: no panners, format converters or i/o AU's for our purposes
2164 switch (info
->descriptor
->Type()) {
2165 case kAudioUnitType_Panner
:
2166 case kAudioUnitType_OfflineEffect
:
2167 case kAudioUnitType_FormatConverter
:
2170 case kAudioUnitType_Output
:
2171 info
->category
= _("AudioUnit Outputs");
2173 case kAudioUnitType_MusicDevice
:
2174 info
->category
= _("AudioUnit Instruments");
2176 case kAudioUnitType_MusicEffect
:
2177 info
->category
= _("AudioUnit MusicEffects");
2179 case kAudioUnitType_Effect
:
2180 info
->category
= _("AudioUnit Effects");
2182 case kAudioUnitType_Mixer
:
2183 info
->category
= _("AudioUnit Mixers");
2185 case kAudioUnitType_Generator
:
2186 info
->category
= _("AudioUnit Generators");
2189 info
->category
= _("AudioUnit (Unknown)");
2193 AUPluginInfo::get_names (temp
, info
->name
, info
->creator
);
2195 info
->type
= ARDOUR::AudioUnit
;
2196 info
->unique_id
= stringify_descriptor (*info
->descriptor
);
2198 /* XXX not sure of the best way to handle plugin versioning yet
2201 CAComponent
cacomp (*info
->descriptor
);
2203 if (cacomp
.GetResourceVersion (info
->version
) != noErr
) {
2207 if (cached_io_configuration (info
->unique_id
, info
->version
, cacomp
, info
->cache
, info
->name
)) {
2209 /* here we have to map apple's wildcard system to a simple pair
2210 of values. in ::can_do() we use the whole system, but here
2211 we need a single pair of values. XXX probably means we should
2212 remove any use of these values.
2215 info
->n_inputs
.set (DataType::AUDIO
, info
->cache
.io_configs
.front().first
);
2216 info
->n_outputs
.set (DataType::AUDIO
, info
->cache
.io_configs
.front().second
);
2218 cerr
<< "detected AU: " << info
->name
.c_str() << " (" << info
->cache
.io_configs
.size() << " i/o configurations) - " << info
->unique_id
<< endl
;
2220 plugs
.push_back (info
);
2223 error
<< string_compose (_("Cannot get I/O configuration info for AU %1"), info
->name
) << endmsg
;
2226 comp
= FindNextComponent (comp
, &desc
);
2231 AUPluginInfo::cached_io_configuration (const std::string
& unique_id
,
2234 AUPluginCachedInfo
& cinfo
,
2235 const std::string
& name
)
2240 /* concatenate unique ID with version to provide a key for cached info lookup.
2241 this ensures we don't get stale information, or should if plugin developers
2242 follow Apple "guidelines".
2245 snprintf (buf
, sizeof (buf
), "%u", (uint32_t) version
);
2250 CachedInfoMap::iterator cim
= cached_info
.find (id
);
2252 if (cim
!= cached_info
.end()) {
2253 cinfo
= cim
->second
;
2258 AUChannelInfo
* channel_info
;
2262 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name
));
2266 if (CAAudioUnit::Open (comp
, unit
) != noErr
) {
2272 warning
<< string_compose (_("Could not load AU plugin %1 - ignored"), name
) << endmsg
;
2273 cerr
<< string_compose (_("Could not load AU plugin %1 - ignored"), name
) << endl
;
2278 TRACE_API ("get AU channel info\n");
2279 if ((ret
= unit
.GetChannelInfo (&channel_info
, cnt
)) < 0) {
2284 /* no explicit info available */
2286 cinfo
.io_configs
.push_back (pair
<int,int> (-1, -1));
2290 /* store each configuration */
2292 for (uint32_t n
= 0; n
< cnt
; ++n
) {
2293 cinfo
.io_configs
.push_back (pair
<int,int> (channel_info
[n
].inChannels
,
2294 channel_info
[n
].outChannels
));
2297 free (channel_info
);
2300 add_cached_info (id
, cinfo
);
2301 save_cached_info ();
2307 AUPluginInfo::add_cached_info (const std::string
& id
, AUPluginCachedInfo
& cinfo
)
2309 cached_info
[id
] = cinfo
;
2312 #define AU_CACHE_VERSION "2.0"
2315 AUPluginInfo::save_cached_info ()
2319 node
= new XMLNode (X_("AudioUnitPluginCache"));
2320 node
->add_property( "version", AU_CACHE_VERSION
);
2322 for (map
<string
,AUPluginCachedInfo
>::iterator i
= cached_info
.begin(); i
!= cached_info
.end(); ++i
) {
2323 XMLNode
* parent
= new XMLNode (X_("plugin"));
2324 parent
->add_property ("id", i
->first
);
2325 node
->add_child_nocopy (*parent
);
2327 for (vector
<pair
<int, int> >::iterator j
= i
->second
.io_configs
.begin(); j
!= i
->second
.io_configs
.end(); ++j
) {
2329 XMLNode
* child
= new XMLNode (X_("io"));
2332 snprintf (buf
, sizeof (buf
), "%d", j
->first
);
2333 child
->add_property (X_("in"), buf
);
2334 snprintf (buf
, sizeof (buf
), "%d", j
->second
);
2335 child
->add_property (X_("out"), buf
);
2336 parent
->add_child_nocopy (*child
);
2341 Glib::ustring path
= au_cache_path ();
2344 tree
.set_root (node
);
2346 if (!tree
.write (path
)) {
2347 error
<< string_compose (_("could not save AU cache to %1"), path
) << endmsg
;
2348 unlink (path
.c_str());
2353 AUPluginInfo::load_cached_info ()
2355 Glib::ustring path
= au_cache_path ();
2358 if (!Glib::file_test (path
, Glib::FILE_TEST_EXISTS
)) {
2362 if ( !tree
.read (path
) ) {
2363 error
<< "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg
;
2367 const XMLNode
* root (tree
.root());
2369 if (root
->name() != X_("AudioUnitPluginCache")) {
2373 //initial version has incorrectly stored i/o info, and/or garbage chars.
2374 const XMLProperty
* version
= root
->property(X_("version"));
2375 if (! ((version
!= NULL
) && (version
->value() == X_(AU_CACHE_VERSION
)))) {
2376 error
<< "au_cache is not correct version. AU plugins will be re-scanned" << endmsg
;
2380 cached_info
.clear ();
2382 const XMLNodeList children
= root
->children();
2384 for (XMLNodeConstIterator iter
= children
.begin(); iter
!= children
.end(); ++iter
) {
2386 const XMLNode
* child
= *iter
;
2388 if (child
->name() == X_("plugin")) {
2390 const XMLNode
* gchild
;
2391 const XMLNodeList gchildren
= child
->children();
2392 const XMLProperty
* prop
= child
->property (X_("id"));
2398 string id
= prop
->value();
2402 string::size_type slash
= id
.find_last_of ('/');
2404 if (slash
== string::npos
) {
2408 version
= id
.substr (slash
);
2409 id
= id
.substr (0, slash
);
2410 fixed
= AUPlugin::maybe_fix_broken_au_id (id
);
2412 if (fixed
.empty()) {
2413 error
<< string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id
) << endmsg
;
2420 AUPluginCachedInfo cinfo
;
2422 for (XMLNodeConstIterator giter
= gchildren
.begin(); giter
!= gchildren
.end(); giter
++) {
2426 if (gchild
->name() == X_("io")) {
2430 const XMLProperty
* iprop
;
2431 const XMLProperty
* oprop
;
2433 if (((iprop
= gchild
->property (X_("in"))) != 0) &&
2434 ((oprop
= gchild
->property (X_("out"))) != 0)) {
2435 in
= atoi (iprop
->value());
2436 out
= atoi (oprop
->value());
2438 cinfo
.io_configs
.push_back (pair
<int,int> (in
, out
));
2443 if (cinfo
.io_configs
.size()) {
2444 add_cached_info (id
, cinfo
);
2453 AUPluginInfo::get_names (CAComponentDescription
& comp_desc
, std::string
& name
, std::string
& maker
)
2455 CFStringRef itemName
= NULL
;
2457 // Marc Poirier-style item name
2458 CAComponent
auComponent (comp_desc
);
2459 if (auComponent
.IsValid()) {
2460 CAComponentDescription dummydesc
;
2461 Handle nameHandle
= NewHandle(sizeof(void*));
2462 if (nameHandle
!= NULL
) {
2463 OSErr err
= GetComponentInfo(auComponent
.Comp(), &dummydesc
, nameHandle
, NULL
, NULL
);
2465 ConstStr255Param nameString
= (ConstStr255Param
) (*nameHandle
);
2466 if (nameString
!= NULL
) {
2467 itemName
= CFStringCreateWithPascalString(kCFAllocatorDefault
, nameString
, CFStringGetSystemEncoding());
2470 DisposeHandle(nameHandle
);
2474 // if Marc-style fails, do the original way
2475 if (itemName
== NULL
) {
2476 CFStringRef compTypeString
= UTCreateStringForOSType(comp_desc
.componentType
);
2477 CFStringRef compSubTypeString
= UTCreateStringForOSType(comp_desc
.componentSubType
);
2478 CFStringRef compManufacturerString
= UTCreateStringForOSType(comp_desc
.componentManufacturer
);
2480 itemName
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("%@ - %@ - %@"),
2481 compTypeString
, compManufacturerString
, compSubTypeString
);
2483 if (compTypeString
!= NULL
)
2484 CFRelease(compTypeString
);
2485 if (compSubTypeString
!= NULL
)
2486 CFRelease(compSubTypeString
);
2487 if (compManufacturerString
!= NULL
)
2488 CFRelease(compManufacturerString
);
2491 string str
= CFStringRefToStdString(itemName
);
2492 string::size_type colon
= str
.find (':');
2495 name
= str
.substr (colon
+1);
2496 maker
= str
.substr (0, colon
);
2497 strip_whitespace_edges (maker
);
2498 strip_whitespace_edges (name
);
2502 strip_whitespace_edges (name
);
2507 AUPluginInfo::stringify_descriptor (const CAComponentDescription
& desc
)
2511 /* note: OSType is a compiler-implemenation-defined value,
2512 historically a 32 bit integer created with a multi-character
2513 constant such as 'abcd'. It is, fundamentally, an abomination.
2518 s
<< desc
.SubType();
2526 AUPluginInfo::needs_midi_input ()
2528 return is_effect_with_midi_input () || is_instrument ();
2532 AUPluginInfo::is_effect () const
2534 return is_effect_without_midi_input() || is_effect_with_midi_input();
2538 AUPluginInfo::is_effect_without_midi_input () const
2540 return descriptor
->IsAUFX();
2544 AUPluginInfo::is_effect_with_midi_input () const
2546 return descriptor
->IsAUFM();
2550 AUPluginInfo::is_instrument () const
2552 return descriptor
->IsMusicDevice();