• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ossia / score / 43892858954

16 Nov 2026 03:06PM UTC coverage: 61.472% (+0.3%) from 61.219%
43892858954

push

github

jcelerier
score: the open right-click box is exported in every build, so add-ons using score's knobs, sliders and spinboxes link on Windows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdPgufUMRpkKzaYvUs9iHW

261684 of 791694 branches covered (33.05%)

267913 of 435828 relevant lines covered (61.47%)

724440.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.65
/src/plugins/score-plugin-vst/Vst/EffectModel.cpp
1
#include "EffectModel.hpp"
2

3
#include "Widgets.hpp"
4

5
#include <Process/Dataflow/Port.hpp>
6
#include <Process/Dataflow/PortFactory.hpp>
7

8
#include <Scenario/Document/ScenarioDocument/ScenarioDocumentModel.hpp>
9

10
#include <Audio/Settings/Model.hpp>
11
#include <Execution/DocumentPlugin.hpp>
12
#include <Vst/ApplicationPlugin.hpp>
13
#include <Vst/Commands.hpp>
14
#include <Vst/Control.hpp>
15
#include <Vst/Loader.hpp>
16
#include <Vst/Node.hpp>
17
#include <Vst/Window.hpp>
18

19
#include <score/tools/DeleteAll.hpp>
20
#include <score/tools/IdentifierGeneration.hpp>
21

22
#include <ossia/detail/math.hpp>
23
#include <ossia/detail/pod_vector.hpp>
24

25
#include <ossia-qt/invoke.hpp>
26

27
#include <QCoreApplication>
28
#include <QGuiApplication>
29
#include <QInputDialog>
30
#include <QTimer>
31

32
#include <websocketpp/base64/base64.hpp>
33

34
#include <cmath>
35
#include <wobjectimpl.h>
36

37
#include <memory>
38
W_OBJECT_IMPL(vst::Model)
11,506 !
39

40
// If a VST has less than this many parameters they will be shown by default.
41
#define VST_DEFAULT_PARAM_NUMBER_CUTOFF 10
42
namespace Process
43
{
44
template <>
45
QString EffectProcessFactory_T<vst::Model>::customConstructionData() const noexcept
×
46
{
47
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
×
48
  QStringList vsts;
×
49
  vsts.reserve(app.vst_infos.size());
×
50
  QMap<QString, int32_t> ids;
×
51
  for(vst::VSTInfo& i : app.vst_infos)
×
52
  {
53
    if(i.isValid)
×
54
    {
55
      auto name = i.prettyName;
×
56
      if(i.isSynth)
×
57
        name = "♪ " + name;
×
58
      vsts.push_back(name);
×
59
      ids.insert(name, i.uniqueID);
×
60
    }
×
61
  }
62
  ossia::sort(vsts);
×
63
  bool ok = false;
×
64
  auto res = QInputDialog::getItem(
×
65
      nullptr, QObject::tr("Select a VST plug-in"), QObject::tr("VST plug-in"), vsts, 0,
×
66
      false, &ok);
67
  if(ok)
×
68
    return QString::number(ids[res]);
×
69
  return {};
×
70
}
×
71

72
template <>
73
Process::Descriptor
74
EffectProcessFactory_T<vst::Model>::descriptor(QString d) const noexcept
65 ✔
75
{
76
  Process::Descriptor desc;
65 !
77
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
65 !
78

79
  auto it = ossia::find_if(
65 !
80
      app.vst_infos, [d](const vst::VSTInfo& vst) { return vst.uniqueID == d.toInt(); });
177 ✔
81
  desc.documentationLink = QUrl(
65 !
82
      "https://ossia.io/score-docs/processes/"
65 !
83
      "audio-plugins.html#common-formats-vst-vst3-lv2-jsfx");
84
  if(it != app.vst_infos.end())
65 ✔
85
  {
86
    desc.prettyName = it->displayName;
64 ✔
87
    if(desc.prettyName.isEmpty())
64 ✔
88
      desc.prettyName = it->prettyName;
48 ✔
89

90
    desc.author = it->author;
64 ✔
91

92
    if(it->isSynth)
64 ✔
93
    {
94
      desc.category = Process::ProcessCategory::Synth;
24 ✔
95

96
      auto inlets = std::vector<Process::PortType>{Process::PortType::Midi};
24 !
97
      for(int i = 0; i < it->controls; i++)
48 ✔
98
        inlets.push_back(Process::PortType::Message);
24 !
99
      desc.inlets = std::move(inlets);
24 ✔
100

101
      desc.outlets = {std::vector<Process::PortType>{Process::PortType::Audio}};
24 !
102
    }
24 ✔
103
    else
104
    {
105
      desc.category = Process::ProcessCategory::AudioEffect;
40 ✔
106

107
      auto inlets = std::vector<Process::PortType>{Process::PortType::Audio};
40 !
108
      for(int i = 0; i < it->controls; i++)
72 ✔
109
        inlets.push_back(Process::PortType::Message);
32 !
110
      desc.inlets = std::move(inlets);
40 ✔
111

112
      desc.outlets = {std::vector<Process::PortType>{Process::PortType::Audio}};
40 !
113
    }
40 ✔
114
  }
64 ✔
115
  return desc;
65 ✔
116
}
65 ✔
117

118
template <>
119
Process::Descriptor EffectProcessFactory_T<vst::Model>::descriptor(
64 ✔
120
    const Process::ProcessModel& d) const noexcept
121
{
122
  return descriptor(d.effect());
64 ✔
123
}
124
}
125

