fix maths thinko
[ardour.git] / libs / ardour / session_vst.cc
1 /*
2     Copyright (C) 2004
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifndef COMPILER_MSVC
21 #include <stdbool.h>
22 #endif
23 #include <cstdio>
24
25 #include "ardour/audioengine.h"
26 #include "ardour/debug.h"
27 #include "ardour/session.h"
28 #include "ardour/tempo.h"
29 #include "ardour/plugin_insert.h"
30 #include "ardour/windows_vst_plugin.h"
31 #include "ardour/vestige/aeffectx.h"
32 #include "ardour/vst_types.h"
33 #ifdef WINDOWS_VST_SUPPORT
34 #include <fst.h>
35 #endif
36
37 #include "i18n.h"
38
39 using namespace ARDOUR;
40
41 #define SHOW_CALLBACK(MSG) DEBUG_TRACE (PBD::DEBUG::VSTCallbacks, string_compose (MSG " val = %1 idx = %2\n", index, value))
42
43 static double
44 vst_ppq (const TempoMetric& tm, const Timecode::BBT_Time& bbt, double& ppqBar)
45 {
46
47         /* PPQ = pulse per quarter
48          * VST's "pulse" is our "division".
49          *
50          * 8 divisions per bar, 1 division = quarter, so 8 quarters per bar, ppq = 1
51          * 8 divisions per bar, 1 division = eighth, so  4 quarters per bar, ppq = 2
52          * 4 divisions per bar, 1 division = quarter, so  4 quarters per bar, ppq = 1
53          * 4 divisions per bar, 1 division = half, so 8 quarters per bar, ppq = 0.5
54          * 4 divisions per bar, 1 division = fifth, so (4 * 5/4) quarters per bar, ppq = 5/4
55          *
56          * general: divs_per_bar / (note_type / 4.0)
57          */
58         const double ppq_scaling =  tm.meter().note_divisor() / 4.0;
59
60         /* Note that this assumes constant meter/tempo throughout the session. Stupid VST */
61         ppqBar = double(bbt.bars - 1) * tm.meter().divisions_per_bar();
62         double ppqBeat = double(bbt.beats - 1);
63         double ppqTick = double(bbt.ticks) / Timecode::BBT_Time::ticks_per_beat;
64
65         ppqBar *= ppq_scaling;
66         ppqBeat *= ppq_scaling;
67         ppqTick *= ppq_scaling;
68
69         return ppqBar + ppqBeat + ppqTick;
70 }
71
72 int Session::vst_current_loading_id = 0;
73 const char* Session::vst_can_do_strings[] = {
74         X_("supplyIdle"),
75         X_("sendVstTimeInfo"),
76         X_("sendVstEvents"),
77         X_("sendVstMidiEvent"),
78         X_("receiveVstEvents"),
79         X_("receiveVstMidiEvent"),
80         X_("supportShell"),
81         X_("shellCategory"),
82         X_("shellCategorycurID")
83 };
84 const int Session::vst_can_do_string_count = sizeof (vst_can_do_strings) / sizeof (char*);
85
86 intptr_t Session::vst_callback (
87         AEffect* effect,
88         int32_t opcode,
89         int32_t index,
90         intptr_t value,
91         void* ptr,
92         float opt
93         )
94 {
95         VSTPlugin* plug;
96         Session* session;
97         static VstTimeInfo _timeinfo; // only uses as fallback
98         VstTimeInfo* timeinfo;
99         int32_t newflags = 0;
100
101         if (effect && effect->user) {
102                 plug = (VSTPlugin *) (effect->user);
103                 session = &plug->session();
104                 timeinfo = plug->timeinfo ();
105                 DEBUG_TRACE (PBD::DEBUG::VSTCallbacks, string_compose ("am callback 0x%1%2, opcode = %3%4, plugin = \"%5\"\n",
106                                         std::hex, (void*) DEBUG_THREAD_SELF,
107                                         std::dec, opcode, plug->name()));
108         } else {
109                 plug = 0;
110                 session = 0;
111                 timeinfo = &_timeinfo;
112                 DEBUG_TRACE (PBD::DEBUG::VSTCallbacks, string_compose ("am callback 0x%1%2, opcode = %3%4\n",
113                                         std::hex, (void*) DEBUG_THREAD_SELF,
114                                         std::dec, opcode));
115         }
116
117         switch(opcode){
118
119         case audioMasterAutomate:
120                 SHOW_CALLBACK ("audioMasterAutomate");
121                 // index, value, returns 0
122                 if (plug) {
123                         plug->parameter_changed_externally (index, opt);
124                 }
125                 return 0;
126
127         case audioMasterVersion:
128                 SHOW_CALLBACK ("audioMasterVersion");
129                 // vst version, currently 2 (0 for older)
130                 return 2400;
131
132         case audioMasterCurrentId:
133                 SHOW_CALLBACK ("audioMasterCurrentId");
134                 // returns the unique id of a plug that's currently loading
135                 return vst_current_loading_id;
136
137         case audioMasterIdle:
138                 SHOW_CALLBACK ("audioMasterIdle");
139 #ifdef WINDOWS_VST_SUPPORT
140                 fst_audio_master_idle();
141 #endif
142                 if (effect) {
143                         effect->dispatcher(effect, effEditIdle, 0, 0, NULL, 0.0f);
144                 }
145                 return 0;
146
147         case audioMasterPinConnected:
148                 SHOW_CALLBACK ("audioMasterPinConnected");
149                 // inquire if an input or output is beeing connected;
150                 // index enumerates input or output counting from zero:
151                 // value is 0 for input and != 0 otherwise. note: the
152                 // return value is 0 for <true> such that older versions
153                 // will always return true.
154                 if (!plug) {
155                         // we don't know.
156                         // but ardour always connects all buffers, so we're good
157                         return 0;
158                 }
159                 switch (value) {
160                         case 0:
161                                 if (plug->plugin_insert ()) {
162                                         bool valid;
163                                         const ChanMapping& map (plug->plugin_insert ()->input_map (plug->plugin_number ()));
164                                         map.get (DataType::AUDIO, index, &valid);
165                                         return valid ? 0 : 1;
166                                 }
167                                 if (index < plug->plugin()->numInputs) {
168                                         return 0;
169                                 }
170                                 break;
171                         case 1:
172 #if 0 // investigate, the outputs *are* connected to scratch buffers
173                                 if (plug->plugin_insert ()) {
174                                         bool valid;
175                                         const ChanMapping& map (plug->plugin_insert ()->output_map (plug->plugin_number ()));
176                                         map.get (DataType::AUDIO, index, &valid);
177                                         return valid ? 0 : 1;
178                                 }
179 #endif
180                                 if (index < plug->plugin()->numOutputs) {
181                                         return 0;
182                                 }
183                                 break;
184                         default:
185                                 break;
186                 }
187                 return 1;
188
189         case audioMasterWantMidi:
190                 SHOW_CALLBACK ("audioMasterWantMidi");
191                 // <value> is a filter which is currently ignored
192                 if (plug && plug->get_info() != NULL) {
193                         plug->get_info()->n_inputs.set_midi (1);
194                 }
195                 return 0;
196
197         case audioMasterGetTime:
198                 SHOW_CALLBACK ("audioMasterGetTime");
199                 newflags = kVstNanosValid | kVstAutomationWriting | kVstAutomationReading;
200
201                 timeinfo->nanoSeconds = g_get_monotonic_time () * 1000;
202
203                 if (session) {
204                         framepos_t now = session->transport_frame();
205
206                         timeinfo->samplePos = now;
207                         timeinfo->sampleRate = session->frame_rate();
208
209                         const TempoMetric& tm (session->tempo_map().metric_at (now));
210
211                         if (value & (kVstTempoValid)) {
212                                 const Tempo& t (tm.tempo());
213                                 timeinfo->tempo = t.beats_per_minute ();
214                                 newflags |= (kVstTempoValid);
215                         }
216                         if (value & (kVstTimeSigValid)) {
217                                 const Meter& m (tm.meter());
218                                 timeinfo->timeSigNumerator = m.divisions_per_bar ();
219                                 timeinfo->timeSigDenominator = m.note_divisor ();
220                                 newflags |= (kVstTimeSigValid);
221                         }
222                         if ((value & (kVstPpqPosValid)) || (value & (kVstBarsValid))) {
223                                 Timecode::BBT_Time bbt;
224
225                                 try {
226                                         session->tempo_map().bbt_time_rt (now, bbt);
227                                         double ppqBar;
228                                         double ppqPos = vst_ppq (tm, bbt, ppqBar);
229
230                                         if (value & (kVstPpqPosValid)) {
231                                                 timeinfo->ppqPos = ppqPos;
232                                                 newflags |= kVstPpqPosValid;
233                                         }
234
235                                         if (value & (kVstBarsValid)) {
236                                                 timeinfo->barStartPos = ppqBar;
237                                                 newflags |= kVstBarsValid;
238                                         }
239
240                                 } catch (...) {
241                                         /* relax */
242                                 }
243                         }
244
245                         if (value & (kVstSmpteValid)) {
246                                 Timecode::Time t;
247
248                                 session->timecode_time (now, t);
249
250                                 timeinfo->smpteOffset = (t.hours * t.rate * 60.0 * 60.0) +
251                                         (t.minutes * t.rate * 60.0) +
252                                         (t.seconds * t.rate) +
253                                         (t.frames) +
254                                         (t.subframes);
255
256                                 timeinfo->smpteOffset *= 80.0; /* VST spec is 1/80th frames */
257
258                                 if (session->timecode_drop_frames()) {
259                                         if (session->timecode_frames_per_second() == 30.0) {
260                                                 timeinfo->smpteFrameRate = 5;
261                                         } else {
262                                                 timeinfo->smpteFrameRate = 4; /* 29.97 assumed, thanks VST */
263                                         }
264                                 } else {
265                                         if (session->timecode_frames_per_second() == 24.0) {
266                                                 timeinfo->smpteFrameRate = 0;
267                                         } else if (session->timecode_frames_per_second() == 24.975) {
268                                                 timeinfo->smpteFrameRate = 2;
269                                         } else if (session->timecode_frames_per_second() == 25.0) {
270                                                 timeinfo->smpteFrameRate = 1;
271                                         } else {
272                                                 timeinfo->smpteFrameRate = 3; /* 30 fps */
273                                         }
274                                 }
275                                 newflags |= (kVstSmpteValid);
276                         }
277
278                         if (session->actively_recording ()) {
279                                 newflags |= kVstTransportRecording;
280                         }
281
282                         if (session->transport_speed () != 0.0f) {
283                                 newflags |= kVstTransportPlaying;
284                         }
285
286                         if (session->get_play_loop ()) {
287                                 newflags |= kVstTransportCycleActive;
288                                 Location * looploc = session->locations ()->auto_loop_location ();
289                                 if (looploc) try {
290                                         double ppqBar;
291                                         Timecode::BBT_Time bbt;
292
293                                         session->tempo_map().bbt_time_rt (looploc->start (), bbt);
294                                         timeinfo->cycleStartPos = vst_ppq (tm, bbt, ppqBar);
295
296                                         session->tempo_map().bbt_time_rt (looploc->end (), bbt);
297                                         timeinfo->cycleEndPos = vst_ppq (tm, bbt, ppqBar);
298
299                                         newflags |= kVstCyclePosValid;
300                                 } catch (...) { }
301                         }
302
303                 } else {
304                         timeinfo->samplePos = 0;
305                         timeinfo->sampleRate = AudioEngine::instance()->sample_rate();
306                 }
307
308                 if ((timeinfo->flags & (kVstTransportPlaying | kVstTransportRecording | kVstTransportCycleActive))
309                     !=
310                     (newflags        & (kVstTransportPlaying | kVstTransportRecording | kVstTransportCycleActive)))
311                 {
312                         newflags |= kVstTransportChanged;
313                 }
314
315                 timeinfo->flags = newflags;
316                 return (intptr_t) timeinfo;
317
318         case audioMasterProcessEvents:
319                 SHOW_CALLBACK ("audioMasterProcessEvents");
320                 // VstEvents* in <ptr>
321                 if (plug && plug->midi_buffer()) {
322                         VstEvents* v = (VstEvents*)ptr;
323                         for (int n = 0 ; n < v->numEvents; ++n) {
324                                 VstMidiEvent *vme = (VstMidiEvent*) (v->events[n]->dump);
325                                 if (vme->type == kVstMidiType) {
326                                         plug->midi_buffer()->push_back(vme->deltaFrames, 3, (uint8_t*)vme->midiData);
327                                 }
328                         }
329                 }
330                 return 0;
331
332         case audioMasterSetTime:
333                 SHOW_CALLBACK ("audioMasterSetTime");
334                 // VstTimenfo* in <ptr>, filter in <value>, not supported
335
336         case audioMasterTempoAt:
337                 SHOW_CALLBACK ("audioMasterTempoAt");
338                 // returns tempo (in bpm * 10000) at sample frame location passed in <value>
339                 if (session) {
340                         const Tempo& t (session->tempo_map().tempo_at (value));
341                         return t.beats_per_minute() * 1000;
342                 } else {
343                         return 0;
344                 }
345                 break;
346
347         case audioMasterGetNumAutomatableParameters:
348                 SHOW_CALLBACK ("audioMasterGetNumAutomatableParameters");
349                 return 0;
350
351         case audioMasterGetParameterQuantization:
352                 SHOW_CALLBACK ("audioMasterGetParameterQuantization");
353                 // returns the integer value for +1.0 representation,
354                 // or 1 if full single float precision is maintained
355                 // in automation. parameter index in <value> (-1: all, any)
356                 return 0;
357
358         case audioMasterIOChanged:
359                 SHOW_CALLBACK ("audioMasterIOChanged");
360                 // numInputs and/or numOutputs has changed
361                 return 0;
362
363         case audioMasterNeedIdle:
364                 SHOW_CALLBACK ("audioMasterNeedIdle");
365                 // plug needs idle calls (outside its editor window)
366                 if (plug) {
367                         plug->state()->wantIdle = 1;
368                 }
369                 return 0;
370
371         case audioMasterSizeWindow:
372                 SHOW_CALLBACK ("audioMasterSizeWindow");
373                 if (plug && plug->state()) {
374                         plug->state()->width = index;
375                         plug->state()->height = value;
376                         plug->state()->want_resize = 1;
377                 }
378                 return 0;
379
380         case audioMasterGetSampleRate:
381                 SHOW_CALLBACK ("audioMasterGetSampleRate");
382                 if (session) {
383                         return session->frame_rate();
384                 }
385                 return 0;
386
387         case audioMasterGetBlockSize:
388                 SHOW_CALLBACK ("audioMasterGetBlockSize");
389                 if (session) {
390                         return session->get_block_size();
391                 }
392                 return 0;
393
394         case audioMasterGetInputLatency:
395                 SHOW_CALLBACK ("audioMasterGetInputLatency");
396                 return 0;
397
398         case audioMasterGetOutputLatency:
399                 SHOW_CALLBACK ("audioMasterGetOutputLatency");
400                 return 0;
401
402         case audioMasterGetPreviousPlug:
403                 SHOW_CALLBACK ("audioMasterGetPreviousPlug");
404                 // input pin in <value> (-1: first to come), returns cEffect*
405                 return 0;
406
407         case audioMasterGetNextPlug:
408                 SHOW_CALLBACK ("audioMasterGetNextPlug");
409                 // output pin in <value> (-1: first to come), returns cEffect*
410
411         case audioMasterWillReplaceOrAccumulate:
412                 SHOW_CALLBACK ("audioMasterWillReplaceOrAccumulate");
413                 // returns: 0: not supported, 1: replace, 2: accumulate
414                 return 0;
415
416         case audioMasterGetCurrentProcessLevel:
417                 SHOW_CALLBACK ("audioMasterGetCurrentProcessLevel");
418                 // returns: 0: not supported,
419                 // 1: currently in user thread (gui)
420                 // 2: currently in audio thread (where process is called)
421                 // 3: currently in 'sequencer' thread (midi, timer etc)
422                 // 4: currently offline processing and thus in user thread
423                 // other: not defined, but probably pre-empting user thread.
424                 return 0;
425
426         case audioMasterGetAutomationState:
427                 SHOW_CALLBACK ("audioMasterGetAutomationState");
428                 // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
429                 // offline
430                 return 0;
431
432         case audioMasterOfflineStart:
433                 SHOW_CALLBACK ("audioMasterOfflineStart");
434                 return 0;
435
436         case audioMasterOfflineRead:
437                 SHOW_CALLBACK ("audioMasterOfflineRead");
438                 // ptr points to offline structure, see below. return 0: error, 1 ok
439                 return 0;
440
441         case audioMasterOfflineWrite:
442                 SHOW_CALLBACK ("audioMasterOfflineWrite");
443                 // same as read
444                 return 0;
445
446         case audioMasterOfflineGetCurrentPass:
447                 SHOW_CALLBACK ("audioMasterOfflineGetCurrentPass");
448                 return 0;
449
450         case audioMasterOfflineGetCurrentMetaPass:
451                 SHOW_CALLBACK ("audioMasterOfflineGetCurrentMetaPass");
452                 return 0;
453
454         case audioMasterSetOutputSampleRate:
455                 SHOW_CALLBACK ("audioMasterSetOutputSampleRate");
456                 // for variable i/o, sample rate in <opt>
457                 return 0;
458
459         case audioMasterGetSpeakerArrangement:
460                 SHOW_CALLBACK ("audioMasterGetSpeakerArrangement");
461                 // (long)input in <value>, output in <ptr>
462                 return 0;
463
464         case audioMasterGetVendorString:
465                 SHOW_CALLBACK ("audioMasterGetVendorString");
466                 // fills <ptr> with a string identifying the vendor (max 64 char)
467                 strcpy ((char*) ptr, "Linux Audio Systems");
468                 return 0;
469
470         case audioMasterGetProductString:
471                 SHOW_CALLBACK ("audioMasterGetProductString");
472                 // fills <ptr> with a string with product name (max 64 char)
473                 strcpy ((char*) ptr, PROGRAM_NAME);
474                 return 0;
475
476         case audioMasterGetVendorVersion:
477                 SHOW_CALLBACK ("audioMasterGetVendorVersion");
478                 // returns vendor-specific version
479                 return 900;
480
481         case audioMasterVendorSpecific:
482                 SHOW_CALLBACK ("audioMasterVendorSpecific");
483                 // no definition, vendor specific handling
484                 return 0;
485
486         case audioMasterSetIcon:
487                 SHOW_CALLBACK ("audioMasterSetIcon");
488                 // void* in <ptr>, format not defined yet
489                 return 0;
490
491         case audioMasterCanDo:
492                 SHOW_CALLBACK ("audioMasterCanDo");
493                 // string in ptr,  (const char*)ptr
494                 for (int i = 0; i < vst_can_do_string_count; i++) {
495                         if (! strcmp(vst_can_do_strings[i], (const char*)ptr)) {
496                                 return 1;
497                         }
498                 }
499                 return 0;
500
501         case audioMasterGetLanguage:
502                 SHOW_CALLBACK ("audioMasterGetLanguage");
503                 // see enum
504                 return 0;
505
506         case audioMasterOpenWindow:
507                 SHOW_CALLBACK ("audioMasterOpenWindow");
508                 // returns platform specific ptr
509                 return 0;
510
511         case audioMasterCloseWindow:
512                 SHOW_CALLBACK ("audioMasterCloseWindow");
513                 // close window, platform specific handle in <ptr>
514                 return 0;
515
516         case audioMasterGetDirectory:
517                 SHOW_CALLBACK ("audioMasterGetDirectory");
518                 // get plug directory, FSSpec on MAC, else char*
519                 return 0;
520
521         case audioMasterUpdateDisplay:
522                 SHOW_CALLBACK ("audioMasterUpdateDisplay");
523                 // something has changed, update 'multi-fx' display
524                 if (effect) {
525                         effect->dispatcher(effect, effEditIdle, 0, 0, NULL, 0.0f);
526                 }
527                 return 0;
528
529         case audioMasterBeginEdit:
530                 SHOW_CALLBACK ("audioMasterBeginEdit");
531                 // begin of automation session (when mouse down), parameter index in <index>
532                 return 0;
533
534         case audioMasterEndEdit:
535                 SHOW_CALLBACK ("audioMasterEndEdit");
536                 // end of automation session (when mouse up),     parameter index in <index>
537                 return 0;
538
539         case audioMasterOpenFileSelector:
540                 SHOW_CALLBACK ("audioMasterOpenFileSelector");
541                 // open a fileselector window with VstFileSelect* in <ptr>
542                 return 0;
543
544         default:
545                 DEBUG_TRACE (PBD::DEBUG::VSTCallbacks, string_compose ("VST master dispatcher: undefed: %1\n", opcode));
546                 break;
547         }
548
549         return 0;
550 }
551