~ubuntu-branches/ubuntu/utopic/ardour3/utopic

« back to all changes in this revision

Viewing changes to libs/ardour/audio_unit.cc

  • Committer: Package Import Robot
  • Author(s): Felipe Sateler
  • Date: 2013-09-21 19:05:02 UTC
  • Revision ID: package-import@ubuntu.com-20130921190502-8gsftrku6jnzhd7v
Tags: upstream-3.4~dfsg
ImportĀ upstreamĀ versionĀ 3.4~dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
    Copyright (C) 2006-2009 Paul Davis
 
3
    Some portions Copyright (C) Sophia Poirier.
 
4
 
 
5
    This program is free software; you can redistribute it and/or modify
 
6
    it under the terms of the GNU General Public License as published by
 
7
    the Free Software Foundation; either version 2 of the License, or
 
8
    (at your option) any later version.
 
9
 
 
10
    This program is distributed in the hope that it will be useful,
 
11
    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
    GNU General Public License for more details.
 
14
 
 
15
    You should have received a copy of the GNU General Public License
 
16
    along with this program; if not, write to the Free Software
 
17
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
18
 
 
19
*/
 
20
 
 
21
#include <sstream>
 
22
#include <errno.h>
 
23
#include <string.h>
 
24
#include <math.h>
 
25
#include <ctype.h>
 
26
 
 
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"
 
33
 
 
34
#include <glibmm/threads.h>
 
35
#include <glibmm/fileutils.h>
 
36
#include <glibmm/miscutils.h>
 
37
 
 
38
#include "ardour/ardour.h"
 
39
#include "ardour/audioengine.h"
 
40
#include "ardour/audio_buffer.h"
 
41
#include "ardour/debug.h"
 
42
#include "ardour/midi_buffer.h"
 
43
#include "ardour/filesystem_paths.h"
 
44
#include "ardour/io.h"
 
45
#include "ardour/audio_unit.h"
 
46
#include "ardour/route.h"
 
47
#include "ardour/session.h"
 
48
#include "ardour/tempo.h"
 
49
#include "ardour/utils.h"
 
50
 
 
51
#include "appleutility/CAAudioUnit.h"
 
52
#include "appleutility/CAAUParameter.h"
 
53
 
 
54
#include <CoreFoundation/CoreFoundation.h>
 
55
#include <CoreServices/CoreServices.h>
 
56
#include <AudioUnit/AudioUnit.h>
 
57
#include <AudioToolbox/AudioUnitUtilities.h>
 
58
#ifdef WITH_CARBON
 
59
#include <Carbon/Carbon.h>
 
60
#endif
 
61
 
 
62
#include "i18n.h"
 
63
 
 
64
using namespace std;
 
65
using namespace PBD;
 
66
using namespace ARDOUR;
 
67
 
 
68
AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
 
69
 
 
70
static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
 
71
static string preset_suffix = ".aupreset";
 
72
static bool preset_search_path_initialized = false;
 
73
 
 
74
static OSStatus
 
75
_render_callback(void *userData,
 
76
                 AudioUnitRenderActionFlags *ioActionFlags,
 
77
                 const AudioTimeStamp    *inTimeStamp,
 
78
                 UInt32       inBusNumber,
 
79
                 UInt32       inNumberFrames,
 
80
                 AudioBufferList*       ioData)
 
81
{
 
82
        if (userData) {
 
83
                return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
 
84
        }
 
85
        return paramErr;
 
86
}
 
87
 
 
88
static OSStatus
 
89
_get_beat_and_tempo_callback (void*    userData,
 
90
                              Float64* outCurrentBeat,
 
91
                              Float64* outCurrentTempo)
 
92
{
 
93
        if (userData) {
 
94
                return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
 
95
        }
 
96
 
 
97
        return paramErr;
 
98
}
 
99
 
 
100
static OSStatus
 
101
_get_musical_time_location_callback (void *     userData,
 
102
                                     UInt32 *   outDeltaSampleOffsetToNextBeat,
 
103
                                     Float32 *  outTimeSig_Numerator,
 
104
                                     UInt32 *   outTimeSig_Denominator,
 
105
                                     Float64 *  outCurrentMeasureDownBeat)
 
106
{
 
107
        if (userData) {
 
108
                return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
 
109
                                                                                  outTimeSig_Numerator,
 
110
                                                                                  outTimeSig_Denominator,
 
111
                                                                                  outCurrentMeasureDownBeat);
 
112
        }
 
113
        return paramErr;
 
114
}
 
115
 
 
116
static OSStatus
 
117
_get_transport_state_callback (void*     userData,
 
118
                               Boolean*  outIsPlaying,
 
119
                               Boolean*  outTransportStateChanged,
 
120
                               Float64*  outCurrentSampleInTimeLine,
 
121
                               Boolean*  outIsCycling,
 
122
                               Float64*  outCycleStartBeat,
 
123
                               Float64*  outCycleEndBeat)
 
124
{
 
125
        if (userData) {
 
126
                return ((AUPlugin*)userData)->get_transport_state_callback (
 
127
                        outIsPlaying, outTransportStateChanged,
 
128
                        outCurrentSampleInTimeLine, outIsCycling,
 
129
                        outCycleStartBeat, outCycleEndBeat);
 
130
        }
 
131
        return paramErr;
 
132
}
 
133
 
 
134
 
 
135
static int
 
136
save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
 
137
 
 
138
{
 
139
        CFDataRef xmlData;
 
140
        int fd;
 
141
 
 
142
        // Convert the property list into XML data.
 
143
 
 
144
        xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
 
145
 
 
146
        if (!xmlData) {
 
147
                error << _("Could not create XML version of property list") << endmsg;
 
148
                return -1;
 
149
        }
 
150
 
 
151
        // Write the XML data to the file.
 
152
 
 
153
        fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
 
154
        while (fd < 0) {
 
155
                if (errno == EEXIST) {
 
156
                        error << string_compose (_("Preset file %1 exists; not overwriting"),
 
157
                                                 path) << endmsg;
 
158
                } else {
 
159
                        error << string_compose (_("Cannot open preset file %1 (%2)"),
 
160
                                                 path, strerror (errno)) << endmsg;
 
161
                }
 
162
                CFRelease (xmlData);
 
163
                return -1;
 
164
        }
 
165
 
 
166
        size_t cnt = CFDataGetLength (xmlData);
 
167
 
 
168
        if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
 
169
                CFRelease (xmlData);
 
170
                close (fd);
 
171
                return -1;
 
172
        }
 
173
 
 
174
        close (fd);
 
175
        return 0;
 
176
}
 
177
 
 
178
 
 
179
static CFPropertyListRef
 
180
load_property_list (Glib::ustring path)
 
181
{
 
182
        int fd;
 
183
        CFPropertyListRef propertyList = 0;
 
184
        CFDataRef         xmlData;
 
185
        CFStringRef       errorString;
 
186
 
 
187
        // Read the XML file.
 
188
 
 
189
        if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
 
190
                return propertyList;
 
191
 
 
192
        }
 
193
 
 
194
        off_t len = lseek (fd, 0, SEEK_END);
 
195
        char* buf = new char[len];
 
196
        lseek (fd, 0, SEEK_SET);
 
197
 
 
198
        if (read (fd, buf, len) != len) {
 
199
                delete [] buf;
 
200
                close (fd);
 
201
                return propertyList;
 
202
        }
 
203
 
 
204
        close (fd);
 
205
 
 
206
        xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
 
207
 
 
208
        // Reconstitute the dictionary using the XML data.
 
209
 
 
210
        propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
 
211
                                                        xmlData,
 
212
                                                        kCFPropertyListImmutable,
 
213
                                                        &errorString);
 
214
 
 
215
        CFRelease (xmlData);
 
216
        delete [] buf;
 
217
 
 
218
        return propertyList;
 
219
}
 
220
 
 
221
//-----------------------------------------------------------------------------
 
222
static void
 
223
set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
 
224
{
 
225
        if (!plist) {
 
226
                return;
 
227
        }
 
228
        CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
 
229
 
 
230
        if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
 
231
                CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
 
232
        }
 
233
 
 
234
        CFRelease (pn);
 
235
}
 
236
 
 
237
//-----------------------------------------------------------------------------
 
238
static std::string
 
239
get_preset_name_in_plist (CFPropertyListRef plist)
 
240
{
 
241
        std::string ret;
 
242
 
 
243
        if (!plist) {
 
244
                return ret;
 
245
        }
 
246
 
 
247
        if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
 
248
                const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
 
249
                if (p) {
 
250
                        CFStringRef str = (CFStringRef) p;
 
251
                        int len = CFStringGetLength(str);
 
252
                        len =  (len * 2) + 1;
 
253
                        char local_buffer[len];
 
254
                        if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
 
255
                                ret = local_buffer;
 
256
                        }
 
257
                }
 
258
        }
 
259
        return ret;
 
260
}
 
261
 
 
262
//--------------------------------------------------------------------------
 
263
// general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
 
264
// if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
 
265
Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
 
266
Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
 
267
{
 
268
        if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
 
269
                return FALSE;
 
270
 
 
271
        if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
 
272
                        && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
 
273
        {
 
274
                // only sub-type and manufacturer IDs need to be equal
 
275
                if (inIgnoreType)
 
276
                        return TRUE;
 
277
                // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
 
278
                else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
 
279
                        return TRUE;
 
280
        }
 
281
 
 
282
        return FALSE;
 
283
}
 
284
 
 
285
//--------------------------------------------------------------------------
 
286
// general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
 
287
// if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
 
288
Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
 
289
Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
 
290
{
 
291
        OSErr status;
 
292
        ComponentDescription desc;
 
293
 
 
294
        if ( (inComponent == NULL) || (inComponentDescription == NULL) )
 
295
                return FALSE;
 
296
 
 
297
        // get the ComponentDescription of the input Component
 
298
        status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
 
299
        if (status != noErr)
 
300
                return FALSE;
 
301
 
 
302
        // check if the Component's ComponentDescription matches the input ComponentDescription
 
303
        return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
 
304
}
 
305
 
 
306
//--------------------------------------------------------------------------
 
307
// determine if 2 ComponentDescriptions are basically equal
 
308
// (by that, I mean that the important identifying values are compared,
 
309
// but not the ComponentDescription flags)
 
310
Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
 
311
{
 
312
        return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
 
313
}
 
314
 
 
315
//--------------------------------------------------------------------------
 
316
// determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
 
317
Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
 
318
{
 
319
        return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
 
320
}
 
321
 
 
322
//--------------------------------------------------------------------------
 
323
// determine if a ComponentDescription basically matches that of a particular Component
 
324
Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
 
325
{
 
326
        return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
 
327
}
 
328
 
 
329
//--------------------------------------------------------------------------
 
330
// determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
 
331
Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
 
332
{
 
333
        return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
 
334
}
 
335
 
 
336
 
 
337
AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
 
338
        : Plugin (engine, session)
 
339
        , comp (_comp)
 
340
        , unit (new CAAudioUnit)
 
341
        , initialized (false)
 
342
        , _current_block_size (0)
 
343
        , _requires_fixed_size_buffers (false)
 
344
        , buffers (0)
 
345
        , input_maxbuf (0)
 
346
        , input_offset (0)
 
347
        , input_buffers (0)
 
348
        , frames_processed (0)
 
349
        , _parameter_listener (0)
 
350
        , _parameter_listener_arg (0)
 
351
        , last_transport_rolling (false)
 
352
        , last_transport_speed (0.0)
 
353
{
 
354
        if (!preset_search_path_initialized) {
 
355
                Glib::ustring p = Glib::get_home_dir();
 
356
                p += "/Library/Audio/Presets:";
 
357
                p += preset_search_path;
 
358
                preset_search_path = p;
 
359
                preset_search_path_initialized = true;
 
360
        }
 
361
 
 
362
        init ();
 
363
}
 
364
 
 
365
 
 
366
AUPlugin::AUPlugin (const AUPlugin& other)
 
367
        : Plugin (other)
 
368
        , comp (other.get_comp())
 
369
        , unit (new CAAudioUnit)
 
370
        , initialized (false)
 
371
        , _current_block_size (0)
 
372
        , _last_nframes (0)
 
373
        , _requires_fixed_size_buffers (false)
 
374
        , buffers (0)
 
375
        , input_maxbuf (0)
 
376
        , input_offset (0)
 
377
        , input_buffers (0)
 
378
        , frames_processed (0)
 
379
        , _parameter_listener (0)
 
380
        , _parameter_listener_arg (0)
 
381
 
 
382
{
 
383
        init ();
 
384
}
 
385
 
 
386
AUPlugin::~AUPlugin ()
 
387
{
 
388
        if (_parameter_listener) {
 
389
                AUListenerDispose (_parameter_listener);
 
390
                _parameter_listener = 0;
 
391
        }
 
392
        
 
393
        if (unit) {
 
394
                DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
 
395
                unit->Uninitialize ();
 
396
        }
 
397
 
 
398
        if (buffers) {
 
399
                free (buffers);
 
400
        }
 
401
}
 
402
 
 
403
void
 
404
AUPlugin::discover_factory_presets ()
 
405
{
 
406
        CFArrayRef presets;
 
407
        UInt32 dataSize;
 
408
        Boolean isWritable;
 
409
        OSStatus err;
 
410
 
 
411
        if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
 
412
                DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
 
413
                return;
 
414
        }
 
415
 
 
416
        assert (dataSize == sizeof (presets));
 
417
 
 
418
        if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
 
419
                error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
 
420
                return;
 
421
        }
 
422
 
 
423
        if (!presets) {
 
424
                return;
 
425
        }
 
426
 
 
427
        CFIndex cnt = CFArrayGetCount (presets);
 
428
 
 
429
        for (CFIndex i = 0; i < cnt; ++i) {
 
430
                AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
 
431
 
 
432
                string name = CFStringRefToStdString (preset->presetName);
 
433
                factory_preset_map[name] = preset->presetNumber;
 
434
        }
 
435
 
 
436
        CFRelease (presets);
 
437
}
 
438
 
 
439
void
 
440
AUPlugin::init ()
 
441
{
 
442
        OSErr err;
 
443
 
 
444
        /* these keep track of *configured* channel set up,
 
445
           not potential set ups.
 
446
        */
 
447
 
 
448
        input_channels = -1;
 
449
        output_channels = -1;
 
450
 
 
451
        try {
 
452
                DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
 
453
                err = CAAudioUnit::Open (*(comp.get()), *unit);
 
454
        } catch (...) {
 
455
                error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
 
456
                throw failed_constructor();
 
457
        }
 
458
 
 
459
        if (err != noErr) {
 
460
                error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
 
461
                throw failed_constructor ();
 
462
        }
 
463
 
 
464
        DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
 
465
        unit->GetElementCount (kAudioUnitScope_Global, global_elements);
 
466
        DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
 
467
        unit->GetElementCount (kAudioUnitScope_Input, input_elements);
 
468
        DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
 
469
        unit->GetElementCount (kAudioUnitScope_Output, output_elements);
 
470
 
 
471
        if (input_elements > 0) {
 
472
                /* setup render callback: the plugin calls this to get input data 
 
473
                 */
 
474
                
 
475
                AURenderCallbackStruct renderCallbackInfo;
 
476
                
 
477
                renderCallbackInfo.inputProc = _render_callback;
 
478
                renderCallbackInfo.inputProcRefCon = this;
 
479
                
 
480
                DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
 
481
                if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
 
482
                                              0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
 
483
                        error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
 
484
                        throw failed_constructor();
 
485
                }
 
486
        }
 
487
 
 
488
        /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
 
489
 
 
490
        HostCallbackInfo info;
 
491
        memset (&info, 0, sizeof (HostCallbackInfo));
 
492
        info.hostUserData = this;
 
493
        info.beatAndTempoProc = _get_beat_and_tempo_callback;
 
494
        info.musicalTimeLocationProc = _get_musical_time_location_callback;
 
495
        info.transportStateProc = _get_transport_state_callback;
 
496
 
 
497
        //ignore result of this - don't care if the property isn't supported
 
498
        DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
 
499
        unit->SetProperty (kAudioUnitProperty_HostCallbacks,
 
500
                           kAudioUnitScope_Global,
 
501
                           0, //elementID
 
502
                           &info,
 
503
                           sizeof (HostCallbackInfo));
 
504
 
 
505
        if (set_block_size (_session.get_block_size())) {
 
506
                error << _("AUPlugin: cannot set processing block size") << endmsg;
 
507
                throw failed_constructor();
 
508
        }
 
509
 
 
510
        create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
 
511
        discover_parameters ();
 
512
        discover_factory_presets ();
 
513
 
 
514
        // Plugin::setup_controls ();
 
515
}
 
516
 
 
517
void
 
518
AUPlugin::discover_parameters ()
 
519
{
 
520
        /* discover writable parameters */
 
521
 
 
522
        AudioUnitScope scopes[] = {
 
523
                kAudioUnitScope_Global,
 
524
                kAudioUnitScope_Output,
 
525
                kAudioUnitScope_Input
 
526
        };
 
527
 
 
528
        descriptors.clear ();
 
529
 
 
530
        for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
 
531
 
 
532
                AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
 
533
 
 
534
                for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
 
535
 
 
536
                        AUParameterDescriptor d;
 
537
 
 
538
                        d.id = param_info.ParamID (i);
 
539
 
 
540
                        const CAAUParameter* param = param_info.GetParamInfo (d.id);
 
541
                        const AudioUnitParameterInfo& info (param->ParamInfo());
 
542
 
 
543
                        const int len = CFStringGetLength (param->GetName());;
 
544
                        char local_buffer[len*2];
 
545
                        Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
 
546
                        if (!good) {
 
547
                                d.label = "???";
 
548
                        } else {
 
549
                                d.label = local_buffer;
 
550
                        }
 
551
 
 
552
                        d.scope = param_info.GetScope ();
 
553
                        d.element = param_info.GetElement ();
 
554
 
 
555
                        /* info.units to consider */
 
556
                        /*
 
557
                          kAudioUnitParameterUnit_Generic             = 0
 
558
                          kAudioUnitParameterUnit_Indexed             = 1
 
559
                          kAudioUnitParameterUnit_Boolean             = 2
 
560
                          kAudioUnitParameterUnit_Percent             = 3
 
561
                          kAudioUnitParameterUnit_Seconds             = 4
 
562
                          kAudioUnitParameterUnit_SampleFrames        = 5
 
563
                          kAudioUnitParameterUnit_Phase               = 6
 
564
                          kAudioUnitParameterUnit_Rate                = 7
 
565
                          kAudioUnitParameterUnit_Hertz               = 8
 
566
                          kAudioUnitParameterUnit_Cents               = 9
 
567
                          kAudioUnitParameterUnit_RelativeSemiTones   = 10
 
568
                          kAudioUnitParameterUnit_MIDINoteNumber      = 11
 
569
                          kAudioUnitParameterUnit_MIDIController      = 12
 
570
                          kAudioUnitParameterUnit_Decibels            = 13
 
571
                          kAudioUnitParameterUnit_LinearGain          = 14
 
572
                          kAudioUnitParameterUnit_Degrees             = 15
 
573
                          kAudioUnitParameterUnit_EqualPowerCrossfade = 16
 
574
                          kAudioUnitParameterUnit_MixerFaderCurve1    = 17
 
575
                          kAudioUnitParameterUnit_Pan                 = 18
 
576
                          kAudioUnitParameterUnit_Meters              = 19
 
577
                          kAudioUnitParameterUnit_AbsoluteCents       = 20
 
578
                          kAudioUnitParameterUnit_Octaves             = 21
 
579
                          kAudioUnitParameterUnit_BPM                 = 22
 
580
                          kAudioUnitParameterUnit_Beats               = 23
 
581
                          kAudioUnitParameterUnit_Milliseconds        = 24
 
582
                          kAudioUnitParameterUnit_Ratio               = 25
 
583
                        */
 
584
 
 
585
                        /* info.flags to consider */
 
586
 
 
587
                        /*
 
588
 
 
589
                          kAudioUnitParameterFlag_CFNameRelease       = (1L << 4)
 
590
                          kAudioUnitParameterFlag_HasClump            = (1L << 20)
 
591
                          kAudioUnitParameterFlag_HasName             = (1L << 21)
 
592
                          kAudioUnitParameterFlag_DisplayLogarithmic  = (1L << 22)
 
593
                          kAudioUnitParameterFlag_IsHighResolution    = (1L << 23)
 
594
                          kAudioUnitParameterFlag_NonRealTime         = (1L << 24)
 
595
                          kAudioUnitParameterFlag_CanRamp             = (1L << 25)
 
596
                          kAudioUnitParameterFlag_ExpertMode          = (1L << 26)
 
597
                          kAudioUnitParameterFlag_HasCFNameString     = (1L << 27)
 
598
                          kAudioUnitParameterFlag_IsGlobalMeta        = (1L << 28)
 
599
                          kAudioUnitParameterFlag_IsElementMeta       = (1L << 29)
 
600
                          kAudioUnitParameterFlag_IsReadable          = (1L << 30)
 
601
                          kAudioUnitParameterFlag_IsWritable          = (1L << 31)
 
602
                        */
 
603
 
 
604
                        d.lower = info.minValue;
 
605
                        d.upper = info.maxValue;
 
606
                        d.default_value = info.defaultValue;
 
607
 
 
608
                        d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
 
609
                        d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
 
610
                                (d.integer_step && ((d.upper - d.lower) == 1.0));
 
611
                        d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
 
612
                        d.automatable = !d.toggled &&
 
613
                                !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
 
614
                                (info.flags & kAudioUnitParameterFlag_IsWritable);
 
615
 
 
616
                        d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
 
617
                        d.unit = info.unit;
 
618
 
 
619
                        d.step = 1.0;
 
620
                        d.smallstep = 0.1;
 
621
                        d.largestep = 10.0;
 
622
                        d.min_unbound = 0; // lower is bound
 
623
                        d.max_unbound = 0; // upper is bound
 
624
 
 
625
                        descriptors.push_back (d);
 
626
 
 
627
                        uint32_t last_param = descriptors.size() - 1;
 
628
                        parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
 
629
                        listen_to_parameter (last_param);
 
630
                }
 
631
        }
 
632
}
 
633
 
 
634
 
 
635
static unsigned int
 
636
four_ints_to_four_byte_literal (unsigned char n[4])
 
637
{
 
638
        /* this is actually implementation dependent. sigh. this is what gcc
 
639
           and quite a few others do.
 
640
         */
 
641
        return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
 
642
}
 
643
 
 
644
std::string
 
645
AUPlugin::maybe_fix_broken_au_id (const std::string& id)
 
646
{
 
647
        if (isdigit (id[0])) {
 
648
                return id;
 
649
        }
 
650
 
 
651
        /* ID format is xxxx-xxxx-xxxx
 
652
           where x maybe \xNN or a printable character.
 
653
 
 
654
           Split at the '-' and and process each part into an integer.
 
655
           Then put it back together.
 
656
        */
 
657
 
 
658
 
 
659
        unsigned char nascent[4];
 
660
        const char* cstr = id.c_str();
 
661
        const char* estr = cstr + id.size();
 
662
        uint32_t n[3];
 
663
        int in;
 
664
        int next_int;
 
665
        char short_buf[3];
 
666
        stringstream s;
 
667
 
 
668
        in = 0;
 
669
        next_int = 0;
 
670
        short_buf[2] = '\0';
 
671
 
 
672
        while (*cstr && next_int < 4) {
 
673
 
 
674
                if (*cstr == '\\') {
 
675
 
 
676
                        if (estr - cstr < 3) {
 
677
 
 
678
                                /* too close to the end for \xNN parsing: treat as literal characters */
 
679
 
 
680
                                nascent[in] = *cstr;
 
681
                                ++cstr;
 
682
                                ++in;
 
683
 
 
684
                        } else {
 
685
 
 
686
                                if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
 
687
 
 
688
                                        /* parse \xNN */
 
689
 
 
690
                                        memcpy (short_buf, &cstr[2], 2);
 
691
                                        nascent[in] = strtol (short_buf, NULL, 16);
 
692
                                        cstr += 4;
 
693
                                        ++in;
 
694
 
 
695
                                } else {
 
696
 
 
697
                                        /* treat as literal characters */
 
698
                                        nascent[in] = *cstr;
 
699
                                        ++cstr;
 
700
                                        ++in;
 
701
                                }
 
702
                        }
 
703
 
 
704
                } else {
 
705
 
 
706
                        nascent[in] = *cstr;
 
707
                        ++cstr;
 
708
                        ++in;
 
709
                }
 
710
 
 
711
                if (in && (in % 4 == 0)) {
 
712
                        /* nascent is ready */
 
713
                        n[next_int] = four_ints_to_four_byte_literal (nascent);
 
714
                        in = 0;
 
715
                        next_int++;
 
716
 
 
717
                        /* swallow space-hyphen-space */
 
718
 
 
719
                        if (next_int < 3) {
 
720
                                ++cstr;
 
721
                                ++cstr;
 
722
                                ++cstr;
 
723
                        }
 
724
                }
 
725
        }
 
726
 
 
727
        if (next_int != 3) {
 
728
                goto err;
 
729
        }
 
730
 
 
731
        s << n[0] << '-' << n[1] << '-' << n[2];
 
732
 
 
733
        return s.str();
 
734
 
 
735
  err:
 
736
        return string();
 
737
}
 
738
 
 
739
string
 
740
AUPlugin::unique_id () const
 
741
{
 
742
        return AUPluginInfo::stringify_descriptor (comp->Desc());
 
743
}
 
744
 
 
745
const char *
 
746
AUPlugin::label () const
 
747
{
 
748
        return _info->name.c_str();
 
749
}
 
750
 
 
751
uint32_t
 
752
AUPlugin::parameter_count () const
 
753
{
 
754
        return descriptors.size();
 
755
}
 
756
 
 
757
float
 
758
AUPlugin::default_value (uint32_t port)
 
759
{
 
760
        if (port < descriptors.size()) {
 
761
                return descriptors[port].default_value;
 
762
        }
 
763
 
 
764
        return 0;
 
765
}
 
766
 
 
767
framecnt_t
 
768
AUPlugin::signal_latency () const
 
769
{
 
770
        return unit->Latency() * _session.frame_rate();
 
771
}
 
772
 
 
773
void
 
774
AUPlugin::set_parameter (uint32_t which, float val)
 
775
{
 
776
        if (which >= descriptors.size()) {
 
777
                return;
 
778
        }
 
779
 
 
780
        if (get_parameter(which) == val) {
 
781
                return;
 
782
        }
 
783
 
 
784
        const AUParameterDescriptor& d (descriptors[which]);
 
785
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
 
786
        unit->SetParameter (d.id, d.scope, d.element, val);
 
787
 
 
788
        /* tell the world what we did */
 
789
 
 
790
        AudioUnitEvent theEvent;
 
791
 
 
792
        theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
 
793
        theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
 
794
        theEvent.mArgument.mParameter.mParameterID = d.id;
 
795
        theEvent.mArgument.mParameter.mScope = d.scope;
 
796
        theEvent.mArgument.mParameter.mElement = d.element;
 
797
 
 
798
        DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
 
799
        AUEventListenerNotify (NULL, NULL, &theEvent);
 
800
 
 
801
        Plugin::set_parameter (which, val);
 
802
}
 
803
 
 
804
float
 
805
AUPlugin::get_parameter (uint32_t which) const
 
806
{
 
807
        float val = 0.0;
 
808
        if (which < descriptors.size()) {
 
809
                const AUParameterDescriptor& d (descriptors[which]);
 
810
                // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
 
811
                unit->GetParameter(d.id, d.scope, d.element, val);
 
812
        }
 
813
        return val;
 
814
}
 
815
 
 
816
int
 
817
AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
 
818
{
 
819
        if (which < descriptors.size()) {
 
820
                pd = descriptors[which];
 
821
                return 0;
 
822
        }
 
823
        return -1;
 
824
}
 
825
 
 
826
uint32_t
 
827
AUPlugin::nth_parameter (uint32_t which, bool& ok) const
 
828
{
 
829
        if (which < descriptors.size()) {
 
830
                ok = true;
 
831
                return which;
 
832
        }
 
833
        ok = false;
 
834
        return 0;
 
835
}
 
836
 
 
837
void
 
838
AUPlugin::activate ()
 
839
{
 
840
        if (!initialized) {
 
841
                OSErr err;
 
842
                DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
 
843
                if ((err = unit->Initialize()) != noErr) {
 
844
                        error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
 
845
                } else {
 
846
                        frames_processed = 0;
 
847
                        initialized = true;
 
848
                }
 
849
        }
 
850
}
 
851
 
 
852
void
 
853
AUPlugin::deactivate ()
 
854
{
 
855
        DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
 
856
        unit->Uninitialize ();
 
857
        initialized = false;
 
858
}
 
859
 
 
860
void
 
861
AUPlugin::flush ()
 
862
{
 
863
        DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
 
864
        unit->GlobalReset ();
 
865
}
 
866
 
 
867
bool
 
868
AUPlugin::requires_fixed_size_buffers() const
 
869
{
 
870
        return _requires_fixed_size_buffers;
 
871
}
 
872
 
 
873
 
 
874
int
 
875
AUPlugin::set_block_size (pframes_t nframes)
 
876
{
 
877
        bool was_initialized = initialized;
 
878
        UInt32 numFrames = nframes;
 
879
        OSErr err;
 
880
 
 
881
        if (initialized) {
 
882
                deactivate ();
 
883
        }
 
884
 
 
885
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
 
886
        if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
 
887
                                      0, &numFrames, sizeof (numFrames))) != noErr) {
 
888
                error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
 
889
                return -1;
 
890
        }
 
891
 
 
892
        if (was_initialized) {
 
893
                activate ();
 
894
        }
 
895
 
 
896
        _current_block_size = nframes;
 
897
 
 
898
        return 0;
 
899
}
 
900
 
 
901
bool
 
902
AUPlugin::configure_io (ChanCount in, ChanCount out)
 
903
{
 
904
        AudioStreamBasicDescription streamFormat;
 
905
        bool was_initialized = initialized;
 
906
        int32_t audio_in = in.n_audio();
 
907
        int32_t audio_out = out.n_audio();
 
908
 
 
909
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
 
910
 
 
911
        if (initialized) {
 
912
                //if we are already running with the requested i/o config, bail out here
 
913
                if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
 
914
                        return 0;
 
915
                } else {
 
916
                        deactivate ();
 
917
                }
 
918
        }
 
919
 
 
920
        streamFormat.mSampleRate = _session.frame_rate();
 
921
        streamFormat.mFormatID = kAudioFormatLinearPCM;
 
922
        streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
 
923
 
 
924
#ifdef __LITTLE_ENDIAN__
 
925
        /* relax */
 
926
#else
 
927
        streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
 
928
#endif
 
929
 
 
930
        streamFormat.mBitsPerChannel = 32;
 
931
        streamFormat.mFramesPerPacket = 1;
 
932
 
 
933
        /* apple says that for non-interleaved data, these
 
934
           values always refer to a single channel.
 
935
        */
 
936
        streamFormat.mBytesPerPacket = 4;
 
937
        streamFormat.mBytesPerFrame = 4;
 
938
 
 
939
        streamFormat.mChannelsPerFrame = audio_in;
 
940
 
 
941
        if (set_input_format (streamFormat) != 0) {
 
942
                return -1;
 
943
        }
 
944
 
 
945
        streamFormat.mChannelsPerFrame = audio_out;
 
946
 
 
947
        if (set_output_format (streamFormat) != 0) {
 
948
                return -1;
 
949
        }
 
950
 
 
951
        /* reset plugin info to show currently configured state */
 
952
        
 
953
        _info->n_inputs = in;
 
954
        _info->n_outputs = out;
 
955
 
 
956
        if (was_initialized) {
 
957
                activate ();
 
958
        }
 
959
 
 
960
        return 0;
 
961
}
 
962
 
 
963
ChanCount
 
964
AUPlugin::input_streams() const
 
965
{
 
966
        ChanCount c;
 
967
 
 
968
        c.set (DataType::AUDIO, 1);
 
969
        c.set (DataType::MIDI, 0);
 
970
 
 
971
        if (input_channels < 0) {
 
972
                warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
 
973
        } else {
 
974
                c.set (DataType::AUDIO, input_channels);
 
975
                c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
 
976
        }
 
977
 
 
978
        return c;
 
979
}
 
980
 
 
981
 
 
982
ChanCount
 
983
AUPlugin::output_streams() const
 
984
{
 
985
        ChanCount c;
 
986
 
 
987
        c.set (DataType::AUDIO, 1);
 
988
        c.set (DataType::MIDI, 0);
 
989
 
 
990
        if (output_channels < 0) {
 
991
                warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
 
992
        } else {
 
993
                c.set (DataType::AUDIO, output_channels);
 
994
                c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
 
995
        }
 
996
 
 
997
        return c;
 
998
}
 
999
 
 
1000
bool
 
1001
AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
 
1002
{
 
1003
        // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
 
1004
 
 
1005
        int32_t audio_in = in.n_audio();
 
1006
        int32_t audio_out;
 
1007
        bool found = false;
 
1008
        AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
 
1009
 
 
1010
        /* lets check MIDI first */
 
1011
 
 
1012
        if (in.n_midi() > 0) {
 
1013
                if (!_has_midi_input) {
 
1014
                        return false;
 
1015
                }
 
1016
        }
 
1017
 
 
1018
        vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
 
1019
 
 
1020
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n", 
 
1021
                                                        name(), io_configs.size(), in, out));
 
1022
 
 
1023
        //Ardour expects the plugin to tell it the output
 
1024
        //configuration but AU plugins can have multiple I/O
 
1025
        //configurations in most cases. so first lets see
 
1026
        //if there's a configuration that keeps out==in
 
1027
 
 
1028
        audio_out = audio_in;
 
1029
 
 
1030
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
1031
 
 
1032
                int32_t possible_in = i->first;
 
1033
                int32_t possible_out = i->second;
 
1034
 
 
1035
                if ((possible_in == audio_in) && (possible_out == audio_out)) {
 
1036
                        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n", 
 
1037
                                                                        possible_in, possible_out,
 
1038
                                                                        in, out));
 
1039
 
 
1040
                        out.set (DataType::MIDI, 0);
 
1041
                        out.set (DataType::AUDIO, audio_out);
 
1042
 
 
1043
                        return 1;
 
1044
                }
 
1045
        }
 
1046
 
 
1047
        /* now allow potentially "imprecise" matches */
 
1048
 
 
1049
        audio_out = -1;
 
1050
 
 
1051
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
1052
 
 
1053
                int32_t possible_in = i->first;
 
1054
                int32_t possible_out = i->second;
 
1055
 
 
1056
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
 
1057
 
 
1058
                if (possible_out == 0) {
 
1059
                        warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
 
1060
                        /* XXX surely this is just a send? (e.g. AUNetSend) */
 
1061
                        continue;
 
1062
                }
 
1063
 
 
1064
                if (possible_in == 0) {
 
1065
 
 
1066
                        /* instrument plugin, always legal but throws away inputs ...
 
1067
                        */
 
1068
 
 
1069
                        if (possible_out == -1) {
 
1070
                                /* any configuration possible, provide stereo output */
 
1071
                                audio_out = 2;
 
1072
                                found = true;
 
1073
                        } else if (possible_out == -2) {
 
1074
                                /* plugins shouldn't really use (0,-2) but might. 
 
1075
                                   any configuration possible, provide stereo output 
 
1076
                                */
 
1077
                                audio_out = 2;
 
1078
                                found = true;
 
1079
                        } else if (possible_out < -2) {
 
1080
                                /* explicitly variable number of outputs. 
 
1081
 
 
1082
                                   Since Ardour can handle any configuration,
 
1083
                                   we have to somehow pick a number. 
 
1084
 
 
1085
                                   We'll use the number of inputs
 
1086
                                   to the master bus, or 2 if there
 
1087
                                   is no master bus.
 
1088
                                */
 
1089
                                boost::shared_ptr<Route> master = _session.master_out();
 
1090
                                if (master) {
 
1091
                                        audio_out = master->input()->n_ports().n_audio();
 
1092
                                } else {
 
1093
                                        audio_out = 2;
 
1094
                                }
 
1095
                                found = true;
 
1096
                        } else {
 
1097
                                /* exact number of outputs */
 
1098
                                audio_out = possible_out;
 
1099
                                found = true;
 
1100
                        }
 
1101
                }
 
1102
 
 
1103
                if (possible_in == -1) {
 
1104
 
 
1105
                        /* wildcard for input */
 
1106
 
 
1107
                        if (possible_out == -1) {
 
1108
                                /* out much match in */
 
1109
                                audio_out = audio_in;
 
1110
                                found = true;
 
1111
                        } else if (possible_out == -2) {
 
1112
                                /* any configuration possible, pick matching */
 
1113
                                audio_out = audio_in;
 
1114
                                found = true;
 
1115
                        } else if (possible_out < -2) {
 
1116
                                /* explicitly variable number of outputs, pick maximum */
 
1117
                                audio_out = -possible_out;
 
1118
                                found = true;
 
1119
                        } else {
 
1120
                                /* exact number of outputs */
 
1121
                                audio_out = possible_out;
 
1122
                                found = true;
 
1123
                        }
 
1124
                }
 
1125
 
 
1126
                if (possible_in == -2) {
 
1127
 
 
1128
                        if (possible_out == -1) {
 
1129
                                /* any configuration possible, pick matching */
 
1130
                                audio_out = audio_in;
 
1131
                                found = true;
 
1132
                        } else if (possible_out == -2) {
 
1133
                                /* plugins shouldn't really use (-2,-2) but might. 
 
1134
                                   interpret as (-1,-1).
 
1135
                                */
 
1136
                                audio_out = audio_in;
 
1137
                                found = true;
 
1138
                        } else if (possible_out < -2) {
 
1139
                                /* explicitly variable number of outputs, pick maximum */
 
1140
                                audio_out = -possible_out;
 
1141
                                found = true;
 
1142
                        } else {
 
1143
                                /* exact number of outputs */
 
1144
                                audio_out = possible_out;
 
1145
                                found = true;
 
1146
                        }
 
1147
                }
 
1148
 
 
1149
                if (possible_in < -2) {
 
1150
 
 
1151
                        /* explicit variable number of inputs */
 
1152
 
 
1153
                        if (audio_in > -possible_in) {
 
1154
                                /* request is too large */
 
1155
                        }
 
1156
 
 
1157
 
 
1158
                        if (possible_out == -1) {
 
1159
                                /* any output configuration possible, provide stereo out */
 
1160
                                audio_out = 2;
 
1161
                                found = true;
 
1162
                        } else if (possible_out == -2) {
 
1163
                                /* plugins shouldn't really use (<-2,-2) but might. 
 
1164
                                   interpret as (<-2,-1): any configuration possible, provide stereo output 
 
1165
                                */
 
1166
                                audio_out = 2;
 
1167
                                found = true;
 
1168
                        } else if (possible_out < -2) {
 
1169
                                /* explicitly variable number of outputs. 
 
1170
 
 
1171
                                   Since Ardour can handle any configuration,
 
1172
                                   we have to somehow pick a number. 
 
1173
 
 
1174
                                   We'll use the number of inputs
 
1175
                                   to the master bus, or 2 if there
 
1176
                                   is no master bus.
 
1177
                                */
 
1178
                                boost::shared_ptr<Route> master = _session.master_out();
 
1179
                                if (master) {
 
1180
                                        audio_out = master->input()->n_ports().n_audio();
 
1181
                                } else {
 
1182
                                        audio_out = 2;
 
1183
                                }
 
1184
                                found = true;
 
1185
                        } else {
 
1186
                                /* exact number of outputs */
 
1187
                                audio_out = possible_out;
 
1188
                                found = true;
 
1189
                        }
 
1190
                }
 
1191
 
 
1192
                if (possible_in && (possible_in == audio_in)) {
 
1193
 
 
1194
                        /* exact number of inputs ... must match obviously */
 
1195
 
 
1196
                        if (possible_out == -1) {
 
1197
                                /* any output configuration possible, provide stereo output */
 
1198
                                audio_out = 2;
 
1199
                                found = true;
 
1200
                        } else if (possible_out == -2) {
 
1201
                                /* plugins shouldn't really use (>0,-2) but might. 
 
1202
                                   interpret as (>0,-1): 
 
1203
                                   any output configuration possible, provide stereo output
 
1204
                                */
 
1205
                                audio_out = 2;
 
1206
                                found = true;
 
1207
                        } else if (possible_out < -2) {
 
1208
                                /* explicitly variable number of outputs, pick maximum */
 
1209
                                audio_out = -possible_out;
 
1210
                                found = true;
 
1211
                        } else {
 
1212
                                /* exact number of outputs */
 
1213
                                audio_out = possible_out;
 
1214
                                found = true;
 
1215
                        }
 
1216
                }
 
1217
 
 
1218
                if (found) {
 
1219
                        break;
 
1220
                }
 
1221
 
 
1222
        }
 
1223
 
 
1224
        if (found) {
 
1225
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
 
1226
        } else {
 
1227
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
 
1228
                return false;
 
1229
        }
 
1230
 
 
1231
        out.set (DataType::MIDI, 0);
 
1232
        out.set (DataType::AUDIO, audio_out);
 
1233
 
 
1234
        return true;
 
1235
}
 
1236
 
 
1237
int
 
1238
AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
 
1239
{
 
1240
        return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
 
1241
}
 
1242
 
 
1243
int
 
1244
AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
 
1245
{
 
1246
        if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
 
1247
                return -1;
 
1248
        }
 
1249
 
 
1250
        if (buffers) {
 
1251
                free (buffers);
 
1252
                buffers = 0;
 
1253
        }
 
1254
 
 
1255
        buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
 
1256
                                              fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
 
1257
 
 
1258
        return 0;
 
1259
}
 
1260
 
 
1261
int
 
1262
AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
 
1263
{
 
1264
        OSErr result;
 
1265
 
 
1266
        for (uint32_t i = 0; i < cnt; ++i) {
 
1267
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
 
1268
                                                                (scope == kAudioUnitScope_Input ? "input" : "output"),
 
1269
                                                                scope, cnt));
 
1270
                if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
 
1271
                        error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
 
1272
                                                 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
 
1273
                        return -1;
 
1274
                }
 
1275
        }
 
1276
 
 
1277
        if (scope == kAudioUnitScope_Input) {
 
1278
                input_channels = fmt.mChannelsPerFrame;
 
1279
        } else {
 
1280
                output_channels = fmt.mChannelsPerFrame;
 
1281
        }
 
1282
 
 
1283
        return 0;
 
1284
}
 
1285
 
 
1286
OSStatus
 
1287
AUPlugin::render_callback(AudioUnitRenderActionFlags*,
 
1288
                          const AudioTimeStamp*,
 
1289
                          UInt32,
 
1290
                          UInt32       inNumberFrames,
 
1291
                          AudioBufferList*       ioData)
 
1292
{
 
1293
        /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
 
1294
 
 
1295
        // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
 
1296
        // name(), inNumberFrames, ioData->mNumberBuffers));
 
1297
 
 
1298
        if (input_maxbuf == 0) {
 
1299
                error << _("AUPlugin: render callback called illegally!") << endmsg;
 
1300
                return kAudioUnitErr_CannotDoInCurrentContext;
 
1301
        }
 
1302
        uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
 
1303
 
 
1304
        for (uint32_t i = 0; i < limit; ++i) {
 
1305
                ioData->mBuffers[i].mNumberChannels = 1;
 
1306
                ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
 
1307
 
 
1308
                /* we don't use the channel mapping because audiounits are
 
1309
                   never replicated. one plugin instance uses all channels/buffers
 
1310
                   passed to PluginInsert::connect_and_run()
 
1311
                */
 
1312
 
 
1313
                ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
 
1314
        }
 
1315
 
 
1316
        cb_offset += inNumberFrames;
 
1317
 
 
1318
        return noErr;
 
1319
}
 
1320
 
 
1321
int
 
1322
AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
 
1323
{
 
1324
        Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
 
1325
 
 
1326
        AudioUnitRenderActionFlags flags = 0;
 
1327
        AudioTimeStamp ts;
 
1328
        OSErr err;
 
1329
 
 
1330
        if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
 
1331
                unit->GlobalReset();
 
1332
                _last_nframes = nframes;
 
1333
        }
 
1334
 
 
1335
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
 
1336
                                                        name(), input_channels, output_channels, _has_midi_input,
 
1337
                                                        bufs.count(), bufs.available()));
 
1338
 
 
1339
        /* the apparent number of buffers matches our input configuration, but we know that the bufferset
 
1340
           has the capacity to handle our outputs.
 
1341
        */
 
1342
 
 
1343
        assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
 
1344
 
 
1345
        input_buffers = &bufs;
 
1346
        input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
 
1347
        input_offset = offset;
 
1348
        cb_offset = 0;
 
1349
 
 
1350
        buffers->mNumberBuffers = output_channels;
 
1351
 
 
1352
        for (int32_t i = 0; i < output_channels; ++i) {
 
1353
                buffers->mBuffers[i].mNumberChannels = 1;
 
1354
                buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
 
1355
                /* setting this to 0 indicates to the AU that it can provide buffers here
 
1356
                   if necessary. if it can process in-place, it will use the buffers provided
 
1357
                   as input by ::render_callback() above. 
 
1358
                   
 
1359
                   a non-null values tells the plugin to render into the buffer pointed
 
1360
                   at by the value.
 
1361
                */
 
1362
                buffers->mBuffers[i].mData = 0;
 
1363
        }
 
1364
 
 
1365
        if (_has_midi_input) {
 
1366
 
 
1367
                uint32_t nmidi = bufs.count().n_midi();
 
1368
 
 
1369
                for (uint32_t i = 0; i < nmidi; ++i) {
 
1370
                        
 
1371
                        /* one MIDI port/buffer only */
 
1372
                        
 
1373
                        MidiBuffer& m = bufs.get_midi (i);
 
1374
                        
 
1375
                        for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
 
1376
                                Evoral::MIDIEvent<framepos_t> ev (*i);
 
1377
                                
 
1378
                                if (ev.is_channel_event()) {
 
1379
                                        const uint8_t* b = ev.buffer();
 
1380
                                        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
 
1381
                                        unit->MIDIEvent (b[0], b[1], b[2], ev.time());
 
1382
                                }
 
1383
 
 
1384
                                /* XXX need to handle sysex and other message types */
 
1385
                        }
 
1386
                }
 
1387
        }
 
1388
 
 
1389
        /* does this really mean anything ? 
 
1390
         */
 
1391
 
 
1392
        ts.mSampleTime = frames_processed;
 
1393
        ts.mFlags = kAudioTimeStampSampleTimeValid;
 
1394
 
 
1395
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
 
1396
                                                        name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
 
1397
 
 
1398
        if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
 
1399
 
 
1400
                input_maxbuf = 0;
 
1401
                frames_processed += nframes;
 
1402
 
 
1403
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
 
1404
                                                                name(), buffers->mNumberBuffers, output_channels));
 
1405
 
 
1406
                int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
 
1407
                int32_t i;
 
1408
 
 
1409
                for (i = 0; i < limit; ++i) {
 
1410
                        Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
 
1411
                        if (expected_buffer_address != buffers->mBuffers[i].mData) {
 
1412
                                /* plugin provided its own buffer for output so copy it back to where we want it
 
1413
                                 */
 
1414
                                memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
 
1415
                        }
 
1416
                }
 
1417
 
 
1418
                /* now silence any buffers that were passed in but the that the plugin
 
1419
                   did not fill/touch/use.
 
1420
                */
 
1421
 
 
1422
                for (;i < output_channels; ++i) {
 
1423
                        memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
 
1424
                }
 
1425
 
 
1426
                return 0;
 
1427
        }
 
1428
 
 
1429
        error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
 
1430
        return -1;
 
1431
}
 
1432
 
 
1433
OSStatus
 
1434
AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
 
1435
                                       Float64* outCurrentTempo)
 
1436
{
 
1437
        TempoMap& tmap (_session.tempo_map());
 
1438
 
 
1439
        DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
 
1440
 
 
1441
        /* more than 1 meter or more than 1 tempo means that a simplistic computation
 
1442
           (and interpretation) of a beat position will be incorrect. So refuse to
 
1443
           offer the value.
 
1444
        */
 
1445
 
 
1446
        if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
 
1447
                return kAudioUnitErr_CannotDoInCurrentContext;
 
1448
        }
 
1449
 
 
1450
        Timecode::BBT_Time bbt;
 
1451
        TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
 
1452
        tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
 
1453
 
 
1454
        if (outCurrentBeat) {
 
1455
                float beat;
 
1456
                beat = metric.meter().divisions_per_bar() * bbt.bars;
 
1457
                beat += bbt.beats;
 
1458
                beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
 
1459
                *outCurrentBeat = beat;
 
1460
        }
 
1461
 
 
1462
        if (outCurrentTempo) {
 
1463
                *outCurrentTempo = floor (metric.tempo().beats_per_minute());
 
1464
        }
 
1465
 
 
1466
        return noErr;
 
1467
 
 
1468
}
 
1469
 
 
1470
OSStatus
 
1471
AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
 
1472
                                              Float32*  outTimeSig_Numerator,
 
1473
                                              UInt32*   outTimeSig_Denominator,
 
1474
                                              Float64*  outCurrentMeasureDownBeat)
 
1475
{
 
1476
        TempoMap& tmap (_session.tempo_map());
 
1477
 
 
1478
        DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
 
1479
 
 
1480
        /* more than 1 meter or more than 1 tempo means that a simplistic computation
 
1481
           (and interpretation) of a beat position will be incorrect. So refuse to
 
1482
           offer the value.
 
1483
        */
 
1484
 
 
1485
        if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
 
1486
                return kAudioUnitErr_CannotDoInCurrentContext;
 
1487
        }
 
1488
 
 
1489
        Timecode::BBT_Time bbt;
 
1490
        TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
 
1491
        tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
 
1492
 
 
1493
        if (outDeltaSampleOffsetToNextBeat) {
 
1494
                if (bbt.ticks == 0) {
 
1495
                        /* on the beat */
 
1496
                        *outDeltaSampleOffsetToNextBeat = 0;
 
1497
                } else {
 
1498
                        *outDeltaSampleOffsetToNextBeat = (UInt32) 
 
1499
                                floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
 
1500
                                       metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
 
1501
                }
 
1502
        }
 
1503
 
 
1504
        if (outTimeSig_Numerator) {
 
1505
                *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
 
1506
        }
 
1507
        if (outTimeSig_Denominator) {
 
1508
                *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
 
1509
        }
 
1510
 
 
1511
        if (outCurrentMeasureDownBeat) {
 
1512
 
 
1513
                /* beat for the start of the bar.
 
1514
                   1|1|0 -> 1
 
1515
                   2|1|0 -> 1 + divisions_per_bar
 
1516
                   3|1|0 -> 1 + (2 * divisions_per_bar)
 
1517
                   etc.
 
1518
                */
 
1519
 
 
1520
                *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
 
1521
        }
 
1522
 
 
1523
        return noErr;
 
1524
}
 
1525
 
 
1526
OSStatus
 
1527
AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
 
1528
                                        Boolean*  outTransportStateChanged,
 
1529
                                        Float64*  outCurrentSampleInTimeLine,
 
1530
                                        Boolean*  outIsCycling,
 
1531
                                        Float64*  outCycleStartBeat,
 
1532
                                        Float64*  outCycleEndBeat)
 
1533
{
 
1534
        bool rolling;
 
1535
        float speed;
 
1536
 
 
1537
        DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
 
1538
 
 
1539
        rolling = _session.transport_rolling();
 
1540
        speed = _session.transport_speed ();
 
1541
 
 
1542
        if (outIsPlaying) {
 
1543
                *outIsPlaying = _session.transport_rolling();
 
1544
        }
 
1545
 
 
1546
        if (outTransportStateChanged) {
 
1547
                if (rolling != last_transport_rolling) {
 
1548
                        *outTransportStateChanged = true;
 
1549
                } else if (speed != last_transport_speed) {
 
1550
                        *outTransportStateChanged = true;
 
1551
                } else {
 
1552
                        *outTransportStateChanged = false;
 
1553
                }
 
1554
        }
 
1555
 
 
1556
        if (outCurrentSampleInTimeLine) {
 
1557
                /* this assumes that the AU can only call this host callback from render context,
 
1558
                   where input_offset is valid.
 
1559
                */
 
1560
                *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
 
1561
        }
 
1562
 
 
1563
        if (outIsCycling) {
 
1564
                Location* loc = _session.locations()->auto_loop_location();
 
1565
 
 
1566
                *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
 
1567
 
 
1568
                if (*outIsCycling) {
 
1569
 
 
1570
                        if (outCycleStartBeat || outCycleEndBeat) {
 
1571
 
 
1572
                                TempoMap& tmap (_session.tempo_map());
 
1573
 
 
1574
                                /* more than 1 meter means that a simplistic computation (and interpretation) of
 
1575
                                   a beat position will be incorrect. so refuse to offer the value.
 
1576
                                */
 
1577
 
 
1578
                                if (tmap.n_meters() > 1) {
 
1579
                                        return kAudioUnitErr_CannotDoInCurrentContext;
 
1580
                                }
 
1581
 
 
1582
                                Timecode::BBT_Time bbt;
 
1583
 
 
1584
                                if (outCycleStartBeat) {
 
1585
                                        TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
 
1586
                                        _session.tempo_map().bbt_time (loc->start(), bbt);
 
1587
 
 
1588
                                        float beat;
 
1589
                                        beat = metric.meter().divisions_per_bar() * bbt.bars;
 
1590
                                        beat += bbt.beats;
 
1591
                                        beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
 
1592
 
 
1593
                                        *outCycleStartBeat = beat;
 
1594
                                }
 
1595
 
 
1596
                                if (outCycleEndBeat) {
 
1597
                                        TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
 
1598
                                        _session.tempo_map().bbt_time (loc->end(), bbt);
 
1599
 
 
1600
                                        float beat;
 
1601
                                        beat = metric.meter().divisions_per_bar() * bbt.bars;
 
1602
                                        beat += bbt.beats;
 
1603
                                        beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
 
1604
 
 
1605
                                        *outCycleEndBeat = beat;
 
1606
                                }
 
1607
                        }
 
1608
                }
 
1609
        }
 
1610
 
 
1611
        last_transport_rolling = rolling;
 
1612
        last_transport_speed = speed;
 
1613
 
 
1614
        return noErr;
 
1615
}
 
1616
 
 
1617
set<Evoral::Parameter>
 
1618
AUPlugin::automatable() const
 
1619
{
 
1620
        set<Evoral::Parameter> automates;
 
1621
 
 
1622
        for (uint32_t i = 0; i < descriptors.size(); ++i) {
 
1623
                if (descriptors[i].automatable) {
 
1624
                        automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
 
1625
                }
 
1626
        }
 
1627
 
 
1628
        return automates;
 
1629
}
 
1630
 
 
1631
string
 
1632
AUPlugin::describe_parameter (Evoral::Parameter param)
 
1633
{
 
1634
        if (param.type() == PluginAutomation && param.id() < parameter_count()) {
 
1635
                return descriptors[param.id()].label;
 
1636
        } else {
 
1637
                return "??";
 
1638
        }
 
1639
}
 
1640
 
 
1641
void
 
1642
AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
 
1643
{
 
1644
        // NameValue stuff here
 
1645
}
 
1646
 
 
1647
bool
 
1648
AUPlugin::parameter_is_audio (uint32_t) const
 
1649
{
 
1650
        return false;
 
1651
}
 
1652
 
 
1653
bool
 
1654
AUPlugin::parameter_is_control (uint32_t) const
 
1655
{
 
1656
        return true;
 
1657
}
 
1658
 
 
1659
bool
 
1660
AUPlugin::parameter_is_input (uint32_t) const
 
1661
{
 
1662
        return false;
 
1663
}
 
1664
 
 
1665
bool
 
1666
AUPlugin::parameter_is_output (uint32_t) const
 
1667
{
 
1668
        return false;
 
1669
}
 
1670
 
 
1671
void
 
1672
AUPlugin::add_state (XMLNode* root) const
 
1673
{
 
1674
        LocaleGuard lg (X_("POSIX"));
 
1675
        CFDataRef xmlData;
 
1676
        CFPropertyListRef propertyList;
 
1677
 
 
1678
        DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
 
1679
        if (unit->GetAUPreset (propertyList) != noErr) {
 
1680
                return;
 
1681
        }
 
1682
 
 
1683
        // Convert the property list into XML data.
 
1684
 
 
1685
        xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
 
1686
 
 
1687
        if (!xmlData) {
 
1688
                error << _("Could not create XML version of property list") << endmsg;
 
1689
                return;
 
1690
        }
 
1691
 
 
1692
        /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
 
1693
           our state node. GACK!
 
1694
        */
 
1695
 
 
1696
        XMLTree t;
 
1697
 
 
1698
        if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
 
1699
                if (t.root()) {
 
1700
                        root->add_child_copy (*t.root());
 
1701
                }
 
1702
        }
 
1703
 
 
1704
        CFRelease (xmlData);
 
1705
        CFRelease (propertyList);
 
1706
}
 
1707
 
 
1708
int
 
1709
AUPlugin::set_state(const XMLNode& node, int version)
 
1710
{
 
1711
        int ret = -1;
 
1712
        CFPropertyListRef propertyList;
 
1713
        LocaleGuard lg (X_("POSIX"));
 
1714
 
 
1715
        if (node.name() != state_node_name()) {
 
1716
                error << _("Bad node sent to AUPlugin::set_state") << endmsg;
 
1717
                return -1;
 
1718
        }
 
1719
 
 
1720
#ifndef NO_PLUGIN_STATE
 
1721
        if (node.children().empty()) {
 
1722
                return -1;
 
1723
        }
 
1724
 
 
1725
        XMLNode* top = node.children().front();
 
1726
        XMLNode* copy = new XMLNode (*top);
 
1727
 
 
1728
        XMLTree t;
 
1729
        t.set_root (copy);
 
1730
 
 
1731
        const string& xml = t.write_buffer ();
 
1732
        CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
 
1733
        CFStringRef errorString;
 
1734
 
 
1735
        propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
 
1736
                                                        xmlData,
 
1737
                                                        kCFPropertyListImmutable,
 
1738
                                                        &errorString);
 
1739
 
 
1740
        CFRelease (xmlData);
 
1741
 
 
1742
        if (propertyList) {
 
1743
                DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
 
1744
                if (unit->SetAUPreset (propertyList) == noErr) {
 
1745
                        ret = 0;
 
1746
 
 
1747
                        /* tell the world */
 
1748
 
 
1749
                        AudioUnitParameter changedUnit;
 
1750
                        changedUnit.mAudioUnit = unit->AU();
 
1751
                        changedUnit.mParameterID = kAUParameterListener_AnyParameter;
 
1752
                        AUParameterListenerNotify (NULL, NULL, &changedUnit);
 
1753
                }
 
1754
                CFRelease (propertyList);
 
1755
        }
 
1756
#endif
 
1757
 
 
1758
        Plugin::set_state (node, version);
 
1759
        return ret;
 
1760
}
 
1761
 
 
1762
bool
 
1763
AUPlugin::load_preset (PresetRecord r)
 
1764
{
 
1765
        Plugin::load_preset (r);
 
1766
 
 
1767
        bool ret = false;
 
1768
        CFPropertyListRef propertyList;
 
1769
        Glib::ustring path;
 
1770
        UserPresetMap::iterator ux;
 
1771
        FactoryPresetMap::iterator fx;
 
1772
 
 
1773
        /* look first in "user" presets */
 
1774
 
 
1775
        if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
 
1776
 
 
1777
                if ((propertyList = load_property_list (ux->second)) != 0) {
 
1778
                        DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
 
1779
                        if (unit->SetAUPreset (propertyList) == noErr) {
 
1780
                                ret = true;
 
1781
 
 
1782
                                /* tell the world */
 
1783
 
 
1784
                                AudioUnitParameter changedUnit;
 
1785
                                changedUnit.mAudioUnit = unit->AU();
 
1786
                                changedUnit.mParameterID = kAUParameterListener_AnyParameter;
 
1787
                                AUParameterListenerNotify (NULL, NULL, &changedUnit);
 
1788
                        }
 
1789
                        CFRelease(propertyList);
 
1790
                }
 
1791
 
 
1792
        } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
 
1793
 
 
1794
                AUPreset preset;
 
1795
 
 
1796
                preset.presetNumber = fx->second;
 
1797
                preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
 
1798
 
 
1799
                DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
 
1800
 
 
1801
                if (unit->SetPresentPreset (preset) == 0) {
 
1802
                        ret = true;
 
1803
 
 
1804
                        /* tell the world */
 
1805
 
 
1806
                        AudioUnitParameter changedUnit;
 
1807
                        changedUnit.mAudioUnit = unit->AU();
 
1808
                        changedUnit.mParameterID = kAUParameterListener_AnyParameter;
 
1809
                        AUParameterListenerNotify (NULL, NULL, &changedUnit);
 
1810
                }
 
1811
        }
 
1812
 
 
1813
        return ret;
 
1814
}
 
1815
 
 
1816
void
 
1817
AUPlugin::do_remove_preset (std::string) 
 
1818
{
 
1819
}
 
1820
 
 
1821
string
 
1822
AUPlugin::do_save_preset (string preset_name)
 
1823
{
 
1824
        CFPropertyListRef propertyList;
 
1825
        vector<Glib::ustring> v;
 
1826
        Glib::ustring user_preset_path;
 
1827
 
 
1828
        std::string m = maker();
 
1829
        std::string n = name();
 
1830
 
 
1831
        strip_whitespace_edges (m);
 
1832
        strip_whitespace_edges (n);
 
1833
 
 
1834
        v.push_back (Glib::get_home_dir());
 
1835
        v.push_back ("Library");
 
1836
        v.push_back ("Audio");
 
1837
        v.push_back ("Presets");
 
1838
        v.push_back (m);
 
1839
        v.push_back (n);
 
1840
 
 
1841
        user_preset_path = Glib::build_filename (v);
 
1842
 
 
1843
        if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
 
1844
                error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
 
1845
                return string();
 
1846
        }
 
1847
 
 
1848
        DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
 
1849
        if (unit->GetAUPreset (propertyList) != noErr) {
 
1850
                return string();
 
1851
        }
 
1852
 
 
1853
        // add the actual preset name */
 
1854
 
 
1855
        v.push_back (preset_name + preset_suffix);
 
1856
 
 
1857
        // rebuild
 
1858
 
 
1859
        user_preset_path = Glib::build_filename (v);
 
1860
 
 
1861
        set_preset_name_in_plist (propertyList, preset_name);
 
1862
 
 
1863
        if (save_property_list (propertyList, user_preset_path)) {
 
1864
                error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
 
1865
                return string();
 
1866
        }
 
1867
 
 
1868
        CFRelease(propertyList);
 
1869
 
 
1870
        return string ("file:///") + user_preset_path;
 
1871
}
 
1872
 
 
1873
//-----------------------------------------------------------------------------
 
1874
// this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
 
1875
static SInt32
 
1876
GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
 
1877
{
 
1878
        CFNumberRef cfNumber;
 
1879
        SInt32 numberValue = 0;
 
1880
        Boolean dummySuccess;
 
1881
 
 
1882
        if (outSuccess == NULL)
 
1883
                outSuccess = &dummySuccess;
 
1884
        if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
 
1885
        {
 
1886
                *outSuccess = FALSE;
 
1887
                return 0;
 
1888
        }
 
1889
 
 
1890
        cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
 
1891
        if (cfNumber == NULL)
 
1892
        {
 
1893
                *outSuccess = FALSE;
 
1894
                return 0;
 
1895
        }
 
1896
        *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
 
1897
        if (*outSuccess)
 
1898
                return numberValue;
 
1899
        else
 
1900
                return 0;
 
1901
}
 
1902
 
 
1903
static OSStatus
 
1904
GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
 
1905
{
 
1906
        CFDictionaryRef auStateDictionary;
 
1907
        ComponentDescription tempDesc = {0,0,0,0,0};
 
1908
        SInt32 versionValue;
 
1909
        Boolean gotValue;
 
1910
 
 
1911
        if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
 
1912
                return paramErr;
 
1913
 
 
1914
        // the property list for AU state data must be of the dictionary type
 
1915
        if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
 
1916
                return kAudioUnitErr_InvalidPropertyValue;
 
1917
        }
 
1918
 
 
1919
        auStateDictionary = (CFDictionaryRef)inAUStateData;
 
1920
 
 
1921
        // first check to make sure that the version of the AU state data is one that we know understand
 
1922
        // XXX should I really do this?  later versions would probably still hold these ID keys, right?
 
1923
        versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
 
1924
 
 
1925
        if (!gotValue) {
 
1926
                return kAudioUnitErr_InvalidPropertyValue;
 
1927
        }
 
1928
#define kCurrentSavedStateVersion 0
 
1929
        if (versionValue != kCurrentSavedStateVersion) {
 
1930
                return kAudioUnitErr_InvalidPropertyValue;
 
1931
        }
 
1932
 
 
1933
        // grab the ComponentDescription values from the AU state data
 
1934
        tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
 
1935
        tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
 
1936
        tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
 
1937
        // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
 
1938
        if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
 
1939
                return kAudioUnitErr_InvalidPropertyValue;
 
1940
 
 
1941
        *outComponentDescription = tempDesc;
 
1942
        return noErr;
 
1943
}
 
1944
 
 
1945
 
 
1946
static bool au_preset_filter (const string& str, void* arg)
 
1947
{
 
1948
        /* Not a dotfile, has a prefix before a period, suffix is aupreset */
 
1949
 
 
1950
        bool ret;
 
1951
 
 
1952
        ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
 
1953
 
 
1954
        if (ret && arg) {
 
1955
 
 
1956
                /* check the preset file path name against this plugin
 
1957
                   ID. The idea is that all preset files for this plugin
 
1958
                   include "<manufacturer>/<plugin-name>" in their path.
 
1959
                */
 
1960
 
 
1961
                Plugin* p = (Plugin *) arg;
 
1962
                string match = p->maker();
 
1963
                match += '/';
 
1964
                match += p->name();
 
1965
 
 
1966
                ret = str.find (match) != string::npos;
 
1967
 
 
1968
                if (ret == false) {
 
1969
                        string m = p->maker ();
 
1970
                        string n = p->name ();
 
1971
                        strip_whitespace_edges (m);
 
1972
                        strip_whitespace_edges (n);
 
1973
                        match = m;
 
1974
                        match += '/';
 
1975
                        match += n;
 
1976
 
 
1977
                        ret = str.find (match) != string::npos;
 
1978
                }
 
1979
        }
 
1980
 
 
1981
        return ret;
 
1982
}
 
1983
 
 
1984
bool
 
1985
check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
 
1986
{
 
1987
        OSStatus status;
 
1988
        CFPropertyListRef plist;
 
1989
        ComponentDescription presetDesc;
 
1990
        bool ret = false;
 
1991
 
 
1992
        plist = load_property_list (pathstr);
 
1993
 
 
1994
        if (!plist) {
 
1995
                return ret;
 
1996
        }
 
1997
 
 
1998
        // get the ComponentDescription from the AU preset file
 
1999
 
 
2000
        status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
 
2001
 
 
2002
        if (status == noErr) {
 
2003
                if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
 
2004
 
 
2005
                        /* try to get the preset name from the property list */
 
2006
 
 
2007
                        if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
 
2008
 
 
2009
                                const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
 
2010
 
 
2011
                                if (psk) {
 
2012
 
 
2013
                                        const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
 
2014
 
 
2015
                                        if (!p) {
 
2016
                                                char buf[PATH_MAX+1];
 
2017
 
 
2018
                                                if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
 
2019
                                                        preset_name = buf;
 
2020
                                                }
 
2021
                                        }
 
2022
                                }
 
2023
                        }
 
2024
                }
 
2025
        }
 
2026
 
 
2027
        CFRelease (plist);
 
2028
 
 
2029
        return true;
 
2030
}
 
2031
 
 
2032
std::string
 
2033
AUPlugin::current_preset() const
 
2034
{
 
2035
        string preset_name;
 
2036
 
 
2037
        CFPropertyListRef propertyList;
 
2038
 
 
2039
        DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
 
2040
        if (unit->GetAUPreset (propertyList) == noErr) {
 
2041
                preset_name = get_preset_name_in_plist (propertyList);
 
2042
                CFRelease(propertyList);
 
2043
        }
 
2044
 
 
2045
        return preset_name;
 
2046
}
 
2047
 
 
2048
void
 
2049
AUPlugin::find_presets ()
 
2050
{
 
2051
        vector<string*>* preset_files;
 
2052
        PathScanner scanner;
 
2053
 
 
2054
        user_preset_map.clear ();
 
2055
 
 
2056
        preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
 
2057
 
 
2058
        if (!preset_files) {
 
2059
                return;
 
2060
        }
 
2061
 
 
2062
        for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
 
2063
 
 
2064
                string path = *(*x);
 
2065
                string preset_name;
 
2066
 
 
2067
                /* make an initial guess at the preset name using the path */
 
2068
 
 
2069
                preset_name = Glib::path_get_basename (path);
 
2070
                preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
 
2071
 
 
2072
                /* check that this preset file really matches this plugin
 
2073
                   and potentially get the "real" preset name from
 
2074
                   within the file.
 
2075
                */
 
2076
 
 
2077
                if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
 
2078
                        user_preset_map[preset_name] = path;
 
2079
                }
 
2080
 
 
2081
                delete *x;
 
2082
        }
 
2083
 
 
2084
        delete preset_files;
 
2085
 
 
2086
        /* now fill the vector<string> with the names we have */
 
2087
 
 
2088
        for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
 
2089
                _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
 
2090
        }
 
2091
 
 
2092
        /* add factory presets */
 
2093
 
 
2094
        for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
 
2095
                /* XXX: dubious */
 
2096
                string const uri = string_compose ("%1", _presets.size ());
 
2097
                _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
 
2098
        }
 
2099
}
 
2100
 
 
2101
bool
 
2102
AUPlugin::has_editor () const
 
2103
{
 
2104
        // even if the plugin doesn't have its own editor, the AU API can be used
 
2105
        // to create one that looks native.
 
2106
        return true;
 
2107
}
 
2108
 
 
2109
AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
 
2110
        : descriptor (d)
 
2111
{
 
2112
        type = ARDOUR::AudioUnit;
 
2113
}
 
2114
 
 
2115
AUPluginInfo::~AUPluginInfo ()
 
2116
{
 
2117
        type = ARDOUR::AudioUnit;
 
2118
}
 
2119
 
 
2120
PluginPtr
 
2121
AUPluginInfo::load (Session& session)
 
2122
{
 
2123
        try {
 
2124
                PluginPtr plugin;
 
2125
 
 
2126
                DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
 
2127
                boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
 
2128
 
 
2129
                if (!comp->IsValid()) {
 
2130
                        error << ("AudioUnit: not a valid Component") << endmsg;
 
2131
                } else {
 
2132
                        plugin.reset (new AUPlugin (session.engine(), session, comp));
 
2133
                }
 
2134
 
 
2135
                AUPluginInfo *aup = new AUPluginInfo (*this);
 
2136
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
 
2137
                plugin->set_info (PluginInfoPtr (aup));
 
2138
                boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
 
2139
                return plugin;
 
2140
        }
 
2141
 
 
2142
        catch (failed_constructor &err) {
 
2143
                DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
 
2144
                return PluginPtr ();
 
2145
        }
 
2146
}
 
2147
 
 
2148
Glib::ustring
 
2149
AUPluginInfo::au_cache_path ()
 
2150
{
 
2151
        return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
 
2152
}
 
2153
 
 
2154
PluginInfoList*
 
2155
AUPluginInfo::discover ()
 
2156
{
 
2157
        XMLTree tree;
 
2158
 
 
2159
        if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
 
2160
                ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
 
2161
        }
 
2162
 
 
2163
        PluginInfoList* plugs = new PluginInfoList;
 
2164
 
 
2165
        discover_fx (*plugs);
 
2166
        discover_music (*plugs);
 
2167
        discover_generators (*plugs);
 
2168
        discover_instruments (*plugs);
 
2169
 
 
2170
        DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
 
2171
 
 
2172
        return plugs;
 
2173
}
 
2174
 
 
2175
void
 
2176
AUPluginInfo::discover_music (PluginInfoList& plugs)
 
2177
{
 
2178
        CAComponentDescription desc;
 
2179
        desc.componentFlags = 0;
 
2180
        desc.componentFlagsMask = 0;
 
2181
        desc.componentSubType = 0;
 
2182
        desc.componentManufacturer = 0;
 
2183
        desc.componentType = kAudioUnitType_MusicEffect;
 
2184
 
 
2185
        discover_by_description (plugs, desc);
 
2186
}
 
2187
 
 
2188
void
 
2189
AUPluginInfo::discover_fx (PluginInfoList& plugs)
 
2190
{
 
2191
        CAComponentDescription desc;
 
2192
        desc.componentFlags = 0;
 
2193
        desc.componentFlagsMask = 0;
 
2194
        desc.componentSubType = 0;
 
2195
        desc.componentManufacturer = 0;
 
2196
        desc.componentType = kAudioUnitType_Effect;
 
2197
 
 
2198
        discover_by_description (plugs, desc);
 
2199
}
 
2200
 
 
2201
void
 
2202
AUPluginInfo::discover_generators (PluginInfoList& plugs)
 
2203
{
 
2204
        CAComponentDescription desc;
 
2205
        desc.componentFlags = 0;
 
2206
        desc.componentFlagsMask = 0;
 
2207
        desc.componentSubType = 0;
 
2208
        desc.componentManufacturer = 0;
 
2209
        desc.componentType = kAudioUnitType_Generator;
 
2210
 
 
2211
        discover_by_description (plugs, desc);
 
2212
}
 
2213
 
 
2214
void
 
2215
AUPluginInfo::discover_instruments (PluginInfoList& plugs)
 
2216
{
 
2217
        CAComponentDescription desc;
 
2218
        desc.componentFlags = 0;
 
2219
        desc.componentFlagsMask = 0;
 
2220
        desc.componentSubType = 0;
 
2221
        desc.componentManufacturer = 0;
 
2222
        desc.componentType = kAudioUnitType_MusicDevice;
 
2223
 
 
2224
        discover_by_description (plugs, desc);
 
2225
}
 
2226
 
 
2227
void
 
2228
AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
 
2229
{
 
2230
        Component comp = 0;
 
2231
 
 
2232
        comp = FindNextComponent (NULL, &desc);
 
2233
 
 
2234
        while (comp != NULL) {
 
2235
                CAComponentDescription temp;
 
2236
                GetComponentInfo (comp, &temp, NULL, NULL, NULL);
 
2237
 
 
2238
                AUPluginInfoPtr info (new AUPluginInfo
 
2239
                                      (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
 
2240
 
 
2241
                /* although apple designed the subtype field to be a "category" indicator,
 
2242
                   its really turned into a plugin ID field for a given manufacturer. Hence
 
2243
                   there are no categories for AudioUnits. However, to keep the plugins
 
2244
                   showing up under "categories", we'll use the "type" as a high level
 
2245
                   selector.
 
2246
 
 
2247
                   NOTE: no panners, format converters or i/o AU's for our purposes
 
2248
                 */
 
2249
 
 
2250
                switch (info->descriptor->Type()) {
 
2251
                case kAudioUnitType_Panner:
 
2252
                case kAudioUnitType_OfflineEffect:
 
2253
                case kAudioUnitType_FormatConverter:
 
2254
                        continue;
 
2255
 
 
2256
                case kAudioUnitType_Output:
 
2257
                        info->category = _("AudioUnit Outputs");
 
2258
                        break;
 
2259
                case kAudioUnitType_MusicDevice:
 
2260
                        info->category = _("AudioUnit Instruments");
 
2261
                        break;
 
2262
                case kAudioUnitType_MusicEffect:
 
2263
                        info->category = _("AudioUnit MusicEffects");
 
2264
                        break;
 
2265
                case kAudioUnitType_Effect:
 
2266
                        info->category = _("AudioUnit Effects");
 
2267
                        break;
 
2268
                case kAudioUnitType_Mixer:
 
2269
                        info->category = _("AudioUnit Mixers");
 
2270
                        break;
 
2271
                case kAudioUnitType_Generator:
 
2272
                        info->category = _("AudioUnit Generators");
 
2273
                        break;
 
2274
                default:
 
2275
                        info->category = _("AudioUnit (Unknown)");
 
2276
                        break;
 
2277
                }
 
2278
 
 
2279
                AUPluginInfo::get_names (temp, info->name, info->creator);
 
2280
 
 
2281
                info->type = ARDOUR::AudioUnit;
 
2282
                info->unique_id = stringify_descriptor (*info->descriptor);
 
2283
 
 
2284
                /* XXX not sure of the best way to handle plugin versioning yet
 
2285
                 */
 
2286
 
 
2287
                CAComponent cacomp (*info->descriptor);
 
2288
 
 
2289
                if (cacomp.GetResourceVersion (info->version) != noErr) {
 
2290
                        info->version = 0;
 
2291
                }
 
2292
 
 
2293
                if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
 
2294
 
 
2295
                        /* here we have to map apple's wildcard system to a simple pair
 
2296
                           of values. in ::can_do() we use the whole system, but here
 
2297
                           we need a single pair of values. XXX probably means we should
 
2298
                           remove any use of these values.
 
2299
 
 
2300
                           for now, if the plugin provides a wildcard, treat it as 1. we really
 
2301
                           don't care much, because whether we can handle an i/o configuration
 
2302
                           depends upon ::can_support_io_configuration(), not these counts.
 
2303
 
 
2304
                           they exist because other parts of ardour try to present i/o configuration
 
2305
                           info to the user, which should perhaps be revisited.
 
2306
                        */
 
2307
 
 
2308
                        int32_t possible_in = info->cache.io_configs.front().first;
 
2309
                        int32_t possible_out = info->cache.io_configs.front().second;
 
2310
                        
 
2311
                        if (possible_in > 0) {
 
2312
                                info->n_inputs.set (DataType::AUDIO, possible_in);
 
2313
                        } else {
 
2314
                                info->n_inputs.set (DataType::AUDIO, 1);
 
2315
                        }
 
2316
 
 
2317
                        if (possible_out > 0) {
 
2318
                                info->n_outputs.set (DataType::AUDIO, possible_out);
 
2319
                        } else {
 
2320
                                info->n_outputs.set (DataType::AUDIO, 1);
 
2321
                        }
 
2322
 
 
2323
                        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
 
2324
                                                                        info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
 
2325
 
 
2326
                        plugs.push_back (info);
 
2327
 
 
2328
                } else {
 
2329
                        error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
 
2330
                }
 
2331
 
 
2332
                comp = FindNextComponent (comp, &desc);
 
2333
        }
 
2334
}
 
2335
 
 
2336
bool
 
2337
AUPluginInfo::cached_io_configuration (const std::string& unique_id,
 
2338
                                       UInt32 version,
 
2339
                                       CAComponent& comp,
 
2340
                                       AUPluginCachedInfo& cinfo,
 
2341
                                       const std::string& name)
 
2342
{
 
2343
        std::string id;
 
2344
        char buf[32];
 
2345
 
 
2346
        /* concatenate unique ID with version to provide a key for cached info lookup.
 
2347
           this ensures we don't get stale information, or should if plugin developers
 
2348
           follow Apple "guidelines".
 
2349
         */
 
2350
 
 
2351
        snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
 
2352
        id = unique_id;
 
2353
        id += '/';
 
2354
        id += buf;
 
2355
 
 
2356
        CachedInfoMap::iterator cim = cached_info.find (id);
 
2357
 
 
2358
        if (cim != cached_info.end()) {
 
2359
                cinfo = cim->second;
 
2360
                return true;
 
2361
        }
 
2362
 
 
2363
        CAAudioUnit unit;
 
2364
        AUChannelInfo* channel_info;
 
2365
        UInt32 cnt;
 
2366
        int ret;
 
2367
 
 
2368
        ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
 
2369
 
 
2370
        try {
 
2371
 
 
2372
                if (CAAudioUnit::Open (comp, unit) != noErr) {
 
2373
                        return false;
 
2374
                }
 
2375
 
 
2376
        } catch (...) {
 
2377
 
 
2378
                warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
 
2379
                return false;
 
2380
 
 
2381
        }
 
2382
 
 
2383
        DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
 
2384
        if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
 
2385
                return false;
 
2386
        }
 
2387
 
 
2388
        if (ret > 0) {
 
2389
 
 
2390
                /* no explicit info available, so default to 1in/1out */
 
2391
 
 
2392
                /* XXX this is wrong. we should be indicating wildcard values */
 
2393
 
 
2394
                cinfo.io_configs.push_back (pair<int,int> (-1, -1));
 
2395
 
 
2396
        } else {
 
2397
 
 
2398
                /* store each configuration */
 
2399
 
 
2400
                for (uint32_t n = 0; n < cnt; ++n) {
 
2401
                        cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
 
2402
                                                                   channel_info[n].outChannels));
 
2403
                }
 
2404
 
 
2405
                free (channel_info);
 
2406
        }
 
2407
 
 
2408
        add_cached_info (id, cinfo);
 
2409
        save_cached_info ();
 
2410
 
 
2411
        return true;
 
2412
}
 
2413
 
 
2414
void
 
2415
AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
 
2416
{
 
2417
        cached_info[id] = cinfo;
 
2418
}
 
2419
 
 
2420
#define AU_CACHE_VERSION "2.0"
 
2421
 
 
2422
void
 
2423
AUPluginInfo::save_cached_info ()
 
2424
{
 
2425
        XMLNode* node;
 
2426
 
 
2427
        node = new XMLNode (X_("AudioUnitPluginCache"));
 
2428
        node->add_property( "version", AU_CACHE_VERSION );
 
2429
 
 
2430
        for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
 
2431
                XMLNode* parent = new XMLNode (X_("plugin"));
 
2432
                parent->add_property ("id", i->first);
 
2433
                node->add_child_nocopy (*parent);
 
2434
 
 
2435
                for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
 
2436
 
 
2437
                        XMLNode* child = new XMLNode (X_("io"));
 
2438
                        char buf[32];
 
2439
 
 
2440
                        snprintf (buf, sizeof (buf), "%d", j->first);
 
2441
                        child->add_property (X_("in"), buf);
 
2442
                        snprintf (buf, sizeof (buf), "%d", j->second);
 
2443
                        child->add_property (X_("out"), buf);
 
2444
                        parent->add_child_nocopy (*child);
 
2445
                }
 
2446
 
 
2447
        }
 
2448
 
 
2449
        Glib::ustring path = au_cache_path ();
 
2450
        XMLTree tree;
 
2451
 
 
2452
        tree.set_root (node);
 
2453
 
 
2454
        if (!tree.write (path)) {
 
2455
                error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
 
2456
                unlink (path.c_str());
 
2457
        }
 
2458
}
 
2459
 
 
2460
int
 
2461
AUPluginInfo::load_cached_info ()
 
2462
{
 
2463
        Glib::ustring path = au_cache_path ();
 
2464
        XMLTree tree;
 
2465
 
 
2466
        if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
 
2467
                return 0;
 
2468
        }
 
2469
 
 
2470
        if ( !tree.read (path) ) {
 
2471
                error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
 
2472
                return -1;
 
2473
        }
 
2474
 
 
2475
        const XMLNode* root (tree.root());
 
2476
 
 
2477
        if (root->name() != X_("AudioUnitPluginCache")) {
 
2478
                return -1;
 
2479
        }
 
2480
 
 
2481
        //initial version has incorrectly stored i/o info, and/or garbage chars.
 
2482
        const XMLProperty* version = root->property(X_("version"));
 
2483
        if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
 
2484
                error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
 
2485
                return -1;
 
2486
        }
 
2487
 
 
2488
        cached_info.clear ();
 
2489
 
 
2490
        const XMLNodeList children = root->children();
 
2491
 
 
2492
        for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
 
2493
 
 
2494
                const XMLNode* child = *iter;
 
2495
 
 
2496
                if (child->name() == X_("plugin")) {
 
2497
 
 
2498
                        const XMLNode* gchild;
 
2499
                        const XMLNodeList gchildren = child->children();
 
2500
                        const XMLProperty* prop = child->property (X_("id"));
 
2501
 
 
2502
                        if (!prop) {
 
2503
                                continue;
 
2504
                        }
 
2505
 
 
2506
                        string id = prop->value();
 
2507
                        string fixed;
 
2508
                        string version;
 
2509
 
 
2510
                        string::size_type slash = id.find_last_of ('/');
 
2511
 
 
2512
                        if (slash == string::npos) {
 
2513
                                continue;
 
2514
                        }
 
2515
 
 
2516
                        version = id.substr (slash);
 
2517
                        id = id.substr (0, slash);
 
2518
                        fixed = AUPlugin::maybe_fix_broken_au_id (id);
 
2519
 
 
2520
                        if (fixed.empty()) {
 
2521
                                error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
 
2522
                                continue;
 
2523
                        }
 
2524
 
 
2525
                        id = fixed;
 
2526
                        id += version;
 
2527
 
 
2528
                        AUPluginCachedInfo cinfo;
 
2529
 
 
2530
                        for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
 
2531
 
 
2532
                                gchild = *giter;
 
2533
 
 
2534
                                if (gchild->name() == X_("io")) {
 
2535
 
 
2536
                                        int in;
 
2537
                                        int out;
 
2538
                                        const XMLProperty* iprop;
 
2539
                                        const XMLProperty* oprop;
 
2540
 
 
2541
                                        if (((iprop = gchild->property (X_("in"))) != 0) &&
 
2542
                                            ((oprop = gchild->property (X_("out"))) != 0)) {
 
2543
                                                in = atoi (iprop->value());
 
2544
                                                out = atoi (oprop->value());
 
2545
 
 
2546
                                                cinfo.io_configs.push_back (pair<int,int> (in, out));
 
2547
                                        }
 
2548
                                }
 
2549
                        }
 
2550
 
 
2551
                        if (cinfo.io_configs.size()) {
 
2552
                                add_cached_info (id, cinfo);
 
2553
                        }
 
2554
                }
 
2555
        }
 
2556
 
 
2557
        return 0;
 
2558
}
 
2559
 
 
2560
void
 
2561
AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
 
2562
{
 
2563
        CFStringRef itemName = NULL;
 
2564
 
 
2565
        // Marc Poirier-style item name
 
2566
        CAComponent auComponent (comp_desc);
 
2567
        if (auComponent.IsValid()) {
 
2568
                CAComponentDescription dummydesc;
 
2569
                Handle nameHandle = NewHandle(sizeof(void*));
 
2570
                if (nameHandle != NULL) {
 
2571
                        OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
 
2572
                        if (err == noErr) {
 
2573
                                ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
 
2574
                                if (nameString != NULL) {
 
2575
                                        itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
 
2576
                                }
 
2577
                        }
 
2578
                        DisposeHandle(nameHandle);
 
2579
                }
 
2580
        }
 
2581
 
 
2582
        // if Marc-style fails, do the original way
 
2583
        if (itemName == NULL) {
 
2584
                CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
 
2585
                CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
 
2586
                CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
 
2587
 
 
2588
                itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
 
2589
                        compTypeString, compManufacturerString, compSubTypeString);
 
2590
 
 
2591
                if (compTypeString != NULL)
 
2592
                        CFRelease(compTypeString);
 
2593
                if (compSubTypeString != NULL)
 
2594
                        CFRelease(compSubTypeString);
 
2595
                if (compManufacturerString != NULL)
 
2596
                        CFRelease(compManufacturerString);
 
2597
        }
 
2598
 
 
2599
        string str = CFStringRefToStdString(itemName);
 
2600
        string::size_type colon = str.find (':');
 
2601
 
 
2602
        if (colon) {
 
2603
                name = str.substr (colon+1);
 
2604
                maker = str.substr (0, colon);
 
2605
                strip_whitespace_edges (maker);
 
2606
                strip_whitespace_edges (name);
 
2607
        } else {
 
2608
                name = str;
 
2609
                maker = "unknown";
 
2610
                strip_whitespace_edges (name);
 
2611
        }
 
2612
}
 
2613
 
 
2614
std::string
 
2615
AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
 
2616
{
 
2617
        stringstream s;
 
2618
 
 
2619
        /* note: OSType is a compiler-implemenation-defined value,
 
2620
           historically a 32 bit integer created with a multi-character
 
2621
           constant such as 'abcd'. It is, fundamentally, an abomination.
 
2622
        */
 
2623
 
 
2624
        s << desc.Type();
 
2625
        s << '-';
 
2626
        s << desc.SubType();
 
2627
        s << '-';
 
2628
        s << desc.Manu();
 
2629
 
 
2630
        return s.str();
 
2631
}
 
2632
 
 
2633
bool
 
2634
AUPluginInfo::needs_midi_input ()
 
2635
{
 
2636
        return is_effect_with_midi_input () || is_instrument ();
 
2637
}
 
2638
 
 
2639
bool
 
2640
AUPluginInfo::is_effect () const
 
2641
{
 
2642
        return is_effect_without_midi_input() || is_effect_with_midi_input();
 
2643
}
 
2644
 
 
2645
bool
 
2646
AUPluginInfo::is_effect_without_midi_input () const
 
2647
{
 
2648
        return descriptor->IsAUFX();
 
2649
}
 
2650
 
 
2651
bool
 
2652
AUPluginInfo::is_effect_with_midi_input () const
 
2653
{
 
2654
        return descriptor->IsAUFM();
 
2655
}
 
2656
 
 
2657
bool
 
2658
AUPluginInfo::is_instrument () const
 
2659
{
 
2660
        return descriptor->IsMusicDevice();
 
2661
}
 
2662
 
 
2663
void
 
2664
AUPlugin::set_info (PluginInfoPtr info)
 
2665
{
 
2666
        Plugin::set_info (info);
 
2667
        
 
2668
        AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
 
2669
        _has_midi_input = pinfo->needs_midi_input ();
 
2670
        _has_midi_output = false;
 
2671
}
 
2672
 
 
2673
int
 
2674
AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
 
2675
{
 
2676
#ifdef WITH_CARBON
 
2677
        CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop()); 
 
2678
#else
 
2679
        CFRunLoopRef run_loop = CFRunLoopGetCurrent();
 
2680
#endif
 
2681
        CFStringRef  loop_mode = kCFRunLoopDefaultMode;
 
2682
 
 
2683
        if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
 
2684
                return -1;
 
2685
        }
 
2686
 
 
2687
        _parameter_listener_arg = arg;
 
2688
 
 
2689
        return 0;
 
2690
}
 
2691
 
 
2692
int
 
2693
AUPlugin::listen_to_parameter (uint32_t param_id)
 
2694
{
 
2695
        AudioUnitEvent      event;
 
2696
 
 
2697
        if (!_parameter_listener || param_id >= descriptors.size()) {
 
2698
                return -2;
 
2699
        }
 
2700
 
 
2701
        event.mEventType = kAudioUnitEvent_ParameterValueChange;
 
2702
        event.mArgument.mParameter.mAudioUnit = unit->AU();
 
2703
        event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
 
2704
        event.mArgument.mParameter.mScope = descriptors[param_id].scope;
 
2705
        event.mArgument.mParameter.mElement = descriptors[param_id].element;
 
2706
 
 
2707
        if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
 
2708
                return -1;
 
2709
        } 
 
2710
 
 
2711
        event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
 
2712
        event.mArgument.mParameter.mAudioUnit = unit->AU();
 
2713
        event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
 
2714
        event.mArgument.mParameter.mScope = descriptors[param_id].scope;
 
2715
        event.mArgument.mParameter.mElement = descriptors[param_id].element;
 
2716
 
 
2717
        if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
 
2718
                return -1;
 
2719
        } 
 
2720
 
 
2721
        event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
 
2722
        event.mArgument.mParameter.mAudioUnit = unit->AU();
 
2723
        event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
 
2724
        event.mArgument.mParameter.mScope = descriptors[param_id].scope;
 
2725
        event.mArgument.mParameter.mElement = descriptors[param_id].element;
 
2726
 
 
2727
        if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
 
2728
                return -1;
 
2729
        } 
 
2730
 
 
2731
        return 0;
 
2732
}
 
2733
 
 
2734
int
 
2735
AUPlugin::end_listen_to_parameter (uint32_t param_id)
 
2736
{
 
2737
        AudioUnitEvent      event;
 
2738
 
 
2739
        if (!_parameter_listener || param_id >= descriptors.size()) {
 
2740
                return -2;
 
2741
        }
 
2742
 
 
2743
        event.mEventType = kAudioUnitEvent_ParameterValueChange;
 
2744
        event.mArgument.mParameter.mAudioUnit = unit->AU();
 
2745
        event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
 
2746
        event.mArgument.mParameter.mScope = descriptors[param_id].scope;
 
2747
        event.mArgument.mParameter.mElement = descriptors[param_id].element;
 
2748
 
 
2749
        if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
 
2750
                return -1;
 
2751
        } 
 
2752
 
 
2753
        event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
 
2754
        event.mArgument.mParameter.mAudioUnit = unit->AU();
 
2755
        event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
 
2756
        event.mArgument.mParameter.mScope = descriptors[param_id].scope;
 
2757
        event.mArgument.mParameter.mElement = descriptors[param_id].element;
 
2758
 
 
2759
        if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
 
2760
                return -1;
 
2761
        } 
 
2762
 
 
2763
        event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
 
2764
        event.mArgument.mParameter.mAudioUnit = unit->AU();
 
2765
        event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
 
2766
        event.mArgument.mParameter.mScope = descriptors[param_id].scope;
 
2767
        event.mArgument.mParameter.mElement = descriptors[param_id].element;
 
2768
 
 
2769
        if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
 
2770
                return -1;
 
2771
        } 
 
2772
 
 
2773
        return 0;
 
2774
}
 
2775
 
 
2776
void
 
2777
AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
 
2778
{
 
2779
        ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
 
2780
}
 
2781
 
 
2782
void
 
2783
AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
 
2784
{
 
2785
        ParameterMap::iterator i;
 
2786
 
 
2787
        if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
 
2788
                return;
 
2789
        }
 
2790
        
 
2791
        switch (event->mEventType) {
 
2792
        case kAudioUnitEvent_BeginParameterChangeGesture:
 
2793
                StartTouch (i->second);
 
2794
                break;
 
2795
        case kAudioUnitEvent_EndParameterChangeGesture:
 
2796
                EndTouch (i->second);
 
2797
                break;
 
2798
        case kAudioUnitEvent_ParameterValueChange:
 
2799
                ParameterChanged (i->second, new_value);
 
2800
                break;
 
2801
        default:
 
2802
                break;
 
2803
        }
 
2804
}