126
namespace vst
127
{
128
QString Model::getString(AEffectOpcodes op, int param)
380 ✔
129
{
130
  char paramName[512] = {0};
380 ✔
131
  dispatch(op, param, 0, paramName);
380 ✔
132
  return QString::fromUtf8(paramName);
380 ✔
133
}
134

135
Model::Model(
129 !
136
    TimeVal t, const QString& path, const Id<Process::ProcessModel>& id, QObject* parent)
137
    : ProcessModel{t, id, "vst", parent}
129 !
138
    , m_effectId{path.toInt()}
129 !
139
    , m_registration{*this}
129 !
140
{
129 ✔
141
  init();
129 !
142
  create();
129 !
143
}
129 ✔
144

145
Model::~Model()
355 ✔
146
{
160 ✔
147
  // close will set the pointer to nullptr
148
  if(this->externalUI)
195 !
149
    this->externalUI->close();
×
150

151
  if(fx)
195 ✔
152
    fx->host->model = nullptr;
190 ✔
153

154
  fx.reset();
195 ✔
155
}
355 ✔
156

157
Process::ProcessFlags Model::flags() const noexcept
1,026 ✔
158
{
159
  auto flags = Metadata<Process::ProcessFlags_k, Model>::get();
1,026 !
160
  if(fx && fx->fx)
1,026 !
161
  {
162
    if((fx->fx->numParams >= VST_DEFAULT_PARAM_NUMBER_CUTOFF)
1,026 ✔
163
       && (fx->fx->flags & VstAEffectFlags::effFlagsHasEditor))
1,026 !
164
    {
165
      flags |= Process::CanCreateControls;
×
166
    }
×
167
  }
1,026 ✔
168
  if(m_createControls)
1,026 ✔
169
    flags |= Process::CreateControls;
4 ✔
170
  return flags;
1,026 ✔
171
}
172

173
void Model::setCreatingControls(bool ok)
4 ✔
174
{
175
  if(ok != m_createControls)
4 ✔
176
  {
177
    m_createControls = ok;
2 ✔
178
    creatingControlsChanged(ok);
2 ✔
179
  }
2 ✔
180
}
4 ✔
181

182
QString Model::prettyName() const noexcept
20 ✔
183
{
184
  return metadata().getLabel();
20 ✔
185
}
186

187
bool Model::takesMidi() const noexcept
366 ✔
188
{
189
  return m_inlets.size() > 1 && m_inlets[1]->type() == Process::PortType::Midi;
366 !
190
}
191

192
bool Model::sendsMidi() const noexcept
163 ✔
193
{
194
  return m_outlets.size() > 1 && m_outlets[1]->type() == Process::PortType::Midi;
163 ✔
195
}
196

197
bool Model::hasExternalUI() const noexcept
34 ✔
198
{
199
  if(!fx)
34 !
200
    return false;
×
201

202
#if defined(__linux__)
203
  static const thread_local bool is_wayland = qGuiApp->platformName() == "wayland";
34 !
204
  if(is_wayland)
34 !
205
    return false;
×
206
#endif
207

208
  return bool(fx->fx->flags & VstAEffectFlags::effFlagsHasEditor);
34 ✔
209
}
34 ✔
210

211
void Model::removeControl(int fxNum)
×
212
{
213
  auto it = controls.find(fxNum);
×
214
  SCORE_ASSERT(it != controls.end());
×
215
  auto ctrl = it->second;
×
216
  controls.erase(it);
×
217
  for(auto it = m_inlets.begin(); it != m_inlets.end(); ++it)
×
218
  {
219
    if(*it == ctrl)
×
220
    {
221
      m_inlets.erase(it);
×
222
      break;
×
223
    }
224
  }
×
225
  controlRemoved(*ctrl);
×
226
  delete ctrl;
×
227
}
×
228

229
void Model::removeControl(const Id<Process::Port>& id)
×
230
{
231
  auto it = ossia::find_if(m_inlets, [&](const auto& inl) { return inl->id() == id; });
×
232

233
  SCORE_ASSERT(it != m_inlets.end());
×
234
  auto ctrl = safe_cast<ControlInlet*>(*it);
×
235

236
  controls.erase(ctrl->fxNum);
×
237
  m_inlets.erase(it);
×
238

239
  controlRemoved(*ctrl);
×
240
  delete ctrl;
×
241
}
×
242

243
ControlInlet* Model::getControl(const Id<Process::Port>& p) const
1 ✔
244
{
245
  for(auto e : m_inlets)
3 !
246
    if(e->id() == p)
3 ✔
247
      return static_cast<ControlInlet*>(e);
1 ✔
248
  return nullptr;
×
249
}
1 ✔
250

251
QString Model::effect() const noexcept
98 ✔
252
{
253
  return QString::number(this->m_effectId);
98 !
254
}
255

256
void Model::init()
195 ✔
257
{
258
  //  connect(this, &Model::addControl, this, &Model::on_addControl);
259

260
  connect(this, &Model::resetExecution, this, [this] {
500 ✔
261
    for(auto [index, ctl] : this->controls)
818 ✔
262
    {
263
      fx->setParameter(index, ctl->value());
513 ✔
264
    }
265
  });
305 ✔
266
}
195 ✔
267

268
void Model::setControlName(int fxnum, ControlInlet* ctrl)
190 ✔
269
{
270
  auto name = getString(effGetParamName, fxnum);
190 ✔
271
  auto label = getString(effGetParamLabel, fxnum);
190 !
272
  // auto display = get_string(effGetParamDisplay, i);
273

274
  // Get the name
275
  QString str = name;
190 ✔
276
  if(!label.isEmpty())
190 ✔
277
    str += "(" + label + ")";
24 !
278

279
  ctrl->setName(name);
190 !
280
}
190 ✔
281

282
void Model::on_addControl(int i, float v)
190 ✔
283
{
284
  if(controls.find(i) != controls.end())
190 !
285
  {
286
    return;
×
287
  }
288

289
  SCORE_ASSERT(controls.find(i) == controls.end());
190 !
290
  auto ctrl = new ControlInlet{Id<Process::Port>(getStrongId(inlets()).val()), this};
190 !
291
  ctrl->displayHandledExplicitly = true;
190 ✔
292
  ctrl->fxNum = i;
190 ✔
293
  ctrl->setValue(v);
190 ✔
294

295
  // Metadata
296
  setControlName(i, ctrl);
190 ✔
297

298
  on_addControl_impl(ctrl);
190 ✔
299
}
190 ✔
300

301
void Model::on_addControl_impl(ControlInlet* ctrl)
190 ✔
302
{
303
  connect(
190 ✔
304
      ctrl, &ControlInlet::valueChanged, this,
190 ✔
305
      [this, i = ctrl->fxNum](const ossia::value& newval) {
272 ✔
306
    on_controlChangedFromScore(i, ossia::convert<float>(newval));
82 ✔
307
  });
82 ✔
308

309
  {
310
    /*
311
    VstParameterProperties props;
312
    auto res = dispatch(effGetParameterProperties, i, 0, &props);
313
    if(res == 1)
314
    {
315
      // apparently there's exactly 0 plug-ins supporting this
316
      qDebug() << props.label << props.minInteger << props.maxInteger <<
317
    props.smallStepFloat << props.stepFloat;
318
    }
319
    */
320
  }
321
  m_inlets.push_back(ctrl);
190 ✔
322
  SCORE_ASSERT(controls.find(ctrl->fxNum) == controls.end());
190 !
323
  controls.insert({ctrl->fxNum, ctrl});
190 ✔
324
  SCORE_ASSERT(controls.find(ctrl->fxNum) != controls.end());
190 !
325
  controlAdded(ctrl->id());
190 ✔
326
  // FIXME inletsChanged
327
}
190 ✔
328

329
void Model::on_controlChangedFromScore(int i, float newval)
92 ✔
330
{
331
  if(m_updatingFromPlugin)
92 ✔
332
    return;
13 ✔
333
  if(std::abs(newval - fx->getParameter(i)) > 0.0001)
79 ✔
334
    fx->setParameter(i, newval);
32 ✔
335
}
92 ✔
336

337
void Model::reloadControls()
×
338
{
339
  if(!fx)
×
340
    return;
×
341

342
  for(auto ctrl : controls)
×
343
  {
344
    setControlName(ctrl.first, ctrl.second);
×
345
    const float v = fx->getParameter(ctrl.first);
×
346
    controlReadFromPlugin(ctrl.first, v);
×
347
    ctrl.second->setValue(v);
×
348
  }
349
}
×
350

351
void HostState::parameterChanged(int32_t index) noexcept
19 ✔
352
{
353
  auto* c = changedParams.load(std::memory_order_acquire);
19 ✔
354
  if(c && index >= 0 && index < c->count)
19 !
355
  {
356
    c->flags[index].store(true, std::memory_order_release);
18 !
357
  }
18 ✔
358
  else
359
  {
360
    if(index >= 0)
1 !
361
      otherParam.store(index, std::memory_order_relaxed);
1 ✔
362
    otherParamChanged.store(true, std::memory_order_release);
1 ✔
363
  }
364
  paramsChanged.store(true, std::memory_order_release);
19 ✔
365
}
19 ✔
366

367
bool HostState::trackParameters(int32_t count)
204 ✔
368
{
369
  auto* old = changedParams.load(std::memory_order_relaxed);
204 ✔
370
  if(count <= 0 || (old && old->count >= count))
204 !
371
    return false;
13 ✔
372

373
  auto block = std::make_unique<changed_params>();
191 ✔
374
  block->count = count;
191 ✔
375
  block->flags = std::make_unique<std::atomic_bool[]>(count);
191 !
376
  if(old)
191 ✔
377
    for(int32_t i = 0; i < old->count; i++)
2 ✔
378
      block->flags[i].store(
2 !
379
          old->flags[i].load(std::memory_order_acquire), std::memory_order_relaxed);
2 !
380
  changedParams.store(block.get(), std::memory_order_release);
191 ✔
381
  changedParamBlocks.push_back(std::move(block));
191 !
382
  return true;
191 ✔
383
}
204 ✔
384

385
void Model::updateControlsChangedByPlugin()
3,267 ✔
386
{
387
  if(!fx || !fx->fx)
3,267 !
388
    return;
×
389
  auto& host = *fx->host;
3,267 ✔
390
  if(!host.paramsChanged.exchange(false, std::memory_order_acquire))
3,267 ✔
391
    return;
3,253 ✔
392

393
  // A plug-in may have more parameters than when it was opened: a flag raised
394
  // while they are made may be lost, so each control is read again
395
  const int32_t count = fx->fx->numParams;
14 ✔
396
  bool all = host.trackParameters(count);
14 ✔
397

398
  // An index the flags did not cover: each control is read again, and the
399
  // last such index is a parameter changed
400
  int32_t other = -1;
14 ✔
401
  if(host.otherParamChanged.exchange(false, std::memory_order_acquire))
14 ✔
402
  {
403
    all = true;
1 ✔
404
    other = host.otherParam.exchange(-1, std::memory_order_relaxed);
1 ✔
405
  }
1 ✔
406
  auto* raised = host.changedParams.load(std::memory_order_relaxed);
14 ✔
407
  for(int32_t i = 0; i < count; i++)
30 ✔
408
  {
409
    const bool changed
16 ✔
410
        = i == other
16 ✔
411
          || (raised && i < raised->count
31 !
412
              && raised->flags[i].exchange(false, std::memory_order_acquire));
15 !
413
    if(!changed && !all)
16 ✔
414
      continue;
1 ✔
415

416
    const float v = fx->getParameter(i);
15 ✔
417
    if(auto ctrl_it = controls.find(i); ctrl_it != controls.end())
15 ✔
418
    {
419
      controlReadFromPlugin(i, v);
14 ✔
420
      m_updatingFromPlugin = true;
14 ✔
421
      ctrl_it->second->setValue(v);
14 ✔
422
      m_updatingFromPlugin = false;
14 ✔
423
    }
14 ✔
424
    else if(changed && (flags() & Process::CreateControls))
1 !
425
    {
426
      auto& ctx = score::IDocument::documentContext(*this);
1 ✔
427
      CommandDispatcher<>{ctx.commandStack}.submit<CreateControl>(*this, i, v);
1 ✔
428
    }
1 ✔
429
  }
15 ✔
430
}
3,267 ✔
431

432
void Model::reloadPrograms()
190 ✔
433
{
434
  m_programs.clear();
190 ✔
435
  for(int i = 0; i < fx->fx->numPrograms; i++)
1,325 ✔
436
  {
437
    char effName[128] = {0};
1,135 ✔
438
    fx->dispatch(effGetProgramNameIndexed, i, 0, effName);
1,135 ✔
439
    // Some name their programs only once a bank is loaded (Dexed): still
440
    // programs to choose from
441
    if(effName[0] != '\0')
1,135 !
442
      m_programs.emplace_back(effName, i);
1,135 ✔
443
    // A lone unnamed program is a plug-in's only state, not a preset: JUCE
444
    // gives one to every plug-in without presets. A named one is kept.
445
    else if(fx->fx->numPrograms > 1)
×
446
      m_programs.emplace_back("Program " + std::to_string(i + 1), i);
×
447
  }
1,135 ✔
448
}
190 ✔
449

450
intptr_t vst_host_callback(
336 ✔
451
    AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
452
{
453
  intptr_t result = 0;
336 ✔
454

455
  // Never the process itself: the plug-in may call from any thread, the
456
  // process may be destroyed meanwhile on the main thread
457
  auto* host = effect ? reinterpret_cast<HostState*>(effect->resvd1) : nullptr;
336 ✔
458
  if(host)
336 ✔
459
  {
460
    switch(opcode)
289 !
461
    {
462
      case audioMasterGetTime: {
463
        result = reinterpret_cast<intptr_t>(&host->info);
2 ✔
464
        break;
2 ✔
465
      }
466
      case audioMasterSizeWindow: {
467
        ossia::qt::run_async(
×
468
            QCoreApplication::instance(),
×
469
            [w = host->weak_from_this(), index, value] {
×
470
          if(auto h = w.lock())
×
471
            if(h->model && h->model->externalUI)
×
472
              static_cast<Window*>(h->model->externalUI)->resize(index, value);
×
473
        });
×
474
        result = 1;
×
475
        break;
×
476
      }
477

478
      case audioMasterNeedIdle: {
479
        effect->dispatcher(effect, effEditIdle, 0, 0, nullptr, 0);
×
480
        result = 1;
×
481
        break;
×
482
      }
483

484
      case audioMasterIdle: {
485
        host->needIdle.store(true, std::memory_order_release);
×
486
        result = 1;
×
487
        break;
×
488
      }
489

490
      case audioMasterCurrentId:
491
        result = effect->uniqueID;
×
492
        break;
×
493

494
      case audioMasterUpdateDisplay: {
495
        host->displayChanged.store(true, std::memory_order_release);
×
496
        break;
×
497
      }
498

499
      case audioMasterAutomate: {
500
        // Sent from the editor, but also from the audio thread. The value is
501
        // read back from the plug-in later, on the main thread: opt is not
502
        // always the normalized value, e.g. DPF plug-ins built with a host
503
        // callback that takes an int32_t in its place leave whatever the
504
        // float register holds, often the parameter in its own unit.
505
        host->parameterChanged(index);
19 ✔
506
        break;
19 ✔
507
      }
508

509
      case audioMasterProcessEvents: {
510
        // Dated in the block the node is processing: from any other thread,
511
        // or at any other time, the events have no date and are dropped
512
        if(host->processThread.load(std::memory_order_relaxed)
103 ✔
513
           == std::this_thread::get_id())
103 ✔
514
          if(auto node = host->processingNode)
20 !
515
            node->receiveEvents(static_cast<const VstEvents*>(ptr));
10 ✔
516
        break;
103 ✔
517
      }
518
    }
519
  }
289 ✔
520

521
  switch(opcode)
336 !
522
  {
523
    case audioMasterProcessEvents:
524
      result = 1;
103 ✔
525
      break;
103 ✔
526
    case audioMasterIOChanged:
527
      break;
×
528
    case audioMasterSizeWindow:
529
      result = 1;
×
530
      break;
×
531
    case audioMasterGetInputLatency: {
532
      static const auto& context = score::AppContext();
×
533
      static const auto& settings = context.settings<Audio::Settings::Model>();
×
534
      result = settings.getBufferSize() / double(settings.getRate());
×
535
      break;
×
536
    }
537
    case audioMasterGetOutputLatency: {
538
      static const auto& context = score::AppContext();
×
539
      static const auto& settings = context.settings<Audio::Settings::Model>();
×
540
      result = settings.getBufferSize() / double(settings.getRate());
×
541
      break;
×
542
    }
543
    case audioMasterVersion:
544
      result = kVstVersion;
47 ✔
545
      break;
47 ✔
546
    case audioMasterGetSampleRate: {
547
      static const auto& context = score::AppContext();
75 !
548
      static const auto& settings = context.settings<Audio::Settings::Model>();
75 !
549
      result = settings.getRate();
75 ✔
550
      break;
75 ✔
551
    }
552
    case audioMasterGetBlockSize: {
553
      static const auto& context = score::AppContext();
75 !
554
      static const auto& settings = context.settings<Audio::Settings::Model>();
75 !
555
      result = settings.getBufferSize();
75 ✔
556
      break;
75 ✔
557
    }
558
    case audioMasterGetCurrentProcessLevel: {
559
      static const auto& context = score::GUIAppContext();
×
560
      static const auto& plug = context.applicationPlugin<vst::ApplicationPlugin>();
×
561
      auto this_t = std::this_thread::get_id();
×
562
      if(this_t == plug.mainThreadId())
×
563
      {
564
        result = kVstProcessLevelUser;
×
565
      }
×
566
      else
567
      {
568
        result = kVstProcessLevelRealtime;
×
569
      }
570

571
      break;
×
572
    }
573
    case audioMasterGetAutomationState:
574
      result = kVstAutomationUnsupported;
×
575
      break;
×
576
    case audioMasterGetLanguage:
577
      result = kVstLangEnglish;
×
578
      break;
×
579
    case audioMasterGetVendorVersion:
580
      result = 1;
×
581
      break;
×
582
    case audioMasterGetVendorString:
583
      std::copy_n("ossia", 6, static_cast<char*>(ptr));
×
584
      result = 1;
×
585
      break;
×
586
    case audioMasterGetProductString:
587
      std::copy_n("score", 6, static_cast<char*>(ptr));
×
588
      result = 1;
×
589
      break;
×
590
    case audioMasterBeginEdit:
591
      break;
×
592
    case audioMasterEndEdit:
593
      // TODO use this to trigger undo-redo commands.
594
      break;
×
595
    case audioMasterOpenFileSelector:
596
      break;
×
597
    case audioMasterCloseFileSelector:
598
      break;
×
599
    case audioMasterCanDo: {
600
      static const ossia::flat_set<std::string_view> supported{
×
601
          HostCanDos::canDoSendVstEvents,
602
          HostCanDos::canDoSendVstMidiEvent,
603
          HostCanDos::canDoSendVstTimeInfo,
604
          HostCanDos::canDoSendVstMidiEventFlagIsRealtime,
605
          HostCanDos::canDoSizeWindow,
606
          HostCanDos::canDoHasCockosViewAsConfig};
607
      if(supported.find(static_cast<const char*>(ptr)) != supported.end())
×
608
        result = 1;
×
609
      break;
×
610
    }
611
  }
612
  return result;
336 ✔
613
}
×
614

615
void Model::closePlugin()
195 ✔
616
{
617
  if(fx)
195 !
618
  {
619
    fx->host->model = nullptr;
×
620
    if(externalUI)
×
621
    {
622
      auto w = reinterpret_cast<Window*>(externalUI);
×
623
      delete w;
×
624
    }
×
625

626
    fx.reset();
×
627
  }
×
628
  auto old_inlets = score::clearAndDeleteLater(m_inlets);
195 ✔
629
  auto old_outlets = score::clearAndDeleteLater(m_outlets);
195 ✔
630
  metadata().setLabel("Dead VST");
195 !
631
}
195 ✔
632

633
AEffect* getPluginInstance(const QString& name)
5 ✔
634
{
635
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
5 ✔
636

637
  auto info_it = ossia::find_if(
5 ✔
638
      app.vst_infos, [&](const vst::VSTInfo& i) { return i.prettyName == name; });
5 ✔
639
  if(info_it != app.vst_infos.end())
5 !
640
  {
641
    auto it = app.vst_modules.find(info_it->uniqueID);
×
642
    if(it != app.vst_modules.end())
×
643
    {
644
      if(!it->second)
×
645
        it->second = new vst::Module{info_it->path.toStdString()};
×
646

647
      if(auto m = it->second->getMain())
×
648
      {
649
        return m(vst_host_callback);
×
650
      }
651
    }
×
652
    else
653
    {
654
      auto plugin = new vst::Module{info_it->path.toStdString()};
×
655

656
      if(auto m = plugin->getMain())
×
657
      {
658
        if(auto p = (AEffect*)m(vst::vst_host_callback))
×
659
        {
660
          app.vst_modules.insert({p->uniqueID, plugin});
×
661
          return p;
×
662
        }
663
      }
×
664

665
      delete plugin;
×
666
    }
667
  }
×
668

669
  return nullptr;
5 ✔
670
}
5 ✔
671
AEffect* getPluginInstance(int32_t id)
195 ✔
672
{
673
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
195 ✔
674

675
  auto info_it = ossia::find_if(
195 ✔
676
      app.vst_infos, [&](const vst::VSTInfo& i) { return i.uniqueID == id; });
453 ✔
677
  if(info_it != app.vst_infos.end())
195 ✔
678
  {
679
    auto it = app.vst_modules.find(info_it->uniqueID);
190 ✔
680
    if(it != app.vst_modules.end())
190 !
681
    {
682
      if(!it->second)
190 ✔
683
        it->second = new vst::Module{info_it->path.toStdString()};
95 !
684
      if(auto m = it->second->getMain())
190 !
685
      {
686
        if(auto plug = m(vst_host_callback))
190 !
687
        {
688
          it->second->use_count++;
190 ✔
689
          return plug;
190 ✔
690
        }
691
      }
×
692
      if(it->second && it->second->use_count == 0)
×
693
      {
694
        delete it->second;
×
695
        it->second = nullptr;
×
696
      }
×
697
    }
×
698
    else
699
    {
700
      auto plugin = new vst::Module{info_it->path.toStdString()};
×
701

702
      if(auto m = plugin->getMain())
×
703
      {
704
        if(auto p = (AEffect*)m(vst::vst_host_callback))
×
705
        {
706
          app.vst_modules.insert({p->uniqueID, plugin});
×
707
          return p;
×
708
        }
709
      }
×
710

711
      delete plugin;
×
712
    }
713
  }
×
714

715
  return nullptr;
5 ✔
716
}
195 ✔
717

718
void releasePluginInstance(int uid)
190 ✔
719
{
720
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
190 ✔
721

722
  auto it = app.vst_modules.find(uid);
190 ✔
723
  if(it != app.vst_modules.end())
190 !
724
  {
725
    if(it->second)
190 !
726
    {
727
      it->second->use_count--;
190 ✔
728
      if(it->second->use_count == 0)
190 ✔
729
      {
730
//        delete it->second;
731
        it->second = nullptr;
95 ✔
732
      }
95 ✔
733
    }
190 ✔
734
  }
190 ✔
735
}
190 ✔
736

737
void Model::initFx()
195 ✔
738
{
739
  fx = std::make_shared<AEffectWrapper>(getPluginInstance(m_effectId));
195 ✔
740
  if(!fx->fx)
195 ✔
741
  {
742
    fx = std::make_shared<AEffectWrapper>(getPluginInstance(metadata().getLabel()));
5 ✔
743
    if(!fx->fx)
5 !
744
    {
745
      qDebug() << "plugin was not created";
5 !
746
      fx.reset();
5 ✔
747
      return;
5 ✔
748
    }
749
  }
×
750

751
  // Before the plug-in can call the host with this process
752
  fx->host->trackParameters(fx->fx->numParams);
190 ✔
753
  fx->host->model = this;
190 ✔
754

755
  auto& ctx = score::GUIAppContext();
190 ✔
756
  auto& media = ctx.settings<Audio::Settings::Model>();
190 ✔
757
  const int blockSize = media.getBufferSize();
190 ✔
758
  fx->info.sampleRate = media.getRate();
190 ✔
759

760
  // JUCE hosts do it before effOpen
761
  dispatch(effSetSampleRate, 0, media.getRate(), nullptr, media.getRate());
190 ✔
762
  dispatch(effSetBlockSize, 0, blockSize, nullptr, blockSize);
190 ✔
763

764
  dispatch(effOpen);
190 ✔
765

766
  // Others like Reaper do it after - this is also done in node.hpp
767
  dispatch(effSetSampleRate, 0, media.getRate(), nullptr, media.getRate());
190 ✔
768
  dispatch(effSetBlockSize, 0, blockSize, nullptr, blockSize);
190 ✔
769

770
  auto& app = ctx.applicationPlugin<vst::ApplicationPlugin>();
190 ✔
771
  auto it = ossia::find_if(
190 ✔
772
      app.vst_infos, [this](auto& i) { return i.uniqueID == fx->fx->uniqueID; });
448 ✔
773

774
  if(it != app.vst_infos.end())
190 !
775
  {
776
    metadata().setName(it->prettyName);
190 ✔
777
    if(!it->displayName.isEmpty())
190 ✔
778
      metadata().setLabel(it->displayName);
10 ✔
779
  }
190 ✔
780
  else
781
  {
782
    qDebug() << "warning! " << fx->fx->uniqueID
×
783
             << "not found but plug-in found by name.";
×
784
  }
785

786
  reloadPrograms();
190 ✔
787

788
  // Some plug-ins only play once a program is selected. The one selected is
789
  // the one the plug-in says it is on, or its first when it names none: a
790
  // plug-in that opens on another than its first (Permut8, TAL-Reverb-2)
791
  // stays there.
792
  if(fx->fx->numPrograms > 0)
190 ✔
793
  {
794
    const auto current = dispatch(effGetProgram);
183 ✔
795
    selectProgram(current >= 0 && current < fx->fx->numPrograms ? int(current) : 0);
183 !
796
  }
183 ✔
797
}
195 ✔
798

799
void Model::selectProgram(int index)
279 ✔
800
{
801
  dispatch(effBeginSetProgram);
279 ✔
802
  dispatch(effSetProgram, 0, index);
279 ✔
803
  dispatch(effEndSetProgram);
279 ✔
804
}
279 ✔
805

806
void Model::create()
129 ✔
807
{
808
  SCORE_ASSERT(!fx);
129 !
809

810
  initFx();
129 ✔
811
  if(!fx)
129 !
812
    return;
×
813

814
  int inlet_i = 0;
129 ✔
815

816
  m_inlets.push_back(
258 !
817
      new Process::AudioInlet("Audio In", Id<Process::Port>{inlet_i++}, this));
129 !
818
  // An instrument may not say it is one (JuceOPL): what decides is whether
819
  // it takes MIDI
820
  const auto canDo = [this](const char* what) {
425 ✔
821
    return dispatch(effCanDo, 0, 0, const_cast<char*>(what)) > 0;
296 ✔
822
  };
823
  if((fx->fx->flags & effFlagsIsSynth) || canDo(HostCanDos::canDoReceiveVstMidiEvent)
129 ✔
824
     || canDo(HostCanDos::canDoReceiveVstEvents))
117 !
825
  {
826
    m_inlets.push_back(
220 !
827
        new Process::MidiInlet("MIDI In", Id<Process::Port>{inlet_i++}, this));
110 !
828
  }
110 ✔
829

830
  if(fx->fx->numParams < VST_DEFAULT_PARAM_NUMBER_CUTOFF
129 ✔
831
     || !(fx->fx->flags & VstAEffectFlags::effFlagsHasEditor))
129 !
832
  {
833
    for(int i = 0; i < fx->fx->numParams; i++)
318 ✔
834
    {
835
      on_addControl(i, fx->getParameter(i));
189 ✔
836
    }
189 ✔
837
  }
129 ✔
838

839
  auto out = new Process::AudioOutlet("Audio Out", Id<Process::Port>{}, this);
129 !
840
  out->setPropagate(true);
129 ✔
841
  m_outlets.push_back(out);
129 ✔
842

843
  if(canDo(HostCanDos::canDoSendVstMidiEvent) || canDo(HostCanDos::canDoSendVstEvents))
129 !
844
    m_outlets.push_back(new Process::MidiOutlet("MIDI Out", Id<Process::Port>{1}, this));
98 !
845
}
129 ✔
846

847
void Model::load()
66 ✔
848
{
849
  SCORE_ASSERT(!fx);
66 !
850
  initFx();
66 ✔
851
  if(!fx)
66 ✔
852
  {
853
    qDebug() << "not loading (no fx)";
5 !
854
    return;
5 ✔
855
  }
856

857
  for(std::size_t i = VST_FIRST_CONTROL_INDEX(takesMidi()); i < m_inlets.size(); i++)
178 ✔
858
  {
859
    auto inlet = safe_cast<ControlInlet*>(m_inlets[i]);
117 ✔
860
    int ctrl = inlet->fxNum;
117 ✔
861

862
    connect(
117 ✔
863
        inlet, &ControlInlet::valueChanged, this,
117 ✔
864
        [this, ctrl](const ossia::value& newval) {
127 ✔
865
      on_controlChangedFromScore(ctrl, ossia::convert<float>(newval));
10 ✔
866
    });
10 ✔
867
    controls.insert({ctrl, inlet});
117 ✔
868
  }
117 ✔
869
}
66 ✔
870

871
#define SCORE_DATASTREAM_IDENTIFY_VST_CHUNK int32_t(0xABABABAB)
872
#define SCORE_DATASTREAM_IDENTIFY_VST_PARAMS int32_t(0x10101010)
873
// The plug-in could not be loaded: the state it was saved with, kept as is
874
#define SCORE_DATASTREAM_IDENTIFY_VST_BACKUP int32_t(0x0BAC0BAC)
875
// Before one of the above: the program the plug-in is on. A state saved
876
// without it leaves the plug-in on the program it was set up on.
877
#define SCORE_DATASTREAM_IDENTIFY_VST_PROGRAM int32_t(0x50524F47)
878

879
//! The program the plug-in is on, or the one it was saved on when it could
880
//! not be loaded; -1 for none
881
static int32_t savedProgram(const vst::Model& eff)
109 ✔
882
{
883
  if(!eff.fx)
109 ✔
884
    return eff.m_backup_program;
4 ✔
885
  if(eff.fx->fx->numPrograms <= 0)
105 !
886
    return -1;
×
887
  const auto p = eff.fx->dispatch(effGetProgram, 0, 0, nullptr, 0.f);
105 ✔
888
  return p >= 0 && p < eff.fx->fx->numPrograms ? int32_t(p) : -1;
105 !
889
}
109 ✔
890

891
//! Puts the plug-in back on the program it was saved on, before its chunk or
892
//! its parameters are set, as Carla, Tracktion, LMMS and Ardour do: a program
893
//! selected after them would replace them. Kept as is when it could not be
894
//! loaded.
895
static void restoreProgram(vst::Model& eff, int32_t program)
78 ✔
896
{
897
  if(!eff.fx)
78 ✔
898
    eff.m_backup_program = program;
4 ✔
899
  else if(program >= 0 && program < eff.fx->fx->numPrograms)
74 !
900
    eff.selectProgram(program);
74 ✔
901
}
78 ✔
902

903
static void saveVstChunkToDatastream(DataStreamInput& stream, const vst::Model& eff)
83 ✔
904
{
905
  if(const auto program = savedProgram(eff); program >= 0)
83 !
906
    stream << SCORE_DATASTREAM_IDENTIFY_VST_PROGRAM << program;
83 ✔
907

908
  if(eff.fx)
83 ✔
909
  {
910
    if(eff.fx->fx->flags & effFlagsProgramChunks)
81 ✔
911
    {
912
      stream << SCORE_DATASTREAM_IDENTIFY_VST_CHUNK;
15 ✔
913
      void* ptr{};
15 ✔
914
      auto res = eff.fx->dispatch(effGetChunk, 0, 0, &ptr, 0.f);
15 ✔
915
      std::string encoded;
15 ✔
916
      if(ptr && res > 0)
15 !
917
      {
918
        encoded.assign((const char*)ptr, res);
15 !
919
      }
15 ✔
920
      stream << encoded;
15 !
921

922
      // FIXME the memory should be freed at the next effSuspend / effResume call.
923
    }
15 ✔
924
    else
925
    {
926
      stream << SCORE_DATASTREAM_IDENTIFY_VST_PARAMS;
66 ✔
927
      ossia::float_vector arr(eff.fx->fx->numParams);
66 ✔
928
      for(int i = 0; i < eff.fx->fx->numParams; i++)
204 ✔
929
        arr[i] = eff.fx->getParameter(i);
138 ✔
930
      stream << arr;
66 !
931
    }
66 ✔
932
  }
81 ✔
933
  else
934
  {
935
    // Always write a kind: the loader reads one unconditionally, and without
936
    // it consumed the delimiter (undo of removing a plug-in that failed to
937
    // load asserted in checkDelimiter).
938
    stream << SCORE_DATASTREAM_IDENTIFY_VST_BACKUP << eff.m_backup_chunk
2 ✔
939
           << eff.m_backup_float_data;
2 ✔
940
  }
941
}
83 ✔
942

943
static void loadVstChunkFromDatastream(DataStreamOutput& stream, vst::Model& eff)
69 ✔
944
{
945
  int32_t kind = 0;
69 ✔
946
  stream >> kind;
69 ✔
947

948
  if(kind == SCORE_DATASTREAM_IDENTIFY_VST_PROGRAM)
69 ✔
949
  {
950
    int32_t program = -1;
56 ✔
951
    stream >> program >> kind;
56 ✔
952
    restoreProgram(eff, program);
56 ✔
953
  }
56 ✔
954

955
  // First set the values in the VST
956
  if(kind == SCORE_DATASTREAM_IDENTIFY_VST_CHUNK)
69 ✔
957
  {
958
    std::string chunk;
8 ✔
959
    stream >> chunk;
8 !
960
    if(!chunk.empty())
8 !
961
    {
962
      if(eff.fx)
8 ✔
963
      {
964
        if(eff.fx->fx->flags & effFlagsProgramChunks)
7 !
965
        {
966
          eff.fx->dispatch(effSetChunk, 0, chunk.size(), chunk.data(), 0.f);
7 ✔
967
        }
7 ✔
968
      }
7 ✔
969
      else
970
      {
971
        // Same encoding as the JSON "Data" the backup is written back to
972
        eff.m_backup_chunk = websocketpp::base64_encode(
1 !
973
            (const unsigned char*)chunk.data(), chunk.size());
1 ✔
974
      }
975
    }
8 ✔
976
  }
8 ✔
977
  else if(kind == SCORE_DATASTREAM_IDENTIFY_VST_BACKUP)
61 ✔
978
  {
979
    std::string chunk;
2 ✔
980
    ossia::float_vector params;
2 ✔
981
    stream >> chunk >> params;
2 !
982
    if(eff.fx)
2 !
983
    {
984
      if(!chunk.empty() && (eff.fx->fx->flags & effFlagsProgramChunks))
2 !
985
      {
986
        auto data = websocketpp::base64_decode(chunk);
1 !
987
        eff.fx->dispatch(effSetChunk, 0, data.size(), data.data(), 0.f);
1 ✔
988
      }
1 ✔
989
      for(std::size_t i = 0; i < params.size(); i++)
3 ✔
990
        eff.fx->setParameter(i, params[i]);
1 ✔
991
    }
2 ✔
992
    else
993
    {
994
      eff.m_backup_chunk = std::move(chunk);
×
995
      eff.m_backup_float_data = std::move(params);
×
996
    }
997
  }
2 ✔
998
  else if(kind == SCORE_DATASTREAM_IDENTIFY_VST_PARAMS)
59 !
999
  {
1000
    ossia::float_vector params;
59 ✔
1001
    stream >> params;
59 !
1002

1003
    if(eff.fx)
59 ✔
1004
    {
1005
      for(std::size_t i = 0; i < params.size(); i++)
175 ✔
1006
      {
1007
        eff.fx->setParameter(i, params[i]);
117 ✔
1008
      }
117 ✔
1009
    }
58 ✔
1010
    else
1011
    {
1012
      eff.m_backup_float_data = std::move(params);
1 ✔
1013
    }
1014
  }
59 ✔
1015

1016
  // Then reload our UI controls at the correct values.
1017
  if(eff.fx && eff.fx->fx)
69 !
1018
  {
1019
    for(std::size_t i = VST_FIRST_CONTROL_INDEX(eff.takesMidi()); i < eff.inlets().size();
193 ✔
1020
        i++)
126 ✔
1021
    {
1022
      auto inlet = safe_cast<vst::ControlInlet*>(eff.inlets()[i]);
126 ✔
1023
      inlet->setValue(eff.fx->getParameter(inlet->fxNum));
126 ✔
1024
    }
126 ✔
1025
  }
67 ✔
1026
}
69 ✔
1027

1028
void Model::loadPreset(const Process::Preset& preset)
43 ✔
1029
{
1030
  const rapidjson::Document doc = readJson(preset.data);
43 ✔
1031
  if(!doc.IsObject())
43 !
1032
    return;
×
1033
  auto obj = doc.GetObject();
43 !
1034

1035
  if(auto it = obj.FindMember("Chunk"); it != obj.MemberEnd())
43 !
1036
  {
1037
    QByteArray data = QByteArray::fromBase64(JsonValue{it->value}.toByteArray());
34 !
1038
    QDataStream s{data};
34 !
1039
    DataStreamOutput out{s};
34 ✔
1040
    loadVstChunkFromDatastream(out, *this);
34 !
1041
  }
34 ✔
1042
  else if(auto it = obj.FindMember("ProgramIndex"); it != obj.MemberEnd())
9 !
1043
  {
1044
    auto idx = JsonValue{it->value}.toInt();
9 !
1045
    if(this->fx)
9 !
1046
      selectProgram(idx);
9 !
1047
  }
9 ✔
1048
}
43 ✔
1049

1050
Process::Preset Model::savePreset() const noexcept
30 ✔
1051
{
1052
  Process::Preset p;
30 ✔
1053
  p.name = this->metadata().getName();
30 ✔
1054
  p.key.key = this->concreteKey();
30 ✔
1055
  p.key.effect = this->effect();
30 ✔
1056

1057
  QByteArray data;
30 ✔
1058
  {
1059
    QDataStream s{&data, QIODevice::WriteOnly};
30 !
1060
    DataStreamInput in{s};
30 ✔
1061
    saveVstChunkToDatastream(in, *this);
30 !
1062
  }
30 ✔
1063

1064
  JSONReader r;
30 !
1065
  r.stream.StartObject();
30 !
1066
  r.obj["Chunk"] = data.toBase64();
30 !
1067
  r.stream.EndObject();
30 !
1068
  p.data = r.toByteArray();
30 !
1069
  return p;
30 ✔
1070
}
30 ✔
1071

1072
std::vector<Process::Preset> Model::builtinPresets() const noexcept
7 ✔
1073
{
1074
  if(!fx)
7 !
1075
    return {};
×
1076

1077
  std::vector<Process::Preset> presets;
7 ✔
1078
  for(auto& prog : m_programs)
63 ✔
1079
  {
1080
    Process::Preset p;
56 ✔
1081
    p.key.key = this->static_concreteKey();
56 ✔
1082
    p.key.effect = QString::number(m_effectId);
56 !
1083
    p.name = QString::fromStdString(prog.first);
56 !
1084
    p.data = QStringLiteral(R"({ "ProgramIndex": %1 } )").arg(prog.second).toLatin1();
56 !
1085
    presets.push_back(p);
56 !
1086
  }
56 ✔
1087

1088
  return presets;
7 ✔
1089
}
14 ✔
1090

1091
AEffectWrapper::~AEffectWrapper()
208 ✔
1092
{
1093
  if(fx)
208 ✔
1094
  {
1095
    // What the plug-in calls the host with lives until it is closed
1096
    ossia::qt::run_async(QCoreApplication::instance(), [fx = fx, host = host] {
380 !
1097
      int uid = fx->uniqueID;
190 ✔
1098
      fx->dispatcher(fx, effClose, 0, 0, nullptr, 0.f);
190 ✔
1099

1100
      releasePluginInstance(uid);
190 ✔
1101
    });
190 ✔
1102
  }
190 ✔
1103
}
208 ✔
1104

1105
Model::vst_context_handler::vst_context_handler(Model& self)
195 ✔
1106
    : self{self}
195 ✔
1107
{
1108
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
195 ✔
1109
  app.registerRunningVST(&self);
195 ✔
1110
}
195 ✔
1111

1112
Model::vst_context_handler::~vst_context_handler()
195 ✔
1113
{
1114
  auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
195 !
1115
  app.unregisterRunningVST(&self);
195 !
1116
  self.closePlugin();
195 !
1117
}
195 ✔
1118

1119
}
1120

1121
template <>
1122
void DataStreamReader::read(const vst::Model& eff)
53 ✔
1123
{
1124
  readPorts(*this, eff.m_inlets, eff.m_outlets);
53 ✔
1125
  m_stream << eff.m_effectId;
53 ✔
1126

1127
  saveVstChunkToDatastream(m_stream, eff);
53 ✔
1128

1129
  insertDelimiter();
53 ✔
1130
}
53 ✔
1131

1132
template <>
1133
void DataStreamWriter::write(vst::Model& eff)
35 ✔
1134
{
1135
  writePorts(
35 ✔
1136
      *this, components.interfaces<Process::PortFactoryList>(), eff.m_inlets,
35 ✔
1137
      eff.m_outlets, &eff);
35 ✔
1138

1139
  m_stream >> eff.m_effectId;
35 ✔
1140

1141
  eff.load();
35 ✔
1142

1143
  loadVstChunkFromDatastream(m_stream, eff);
35 ✔
1144

1145
  checkDelimiter();
35 ✔
1146
}
35 ✔
1147

1148
template <>
1149
void JSONReader::read(const vst::Model& eff)
26 ✔
1150
{
1151
  readPorts(*this, eff.m_inlets, eff.m_outlets);
26 ✔
1152
  obj["EffectId"] = eff.m_effectId;
26 ✔
1153
  if(const auto program = savedProgram(eff); program >= 0)
26 !
1154
    obj["Program"] = program;
26 ✔
1155

1156
  if(eff.fx)
26 ✔
1157
  {
1158
    if(eff.fx->fx->flags & effFlagsProgramChunks)
24 ✔
1159
    {
1160
      void* ptr{};
5 ✔
1161
      auto res = eff.fx->dispatch(effGetChunk, 0, 0, &ptr, 0.f);
5 ✔
1162
      if(ptr && res > 0)
5 !
1163
      {
1164
        obj["Data"] = websocketpp::base64_encode((const unsigned char*)ptr, res);
5 ✔
1165
      }
5 ✔
1166
    }
5 ✔
1167
    else
1168
    {
1169
      stream.Key("Params");
19 ✔
1170
      stream.StartArray();
19 ✔
1171
      for(int i = 0; i < eff.fx->fx->numParams; i++)
60 ✔
1172
        stream.Double(eff.fx->getParameter(i));
41 ✔
1173
      stream.EndArray();
19 ✔
1174
    }
1175
  }
24 ✔
1176
  else
1177
  {
1178
    // VST could not be loaded, keep its internal data that was previously saved
1179
    // TODO do the same with the DataStream one
1180
    if(!eff.m_backup_chunk.empty())
2 ✔
1181
    {
1182
      obj["Data"] = eff.m_backup_chunk;
1 ✔
1183
    }
1 ✔
1184
    if(!eff.m_backup_float_data.empty())
2 ✔
1185
    {
1186
      stream.Key("Params");
1 ✔
1187
      stream.StartArray();
1 ✔
1188
      for(float param : eff.m_backup_float_data)
2 ✔
1189
        stream.Double(param);
1 ✔
1190
      stream.EndArray();
1 ✔
1191
    }
1 ✔
1192
  }
1193
}
26 ✔
1194

1195
template <>
1196
void JSONWriter::write(vst::Model& eff)
31 ✔
1197
{
1198
  auto it = base.FindMember("EffectId");
31 ✔
1199
  if(it != base.MemberEnd())
31 !
1200
  {
1201
    eff.m_effectId = it->value.GetInt();
31 ✔
1202
  }
31 ✔
1203
  else
1204
  {
1205
    auto str = obj["Effect"].toString();
×
1206

1207
    auto& app = score::GUIAppContext().applicationPlugin<vst::ApplicationPlugin>();
×
1208
    auto it
1209
        = ossia::find_if(app.vst_infos, [&](const auto& i) { return i.path == str; });
×
1210
    if(it != app.vst_infos.end())
×
1211
    {
1212
      eff.m_effectId = it->uniqueID;
×
1213
    }
×
1214
  }
×
1215

1216
  writePorts(
31 ✔
1217
      *this, components.interfaces<Process::PortFactoryList>(), eff.m_inlets,
31 ✔
1218
      eff.m_outlets, &eff);
31 ✔
1219

1220
  eff.load();
31 ✔
1221

1222
  if(auto program_it = base.FindMember("Program"); program_it != base.MemberEnd())
31 ✔
1223
    restoreProgram(eff, program_it->value.GetInt());
22 ✔
1224

1225
  // Reload controls
1226
  auto data_it = base.FindMember("Data");
31 ✔
1227
  auto params_it = base.FindMember("Params");
31 ✔
1228
  if(eff.fx)
31 ✔
1229
  {
1230
    // Set the parameters in the VST
1231
    if(eff.fx->fx->flags & effFlagsProgramChunks)
28 ✔
1232
    {
1233
      if(data_it != base.MemberEnd())
5 !
1234
      {
1235
        auto b64 = websocketpp::base64_decode(JsonValue{data_it->value}.toStdString());
5 !
1236
        eff.fx->dispatch(effSetChunk, 0, b64.size(), b64.data(), 0.f);
5 ✔
1237
      }
5 ✔
1238
    }
5 ✔
1239
    else
1240
    {
1241
      if(params_it != base.MemberEnd())
23 !
1242
      {
1243
        const auto& arr = params_it->value.GetArray();
23 ✔
1244
        for(std::size_t i = 0; i < arr.Size(); i++)
73 !
1245
        {
1246
          eff.fx->setParameter(i, arr[i].GetDouble());
50 !
1247
        }
50 ✔
1248
      }
23 ✔
1249
    }
1250

1251
    // Reload the vst parameters in the score UI controls
1252
    for(std::size_t i = VST_FIRST_CONTROL_INDEX(eff.takesMidi()); i < eff.inlets().size();
83 ✔
1253
        i++)
55 ✔
1254
    {
1255
      auto inlet = safe_cast<vst::ControlInlet*>(eff.inlets()[i]);
55 ✔
1256
      inlet->setValue(eff.fx->getParameter(inlet->fxNum));
55 ✔
1257
    }
55 ✔
1258
  }
28 ✔
1259
  else
1260
  {
1261
    // Couldn't load the VST, keep the vst data so that we can resave it
1262
    // TODO do the same with the DataStream one
1263
    if(data_it != base.MemberEnd())
3 ✔
1264
    {
1265
      eff.m_backup_chunk = JsonValue{data_it->value}.toStdString();
1 ✔
1266
    }
1 ✔
1267

1268
    if(params_it != base.MemberEnd())
3 ✔
1269
    {
1270
      const auto& arr = params_it->value.GetArray();
1 ✔
1271
      eff.m_backup_float_data.resize(arr.Size());
1 !
1272
      for(std::size_t i = 0; i < arr.Size(); i++)
2 !
1273
      {
1274
        eff.m_backup_float_data[i] = arr[i].GetDouble();
1 !
1275
      }
1 ✔
1276
    }
1 ✔
1277
  }
1278
}
31 ✔
1279

1280
template <>
1281
void DataStreamReader::read(const vst::ControlInlet& p)
115 ✔
1282
{
1283
  m_stream << p.fxNum << p.m_value;
115 ✔
1284
}
115 ✔
1285
template <>
1286
void DataStreamWriter::write(vst::ControlInlet& p)
64 ✔
1287
{
1288
  m_stream >> p.fxNum >> p.m_value;
64 ✔
1289
}
64 ✔
1290

1291
template <>
1292
void JSONReader::read(const vst::ControlInlet& p)
48 ✔
1293
{
1294
  obj["FxNum"] = p.fxNum;
48 ✔
1295
  obj["Value"] = p.value();
48 ✔
1296
}
48 ✔
1297
template <>
1298
void JSONWriter::write(vst::ControlInlet& p)
58 ✔
1299
{
1300
  p.fxNum = obj["FxNum"].toInt();
58 ✔
1301
  p.setValue(obj["Value"].toDouble());
58 ✔
1302
}
58 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc