• 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

54.07
/src/plugins/score-plugin-clap/Clap/EffectModel.cpp
1
#include "EffectModel.hpp"
2

3
#include <Process/Dataflow/Port.hpp>
4
#include <Process/Dataflow/PortFactory.hpp>
5
#include <Process/Dataflow/WidgetInlets.hpp>
6
#include <Process/ExternalFiles.hpp>
7

8
#include <Scenario/Document/Interval/IntervalModel.hpp>
9

10
#include <Audio/Settings/Model.hpp>
11

12
#include <score/serialization/DataStreamVisitor.hpp>
13
#include <score/serialization/JSONVisitor.hpp>
14
#include <score/tools/IdentifierGeneration.hpp>
15

16
#include <ossia/dataflow/exec_pool.hpp>
17
#include <ossia/detail/json.hpp>
18
#include <ossia/detail/thread.hpp>
19
#include <ossia/network/domain/domain.hpp>
20

21
#include <QApplication>
22
#include <QDir>
23
#include <QDirIterator>
24
#include <QFileInfo>
25
#include <QDebug>
26
#include <QMenu>
27
#include <QThread>
28
#include <QTimer>
29

30
#include <Clap/ApplicationPlugin.hpp>
31
#include <Clap/Window.hpp>
32
#include <clap/all.h>
33
#include <clap/ext/state.h>
34
#include <clap/ext/preset-load.h>
35
#include <clap/factory/preset-discovery.h>
36

37
#include <score_git_info.hpp>
38
#include <wobjectimpl.h>
39

40
#include <clap/ext/context-menu.h>
41

42
#if defined(_WIN32)
43
#include <windows.h>
44
#else
45
#include <dlfcn.h>
46
#endif
47

48
W_OBJECT_IMPL(Clap::Model)
3,173 !
49

50
namespace Clap
51
{
52

53
// Some plug-ins (e.g. Octasine) don't zero-init info.name; reject garbage.
54
static QString
55
clap_safe_name(const char* raw, const QString& fallback) noexcept
253 ✔
56
{
57
  if(!raw)
253 !
58
    return fallback;
×
59
  const auto len = qstrnlen(raw, CLAP_NAME_SIZE);
253 !
60
  if(len == 0)
253 !
61
    return fallback;
×
62
  const QString name = QString::fromUtf8(raw, len);
253 !
63
  if(name.isEmpty())
253 !
64
    return fallback;
×
65
  qsizetype letters = 0;
253 ✔
66
  for(QChar c : name)
1,461 !
67
  {
68
    if(c == QChar::ReplacementCharacter)
1,208 !
69
      return fallback;
×
70
    if(!c.isPrint())
1,208 !
71
      return fallback;
×
72
    if(c.isLetter())
1,208 ✔
73
      ++letters;
1,156 ✔
74
  }
75
  if(letters < 2 && letters < name.length())
253 !
76
    return fallback;
×
77
  return name;
253 ✔
78
}
253 ✔
79

80
namespace
81
{
82
//! The instance a host callback is for
83
PluginInstance& instance_of(const clap_host_t* host)
55 ✔
84
{
85
  return *static_cast<PluginInstance*>(host->host_data);
55 ✔
86
}
87
//! The handle of the process of that instance
88
PluginHandle& handle_of(const clap_host_t* host)
19 ✔
89
{
90
  return *instance_of(host).owner;
19 ✔
91
}
92

93
thread_local bool t_acting_as_audio_thread{};
94
}
95

96
ActingAsAudioThread::ActingAsAudioThread() noexcept
7 ✔
97
    : m_previous{t_acting_as_audio_thread}
7 ✔
98
{
99
  t_acting_as_audio_thread = true;
7 ✔
100
}
7 ✔
101

102
ActingAsAudioThread::~ActingAsAudioThread()
7 ✔
103
{
104
  t_acting_as_audio_thread = m_previous;
7 ✔
105
}
7 ✔
106

107
bool ActingAsAudioThread::active() noexcept
3,060 ✔
108
{
109
  return t_acting_as_audio_thread;
3,060 ✔
110
}
111

112
// Host GUI callbacks. clap/ext/gui.h has them all [thread-safe]: from
113
// another thread than the main one, the request is acknowledged and carried
114
// out on the main thread, where the window lives.
115
namespace
116
{
117
template <typename F>
118
bool on_window(const clap_host_t* host, F f)
4 ✔
119
{
120
  auto& h = handle_of(host);
4 ✔
121
  if(QThread::currentThread() == qApp->thread())
4 !
122
  {
123
    Clap::Model* model = h.model;
×
124
    return model && model->window && f(*model->window);
×
125
  }
126

127
  if(!h.model)
4 !
128
    return false;
×
129
  QMetaObject::invokeMethod(h.model, [model = QPointer<Clap::Model>{h.model}, f] {
8 !
130
    if(model && model->window)
4 !
131
      f(*model->window);
4 ✔
132
  }, Qt::QueuedConnection);
4 ✔
133
  return true;
4 ✔
134
}
4 ✔
135
}
136

137
extern "C" {
138
static void resize_hints_changed(const clap_host_t* host)
1 ✔
139
{
140
  on_window(host, [](Clap::Window& window) {
2 ✔
141
    window.resizeHintsChanged();
1 ✔
142
    return true;
1 ✔
143
  });
144
}
1 ✔
145

146
// Off the main thread, true only says that the request is taken: the window
147
// then takes a size the editor accepts, which resizeEvent gives it
148
static bool request_resize(const clap_host_t* host, uint32_t width, uint32_t height)
1 ✔
149
{
150
  return on_window(host, [width, height](Clap::Window& window) {
2 ✔
151
    window.resize(width, height);
1 ✔
152
    return true;
1 ✔
153
  });
154
}
155

156
static bool request_show(const clap_host_t* host)
1 ✔
157
{
158
  return on_window(host, [](Clap::Window& window) {
2 ✔
159
    window.show();
1 ✔
160
    return true;
1 ✔
161
  });
162
}
163

164
static bool request_hide(const clap_host_t* host)
1 ✔
165
{
166
  return on_window(host, [](Clap::Window& window) {
2 ✔
167
    window.hide();
1 ✔
168
    return true;
1 ✔
169
  });
170
}
171

172
static void closed(const clap_host_t* host, bool was_destroyed)
×
173
{
174
  // The editor destroyed its GUI: closing the window destroys it on our side
175
  on_window(host, [was_destroyed](Clap::Window& window) {
×
176
    if(was_destroyed)
×
177
      window.close();
×
178
    return true;
×
179
  });
180
}
×
181

182
static std::atomic<uint32_t> g_next_timer_id{};
183
bool register_timer(const clap_host_t* host, uint32_t period_ms, clap_id* timer_id)
×
184
{
185
  auto& m = handle_of(host);
×
186
  if(!m.model)
×
187
    return false;
×
188

189
  auto tm = new QTimer{};
×
190
  tm->setInterval(period_ms);
×
191
  *timer_id = g_next_timer_id.fetch_add(1, std::memory_order_relaxed);
×
192
  QObject::connect(
×
193
      tm, &QTimer::timeout, m.model,
×
194
      [h = std::weak_ptr{m.model->handle()}, tid = *timer_id] {
×
195
    if(auto hh = h.lock())
×
196
      if(auto t = hh->ext_timer_support)
×
197
        t->on_timer(hh->plugin, tid);
×
198
  });
×
199
  m.model->timers.push_back({*timer_id, tm});
×
200
  tm->start();
×
201
  return true;
×
202
}
×
203

204
// Returns true on success.
205
// [main-thread]
206
bool unregister_timer(const clap_host_t* host, clap_id timer_id)
×
207
{
208
  auto& m = handle_of(host);
×
209
  if(!m.model)
×
210
    return false;
×
211
  for(auto it = m.model->timers.begin(); it != m.model->timers.end(); ++it)
×
212
  {
213
    if(it->first == timer_id)
×
214
    {
215
      delete it->second;
×
216
      m.model->timers.erase(it);
×
217
      return true;
×
218
    }
219
  }
×
220
  return false;
×
221
}
×
222

223
// POSIX fd support host extension
224
bool register_fd(const clap_host_t* host, int fd, clap_posix_fd_flags_t flags)
×
225
{
226
  auto& m = handle_of(host);
×
227
  if(!m.model)
×
228
    return false;
×
229

230
  // Check if fd is already registered
231
  auto it = m.model->fd_notifiers.find(fd);
×
232
  if(it != m.model->fd_notifiers.end())
×
233
  {
234
    qWarning() << "CLAP: Attempted to register already registered fd" << fd;
×
235
    return false;
×
236
  }
237

238
  // Create notifier structure
239
  auto notifiers = std::make_unique<Model::FdNotifiers>();
×
240

241
  // Set up read notifier
242
  if(flags & CLAP_POSIX_FD_READ)
×
243
  {
244
    notifiers->read = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Read);
×
245
    QObject::connect(
×
246
        notifiers->read.get(), &QSocketNotifier::activated, m.model,
×
247
        [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
248
      if(auto h = handle.lock())
×
249
        if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
250
               h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
251
        {
252
          plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_READ);
×
253
        }
×
254
    });
×
255
    notifiers->read->setEnabled(true);
×
256
  }
×
257

258
  // Set up write notifier
259
  if(flags & CLAP_POSIX_FD_WRITE)
×
260
  {
261
    notifiers->write = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Write);
×
262
    QObject::connect(
×
263
        notifiers->write.get(), &QSocketNotifier::activated, m.model,
×
264
        [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
265
      if(auto h = handle.lock())
×
266
        if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
267
               h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
268
        {
269
          plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_WRITE);
×
270
        }
×
271
    });
×
272
    notifiers->write->setEnabled(true);
×
273
  }
×
274

275
  // Set up error/exception notifier
276
  if(flags & CLAP_POSIX_FD_ERROR)
×
277
  {
278
    notifiers->error = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Exception);
×
279
    QObject::connect(
×
280
        notifiers->error.get(), &QSocketNotifier::activated, m.model,
×
281
        [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
282
      if(auto h = handle.lock())
×
283
        if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
284
               h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
285
        {
286
          plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_ERROR);
×
287
        }
×
288
    });
×
289
    notifiers->error->setEnabled(true);
×
290
  }
×
291

292
  // Store the notifiers
293
  m.model->fd_notifiers[fd] = std::move(notifiers);
×
294
  return true;
×
295
}
×
296

297
bool modify_fd(const clap_host_t* host, int fd, clap_posix_fd_flags_t flags)
×
298
{
299
  auto& m = handle_of(host);
×
300
  if(!m.model)
×
301
    return false;
×
302

303
  auto it = m.model->fd_notifiers.find(fd);
×
304
  if(it == m.model->fd_notifiers.end())
×
305
  {
306
    qWarning() << "CLAP: Attempted to modify unregistered fd" << fd;
×
307
    return false;
×
308
  }
309

310
  auto& notifiers = it->second;
×
311

312
  // Update read notifier
313
  if(flags & CLAP_POSIX_FD_READ)
×
314
  {
315
    if(!notifiers->read)
×
316
    {
317
      notifiers->read = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Read);
×
318
      QObject::connect(
×
319
          notifiers->read.get(), &QSocketNotifier::activated, m.model,
×
320
          [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
321
        if(auto h = handle.lock())
×
322
          if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
323
                 h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
324
          {
325
            plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_READ);
×
326
          }
×
327
      });
×
328
    }
×
329
    notifiers->read->setEnabled(true);
×
330
  }
×
331
  else if(notifiers->read)
×
332
  {
333
    notifiers->read->setEnabled(false);
×
334
  }
×
335

336
  // Update write notifier
337
  if(flags & CLAP_POSIX_FD_WRITE)
×
338
  {
339
    if(!notifiers->write)
×
340
    {
341
      notifiers->write = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Write);
×
342
      QObject::connect(
×
343
          notifiers->write.get(), &QSocketNotifier::activated, m.model,
×
344
          [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
345
        if(auto h = handle.lock())
×
346
          if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
347
                 h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
348
          {
349
            plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_WRITE);
×
350
          }
×
351
      });
×
352
    }
×
353
    notifiers->write->setEnabled(true);
×
354
  }
×
355
  else if(notifiers->write)
×
356
  {
357
    notifiers->write->setEnabled(false);
×
358
  }
×
359

360
  // Update error notifier
361
  if(flags & CLAP_POSIX_FD_ERROR)
×
362
  {
363
    if(!notifiers->error)
×
364
    {
365
      notifiers->error
×
366
          = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Exception);
×
367
      QObject::connect(
×
368
          notifiers->error.get(), &QSocketNotifier::activated, m.model,
×
369
          [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
370
        if(auto h = handle.lock())
×
371
          if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
372
                 h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
373
          {
374
            plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_ERROR);
×
375
          }
×
376
      });
×
377
    }
×
378
    notifiers->error->setEnabled(true);
×
379
  }
×
380
  else if(notifiers->error)
×
381
  {
382
    notifiers->error->setEnabled(false);
×
383
  }
×
384

385
  return true;
×
386
}
×
387

388
bool unregister_fd(const clap_host_t* host, int fd)
×
389
{
390
  auto& m = handle_of(host);
×
391
  if(!m.model)
×
392
    return false;
×
393

394
  auto it = m.model->fd_notifiers.find(fd);
×
395
  if(it == m.model->fd_notifiers.end())
×
396
  {
397
    qWarning() << "CLAP: Attempted to unregister unregistered fd" << fd;
×
398
    return false;
×
399
  }
400

401
  // QSocketNotifier objects will be automatically destroyed by unique_ptr
402
  m.model->fd_notifiers.erase(it);
×
403
  return true;
×
404
}
×
405

406
static QByteArray readCLAPState(const clap_plugin_t& plugin)
15 ✔
407
{
408
  QByteArray dat;
15 ✔
409

410
  // Get state extension
411
  auto state = (const clap_plugin_state_t*)plugin.get_extension(&plugin, CLAP_EXT_STATE);
15 !
412
  if(!state)
15 !
413
    return dat;
×
414

415
  // Create a stream to capture the state
416
  struct stream_context
417
  {
418
    QByteArray* data;
419
  };
420

421
  stream_context ctx{&dat};
15 ✔
422

423
  clap_ostream_t stream{};
15 ✔
424
  stream.ctx = &ctx;
15 ✔
425
  stream.write
15 ✔
426
      = [](const clap_ostream_t* stream, const void* buffer, uint64_t size) -> int64_t {
45 ✔
427
    auto* ctx = static_cast<stream_context*>(stream->ctx);
15 ✔
428
    auto old_size = ctx->data->size();
15 ✔
429
    ctx->data->resize(old_size + size);
15 ✔
430
    std::memcpy(ctx->data->data() + old_size, buffer, size);
15 ✔
431
    return size;
15 ✔
432
  };
433

434
  // Save plugin state
435
  if(!state->save(&plugin, &stream))
15 !
436
    dat.clear();
×
437

438
  return dat;
15 ✔
439
}
15 ✔
440
}
441

442
static constexpr clap_host_timer_support_t host_timer_ext
443
    = {.register_timer = register_timer, .unregister_timer = unregister_timer};
444

445
static constexpr clap_host_posix_fd_support_t host_posix_fd_ext = {
446
    .register_fd = register_fd, .modify_fd = modify_fd, .unregister_fd = unregister_fd};
447

448
static constexpr clap_host_state_t host_state_ext
449
    = {.mark_dirty = [](const clap_host_t* host) {
×
450
  // [main-thread] per CLAP spec. The plug-in says its state changed
451
  // (typically because the user manipulated its own UI). Forward to the
452
  // model, which debounces and snapshots. Plug-ins are known to spam
453
  // this — Vital fires it multiple times per knob movement — so the
454
  // debounce is mandatory.
455
  auto& m = handle_of(host);
×
456
  if(!m.model)
×
457
    return;
×
458
  m.model->markStateDirty();
×
459
}};
×
460
static constexpr clap_host_params_t host_params_ext
461
    = {.rescan = [](const clap_host_t* host, clap_param_rescan_flags flags) {
14 ✔
462
  // Spec: [main-thread]. Defer — plug-ins may call from state.load().
463
  if(!host || !host->host_data)
14 !
464
    return;
×
465
  auto& h = handle_of(host);
14 ✔
466
  if(!h.model)
14 !
467
    return;
×
468
  QMetaObject::invokeMethod(h.model, [model = QPointer<Model>{h.model}, flags] {
28 !
469
    if(model)
14 !
470
      model->onParamRescan(flags);
14 ✔
471
  }, Qt::AutoConnection);
14 ✔
472
}, .clear = [](const clap_host_t* host, clap_id param_id, clap_param_clear_flags flags) {
14 ✔
473
  // TODO
474
  //  qDebug(Q_FUNC_INFO);
475
}, .request_flush = [](const clap_host_t* host) {
1 ✔
476
  //  qDebug(Q_FUNC_INFO);
477
  auto& m = handle_of(host);
1 ✔
478
  if(!m.model)
1 !
479
    return;
×
480

481
  // Per CLAP spec, request_flush is [thread-safe, !audio-thread] and the host
482
  // must SCHEDULE a call to flush() — not invoke it inline. Plugins sometimes
483
  // call request_flush from inside their own state.load() / flush() / GUI
484
  // event handler, so calling flushFromPluginToHost synchronously here could
485
  // reenter clap_plugin_params.flush().
486
  QMetaObject::invokeMethod(m.model, [model = QPointer<Model>{m.model}] {
2 !
487
    if(model && !model->executing())
1 !
488
      model->flushFromPluginToHost();
1 ✔
489
  }, Qt::QueuedConnection);
1 ✔
490
}};
1 ✔
491

492
static constexpr clap_host_gui_t host_gui_ext
493
    = {.resize_hints_changed = resize_hints_changed,
494
       .request_resize = request_resize,
495
       .request_show = request_show,
496
       .request_hide = request_hide,
497
       .closed = closed};
498

499
// [main-thread] — plug-in queries the enclosing track's name/colour. We
500
// look up the closest parent interval and report its metadata. This is
501
// what AIDA-X et al. show in the title bar.
502
static constexpr clap_host_track_info_t host_track_info_ext
503
    = {.get = [](const clap_host_t* host, clap_track_info_t* info) -> bool {
×
504
  auto& m = handle_of(host);
×
505
  if(!m.model || !info)
×
506
    return false;
×
507
  auto* parent = Scenario::closestParentInterval(m.model);
×
508
  if(!parent)
×
509
    return false;
×
510
  info->flags = CLAP_TRACK_INFO_HAS_TRACK_NAME | CLAP_TRACK_INFO_HAS_TRACK_COLOR;
×
511
  auto& meta = parent->metadata();
×
512
  std::string name;
×
513
  if(!meta.getLabel().isEmpty())
×
514
    name = meta.getLabel().toStdString();
×
515
  else if(!meta.getName().isEmpty())
×
516
    name = meta.getName().toStdString();
×
517

518
  std::strncpy(info->name, name.c_str(), CLAP_NAME_SIZE - 1);
×
519
  if(name.size() < CLAP_NAME_SIZE)
×
520
    info->name[name.size()] = 0;
×
521
  else
522
    info->name[CLAP_NAME_SIZE - 1] = 0;
×
523

524
  QRgb col = meta.getColor().getBrush().color().rgba();
×
525
  info->color = clap_color_t{
×
526
      .alpha = (uint8_t)qAlpha(col),
×
527
      .red = (uint8_t)qRed(col),
×
528
      .green = (uint8_t)qGreen(col),
×
529
      .blue = (uint8_t)qBlue(col)};
×
530
  return true;
×
531
}};
×
532

533
static constexpr clap_host_event_registry_t host_event_registry_ext
534
    = {.query = [](const clap_host_t* host, const char* space_name,
×
535
                   uint16_t* space_id) -> bool {
536
  *space_id = UINT16_MAX;
×
537
  return false;
×
538
}};
539

540
static constexpr clap_host_latency_t host_latency_ext
541
    = {.changed = [](const clap_host_t* host) {
×
542
  // TODO
543
}};
×
544

545
static constexpr clap_host_log_t host_log_ext
546
    = {.log = [](const clap_host_t* host, clap_log_severity severity, const char* msg) {
×
547
  switch(severity)
×
548
  {
549
    case CLAP_LOG_DEBUG:
550
      qDebug() << msg;
×
551
      break;
×
552
    case CLAP_LOG_INFO:
553
      qInfo() << msg;
×
554
      break;
×
555
    case CLAP_LOG_WARNING:
556
      qWarning() << msg;
×
557
      break;
×
558
    case CLAP_LOG_HOST_MISBEHAVING:
559
    case CLAP_LOG_PLUGIN_MISBEHAVING:
560
    case CLAP_LOG_ERROR:
561
      qCritical() << msg;
×
562
      break;
×
563
    case CLAP_LOG_FATAL:
564
      qFatal("%s", msg);
×
565
      break;
566
  }
567
}};
×
568

569
static constexpr clap_host_note_name_t host_note_name_ext
570
    = {.changed = [](const clap_host_t* host) {
×
571
  // TODO
572
}};
×
573

574
static constexpr clap_host_preset_load_t host_preset_load_ext
575
    = {.on_error =
576
           [](const clap_host_t* host, uint32_t location_kind, const char* location,
×
577
              const char* load_key, int32_t os_error, const char* msg) {
578
  qWarning() << "CLAP preset load error:" << (msg ? msg : "Unknown error")
×
579
             << "Location:" << (location ? location : "null")  
×
580
             << "Load key:" << (load_key ? load_key : "null")
×
581
             << "OS error:" << os_error;
×
582
},
×
583
       .loaded = [](const clap_host_t* host, uint32_t location_kind,
×
584
                    const char* location, const char* load_key) {
585
  qDebug() << "CLAP preset loaded successfully:"
×
586
           << "Location:" << (location ? location : "null")
×
587
           << "Load key:" << (load_key ? load_key : "null");
×
588
}};
×
589

590
static constexpr clap_host_remote_controls_t host_remote_control_ext
591
    = {.changed = [](const clap_host_t* host) {
×
592
  // qDebug(Q_FUNC_INFO);
593
  // TODO
594
}, .suggest_page = [](const clap_host_t* host, clap_id page_id) {
×
595
  //  qDebug(Q_FUNC_INFO);
596
  // TODO
597
}};
×
598

599
static constexpr clap_host_tail_t host_tail_ext
600
    = {.changed = [](const clap_host_t* host) {
×
601
  //   qDebug(Q_FUNC_INFO);
602
  // TODO
603
}};
×
604

605
static constexpr clap_host_thread_check_t host_thread_check_ext = {
606
    .is_main_thread = [](const clap_host_t* host) -> bool {
2,482 ✔
607
  if(ActingAsAudioThread::active())
2,482 !
608
    return false;
×
609
  return ossia::get_current_thread_type() == ossia::thread_type::Ui;
2,482 ✔
610
},
2,482 ✔
611
    .is_audio_thread = [](const clap_host_t* host) -> bool {
578 ✔
612
  // The shared task pool pins its workers as AudioTask; they run plug-in
613
  // process() / thread-pool exec() under the audio thread's umbrella, so both
614
  // count as "the audio thread" for the plug-in (matches ensure_current_thread_kind).
615
  if(ActingAsAudioThread::active())
578 ✔
616
    return true;
6 ✔
617
  const auto t = ossia::get_current_thread_type();
572 ✔
618
  return t == ossia::thread_type::Audio || t == ossia::thread_type::AudioTask;
572 !
619
},
578 ✔
620
};
621

622
static constexpr clap_host_thread_pool host_thread_pool_ext
623
    = {.request_exec = [](const clap_host_t* host, uint32_t num_tasks) -> bool {
15 ✔
624
  if(!host || !host->host_data)
15 !
625
    return false;
×
626
  // The instance whose process() calls this, not the process's first one
627
  auto& h = instance_of(host);
15 ✔
628
  if(!h.plugin)
15 !
629
    return false;
×
630
  // Queried when the instance was made: this is called from its process()
631
  auto ext = h.ext_thread_pool;
15 ✔
632
  if(!ext || !ext->exec)
15 !
633
    return false;
×
634
  if(num_tasks == 0)
15 !
635
    return false;
×
636

637
  // Synchronous fork-join on the shared realtime pool: workers are RT-pinned
638
  // AudioTask threads, the calling (audio) thread participates, and nothing is
639
  // allocated here. exec() is C ABI but some plug-ins are C++ inside, so guard
640
  // against an escaping exception terminating the audio thread.
641
  const clap_plugin_t* plugin = h.plugin;
15 ✔
642
  ossia::task_pool::instance().fork_n(
30 ✔
643
      static_cast<int>(num_tasks), [plugin, ext](int i) noexcept {
45 ✔
644
    try
645
    {
646
      ext->exec(plugin, static_cast<uint32_t>(i));
30 !
647
    }
30 ✔
648
    catch(...)
649
    {
650
    }
×
651
  });
30 ✔
652
  return true;
15 ✔
653
}};
15 ✔
654

655
static constexpr clap_host_voice_info_t host_voice_info_ext
656
    = {.changed = [](const clap_host_t* host) {
×
657
  //   qDebug(Q_FUNC_INFO);
658
  // TODO
659
}};
×
660

661
// Context menu builder implementation
662
struct context_menu_builder_impl
663
{
664
  QMenu* menu;
665
  QMenu* root_menu;
666
  const clap_plugin_t* plugin;
667
  const clap_plugin_context_menu_t* plugin_context_menu;
668
  const clap_context_menu_target_t* target;
669

670
  context_menu_builder_impl(
×
671
      QMenu* m, const clap_plugin_t* p, const clap_plugin_context_menu_t* pcm,
672
      const clap_context_menu_target_t* t)
673
      : menu(m)
×
674
      , root_menu(m)
×
675
      , plugin(p)
×
676
      , plugin_context_menu(pcm)
×
677
      , target(t)
×
678
  {
679
  }
×
680
};
681

682
static bool context_menu_add_item(
×
683
    const clap_context_menu_builder_t* builder, clap_context_menu_item_kind_t item_kind,
684
    const void* item_data)
685
{
686
  auto* impl = static_cast<context_menu_builder_impl*>(builder->ctx);
×
687
  if(!impl || !impl->menu)
×
688
    return false;
×
689

690
  switch(item_kind)
×
691
  {
692
    case CLAP_CONTEXT_MENU_ITEM_ENTRY: {
693
      auto* entry = static_cast<const clap_context_menu_entry_t*>(item_data);
×
694
      auto* action = impl->menu->addAction(QString::fromUtf8(entry->label));
×
695
      action->setEnabled(entry->is_enabled);
×
696

697
      clap_id action_id = entry->action_id;
×
698
      QObject::connect(action, &QAction::triggered, [action_id, builder]() {
×
699
        auto* impl = static_cast<context_menu_builder_impl*>(builder->ctx);
×
700
        if(impl && impl->plugin_context_menu)
×
701
        {
702
          impl->plugin_context_menu->perform(impl->plugin, impl->target, action_id);
×
703
        }
×
704
      });
×
705
      return true;
×
706
    }
707

708
    case CLAP_CONTEXT_MENU_ITEM_CHECK_ENTRY: {
709
      auto* entry = static_cast<const clap_context_menu_check_entry_t*>(item_data);
×
710
      auto* action = impl->menu->addAction(QString::fromUtf8(entry->label));
×
711
      action->setEnabled(entry->is_enabled);
×
712
      action->setCheckable(true);
×
713
      action->setChecked(entry->is_checked);
×
714

715
      clap_id action_id = entry->action_id;
×
716
      QObject::connect(action, &QAction::triggered, [action_id, builder]() {
×
717
        auto* impl = static_cast<context_menu_builder_impl*>(builder->ctx);
×
718
        if(impl && impl->plugin_context_menu)
×
719
        {
720
          impl->plugin_context_menu->perform(impl->plugin, impl->target, action_id);
×
721
        }
×
722
      });
×
723
      return true;
×
724
    }
725

726
    case CLAP_CONTEXT_MENU_ITEM_SEPARATOR: {
727
      impl->menu->addSeparator();
×
728
      return true;
×
729
    }
730

731
    case CLAP_CONTEXT_MENU_ITEM_BEGIN_SUBMENU: {
732
      auto* submenu_data = static_cast<const clap_context_menu_submenu_t*>(item_data);
×
733
      auto* submenu = impl->menu->addMenu(QString::fromUtf8(submenu_data->label));
×
734
      submenu->setEnabled(submenu_data->is_enabled);
×
735
      impl->menu = submenu; // Switch context to submenu
×
736
      return true;
×
737
    }
738

739
    case CLAP_CONTEXT_MENU_ITEM_END_SUBMENU: {
740
      // Switch back to parent menu
741
      if(impl->menu != impl->root_menu)
×
742
      {
743
        // Find parent menu by traversing up the object hierarchy
744
        QObject* parent = impl->menu->parent();
×
745
        while(parent && !qobject_cast<QMenu*>(parent))
×
746
          parent = parent->parent();
×
747
        if(parent)
×
748
          impl->menu = static_cast<QMenu*>(parent);
×
749
        else
750
          impl->menu = impl->root_menu;
×
751
      }
×
752
      return true;
×
753
    }
754

755
    case CLAP_CONTEXT_MENU_ITEM_TITLE: {
756
      auto* title = static_cast<const clap_context_menu_item_title_t*>(item_data);
×
757
      auto* action = impl->menu->addAction(QString::fromUtf8(title->title));
×
758
      action->setEnabled(false); // Titles are not clickable
×
759
      auto font = action->font();
×
760
      font.setBold(true);
×
761
      action->setFont(font);
×
762
      return true;
×
763
    }
×
764
  }
765
  return false;
×
766
}
×
767

768
static bool context_menu_supports(
×
769
    const clap_context_menu_builder_t* builder, clap_context_menu_item_kind_t item_kind)
770
{
771
  // We support all standard context menu item types
772
  return item_kind == CLAP_CONTEXT_MENU_ITEM_ENTRY
×
773
         || item_kind == CLAP_CONTEXT_MENU_ITEM_CHECK_ENTRY
×
774
         || item_kind == CLAP_CONTEXT_MENU_ITEM_SEPARATOR
×
775
         || item_kind == CLAP_CONTEXT_MENU_ITEM_BEGIN_SUBMENU
×
776
         || item_kind == CLAP_CONTEXT_MENU_ITEM_END_SUBMENU
×
777
         || item_kind == CLAP_CONTEXT_MENU_ITEM_TITLE;
×
778
}
779

780
static constexpr clap_host_context_menu_t host_context_menu_ext = {
781
    .populate = [](const clap_host_t* host, const clap_context_menu_target_t* target,
×
782
                   const clap_context_menu_builder_t* builder) -> bool { return true; },
×
783

784
    .perform = [](const clap_host_t* host, const clap_context_menu_target_t* target,
×
785
                  clap_id action_id) -> bool { return false; },
×
786

787
    .can_popup = [](const clap_host_t* host) -> bool { return true; },
×
788

789
    .popup = [](const clap_host_t* host, const clap_context_menu_target_t* target,
×
790
                int32_t screen_index, int32_t x, int32_t y) -> bool {
791
  auto& m = handle_of(host);
×
792
  if(!m.model)
×
793
    return false;
×
794
  auto& model = *m.model;
×
795
  // Get the plugin's context menu extension
796
  auto* plugin_context_menu = static_cast<const clap_plugin_context_menu_t*>(
×
797
      m.plugin->get_extension(m.plugin, CLAP_EXT_CONTEXT_MENU));
×
798

799
  if(!plugin_context_menu)
×
800
    return false;
×
801

802
  // Create a QMenu
803
  auto menu = std::make_unique<QMenu>();
×
804

805
  // Create builder context
806
  context_menu_builder_impl builder_ctx(
×
807
      menu.get(), m.plugin, plugin_context_menu, target);
×
808
  clap_context_menu_builder_t builder
809
      = {.ctx = &builder_ctx,
×
810
         .add_item = context_menu_add_item,
811
         .supports = context_menu_supports};
812

813
  // Let the plugin populate the menu
814
  if(!plugin_context_menu->populate(m.plugin, target, &builder))
×
815
    return false;
×
816

817
  // Show the menu at the specified position
818
  QPoint pos(x, y);
×
819
  menu->exec(pos);
×
820

821
  return true;
×
822
}};
×
823

824
PluginInstance::PluginInstance()
247 ✔
825
{
826
  host.host_data = this;
247 ✔
827
  host.clap_version = CLAP_VERSION;
247 ✔
828
  host.name = "ossia score";
247 ✔
829
  host.vendor = "ossia.io";
247 ✔
830
  host.url = "https://ossia.io";
247 ✔
831
  host.version = SCORE_TAG_NO_V;
247 ✔
832
  host.get_extension
247 ✔
833
      = [](const clap_host* host, const char* extension_id) -> const void* {
876 ✔
834
    if(strcmp(extension_id, CLAP_EXT_GUI) == 0)
382 ✔
835
      return &host_gui_ext;
1 ✔
836
    if(strcmp(extension_id, CLAP_EXT_STATE) == 0)
381 !
837
      return &host_state_ext;
×
838
    if(strcmp(extension_id, CLAP_EXT_PARAMS) == 0)
381 ✔
839
      return &host_params_ext;
27 ✔
840
    if(strcmp(extension_id, CLAP_EXT_TIMER_SUPPORT) == 0)
354 !
841
      return &host_timer_ext;
×
842
    if(strcmp(extension_id, CLAP_EXT_POSIX_FD_SUPPORT) == 0)
354 !
843
      return &host_posix_fd_ext;
×
844
    if(strcmp(extension_id, CLAP_EXT_TRACK_INFO) == 0)
354 !
845
      return &host_track_info_ext;
×
846
    if(strcmp(extension_id, "clap.track-info.draft/1") == 0)
354 !
847
      return &host_track_info_ext;
×
848
    if(strcmp(extension_id, CLAP_EXT_EVENT_REGISTRY) == 0)
354 !
849
      return &host_event_registry_ext;
×
850
    if(strcmp(extension_id, CLAP_EXT_LOG) == 0)
354 !
851
      return &host_log_ext;
×
852
    if(strcmp(extension_id, CLAP_EXT_LATENCY) == 0)
354 !
853
      return &host_latency_ext;
×
854
    if(strcmp(extension_id, CLAP_EXT_NOTE_NAME) == 0)
354 !
855
      return &host_note_name_ext;
×
856
    if(strcmp(extension_id, CLAP_EXT_PRESET_LOAD) == 0)
354 !
857
      return &host_preset_load_ext;
×
858
    if(strcmp(extension_id, "clap.preset-load.draft/2") == 0)
354 !
859
      return &host_preset_load_ext;
×
860
    if(strcmp(extension_id, CLAP_EXT_REMOTE_CONTROLS) == 0)
354 !
861
      return &host_remote_control_ext;
×
862
    if(strcmp(extension_id, "clap.remote-controls.draft/2") == 0)
354 !
863
      return &host_remote_control_ext;
×
864
    if(strcmp(extension_id, CLAP_EXT_TAIL) == 0)
354 !
865
      return &host_tail_ext;
×
866
    if(strcmp(extension_id, CLAP_EXT_THREAD_CHECK) == 0)
354 ✔
867
      return &host_thread_check_ext;
339 ✔
868
    if(strcmp(extension_id, CLAP_EXT_THREAD_POOL) == 0)
15 !
869
      return &host_thread_pool_ext;
15 ✔
870
    if(strcmp(extension_id, CLAP_EXT_VOICE_INFO) == 0)
×
871
      return &host_voice_info_ext;
×
872
    if(strcmp(extension_id, CLAP_EXT_CONTEXT_MENU) == 0)
×
873
      return &host_context_menu_ext;
×
874
    if(strcmp(extension_id, "clap.context-menu.draft/0") == 0)
×
875
      return &host_context_menu_ext;
×
876
    return nullptr;
×
877
  };
382 ✔
878
  host.request_restart = [](const clap_host* host) {
264 ✔
879
    // clap/host.h: "Request the host to deactivate and then reactivate the
880
    // plugin. The operation may be delayed by the host." [thread-safe]
881
    // The instance that asks: while its node processes it, the node stops
882
    // it first. Stopped, it is only deactivated, as the next play activates
883
    // it with the engine's rate and block size.
884
    auto& inst = instance_of(host);
17 ✔
885
    inst.restart_pending.store(true, std::memory_order_release);
17 ✔
886
    QMetaObject::invokeMethod(qApp, [w = inst.weak_from_this()] {
34 !
887
      if(auto i = w.lock())
34 !
888
        i->reconcile();
17 !
889
    }, Qt::QueuedConnection);
17 ✔
890
  };
17 ✔
891
  host.request_process = [](const clap_host* host) {
247 ✔
892
    // clap/host.h: "useful if you have external IO and need to wake up the
893
    // plugin from "sleep"." [thread-safe]
894
    instance_of(host).wake.store(true, std::memory_order_release);
×
895
  };
×
896
  host.request_callback = [](const clap_host* host) {
251 ✔
897
    // clap/host.h: "schedule a call to plugin->on_main_thread(plugin)",
898
    // the instance that asks. [thread-safe]
899
    QMetaObject::invokeMethod(qApp, [w = instance_of(host).weak_from_this()] {
8 !
900
      if(auto i = w.lock())
8 !
901
        if(auto plug = i->plugin)
8 !
902
          plug->on_main_thread(plug);
4 !
903
    }, Qt::QueuedConnection);
4 ✔
904
  };
4 ✔
905
}
247 ✔
906

907
PluginInstance::~PluginInstance()
247 ✔
908
{
909
  destroy();
247 !
910
}
247 ✔
911

912
bool PluginInstance::activate(double rate, uint32_t block)
229 ✔
913
{
914
  uint8_t expected = Inactive;
229 ✔
915
  if(!plugin
229 ✔
916
     || !state.compare_exchange_strong(expected, Busy, std::memory_order_acq_rel))
229 !
917
    return false;
×
918
  const bool ok = plugin->activate(plugin, rate, 1, block);
229 ✔
919
  fresh = ok;
229 ✔
920
  state.store(ok ? Active : Inactive, std::memory_order_release);
229 ✔
921
  return ok;
229 ✔
922
}
229 ✔
923

924
bool PluginInstance::deactivate()
430 ✔
925
{
926
  uint8_t expected = Active;
430 ✔
927
  if(!plugin
430 ✔
928
     || !state.compare_exchange_strong(expected, Busy, std::memory_order_acq_rel))
430 ✔
929
    return false;
201 ✔
930
  plugin->deactivate(plugin);
229 ✔
931
  state.store(Inactive, std::memory_order_release);
229 ✔
932
  return true;
229 ✔
933
}
430 ✔
934

935
void PluginInstance::reconcile()
288 ✔
936
{
937
  const bool restart = restart_pending.load(std::memory_order_acquire);
288 ✔
938
  bool deactivated = false;
288 ✔
939
  if(restart || nodes == 0)
288 ✔
940
  {
941
    deactivated = deactivate();
184 ✔
942
    // Processing, or claimed by the audio thread to be: its node stops it,
943
    // then calls this again
944
    if(!deactivated && state.load(std::memory_order_acquire) != Inactive)
184 ✔
945
      return;
22 ✔
946
  }
162 ✔
947
  if(nodes > 0 && state.load(std::memory_order_acquire) == Inactive)
266 ✔
948
    activate(node_rate, node_block);
52 ✔
949
  if(restart)
266 ✔
950
    restart_pending.store(false, std::memory_order_release);
17 ✔
951

952
  if(deactivated && owner == this && owner->model)
266 ✔
953
    owner->model->onDeactivated();
44 ✔
954
}
288 ✔
955

956
void PluginInstance::destroy()
317 ✔
957
{
958
  if(!plugin)
317 ✔
959
    return;
71 ✔
960
  if(state.load(std::memory_order_acquire) == Processing)
246 !
961
  {
962
    ActingAsAudioThread audio;
×
963
    stop_processing();
×
964
  }
×
965
  deactivate();
246 ✔
966
  plugin->destroy(plugin);
246 ✔
967
  plugin = nullptr;
246 ✔
968
}
317 ✔
969

970
bool PluginInstance::start_processing()
124 ✔
971
{
972
  if(restart_pending.load(std::memory_order_acquire))
124 !
973
    return false;
×
974
  uint8_t expected = Active;
124 ✔
975
  if(!state.compare_exchange_strong(expected, Busy, std::memory_order_acq_rel))
124 !
976
    return false;
×
977
  // clap/plugin.h: reset() "Clears all buffers, performs a full reset of the
978
  // processing state (filters, oscillators, envelopes, lfo, ...) and kills
979
  // all voices", "clap_process.steady_time may jump backward": what a play
980
  // starting again after an idle transport needs, without the tails of the
981
  // last one. "The parameter's value remain unchanged." Just activated, it
982
  // has none: a plug-in may answer reset() with a restart (DPF does, without
983
  // a reset parameter), which would otherwise never end.
984
  if(!fresh)
124 ✔
985
    plugin->reset(plugin);
15 ✔
986
  fresh = false;
124 ✔
987
  const bool ok = plugin->start_processing(plugin);
124 ✔
988
  state.store(ok ? Processing : Active, std::memory_order_release);
124 ✔
989
  return ok;
124 ✔
990
}
124 ✔
991

992
void PluginInstance::stop_processing()
124 ✔
993
{
994
  uint8_t expected = Processing;
124 ✔
995
  if(!state.compare_exchange_strong(expected, Busy, std::memory_order_acq_rel))
124 !
996
    return;
×
997
  plugin->stop_processing(plugin);
124 ✔
998
  state.store(Active, std::memory_order_release);
124 ✔
999
}
124 ✔
1000

1001
PluginHandle::PluginHandle()
140 ✔
1002
{
1003
  owner = this;
70 ✔
1004
}
70 ✔
1005

1006
namespace
1007
{
1008
// clap/entry.h: the host calls init() once and deinit() once, in a matched
1009
// pair, however many plug-ins it makes from the library. One count per
1010
// library, as two processes of one .clap share its entry. [main-thread]
1011
ossia::hash_map<const clap_plugin_entry_t*, int>& entry_users()
138 ✔
1012
{
1013
  static ossia::hash_map<const clap_plugin_entry_t*, int> users;
138 !
1014
  return users;
138 ✔
1015
}
×
1016

1017
//! clap/entry.h: what init() is given is the library on Linux and Windows,
1018
//! the bundle on macOS, of which score keeps the binary in Contents/MacOS
1019
std::string entry_init_path(std::string_view library)
62 ✔
1020
{
1021
#if defined(__APPLE__)
1022
  if(auto p = library.rfind(".clap/Contents/MacOS/"); p != std::string_view::npos)
1023
    return std::string(library.substr(0, p + 5));
1024
#endif
1025
  return std::string(library);
62 !
1026
}
×
1027

1028
bool acquire_entry(const clap_plugin_entry_t* entry, const char* path)
69 ✔
1029
{
1030
  auto& users = entry_users();
69 ✔
1031
  if(auto it = users.find(entry); it != users.end())
69 ✔
1032
  {
1033
    it->second++;
7 ✔
1034
    return true;
7 ✔
1035
  }
1036
  if(!entry->init(entry_init_path(path).c_str()))
62 !
1037
    return false;
×
1038
  users[entry] = 1;
62 ✔
1039
  return true;
62 ✔
1040
}
69 ✔
1041

1042
void release_entry(const clap_plugin_entry_t* entry)
69 ✔
1043
{
1044
  auto& users = entry_users();
69 ✔
1045
  auto it = users.find(entry);
69 ✔
1046
  if(it == users.end())
69 !
1047
    return;
×
1048
  if(--it->second == 0)
69 ✔
1049
  {
1050
    users.erase(it);
62 ✔
1051
    entry->deinit();
62 ✔
1052
  }
62 ✔
1053
}
69 ✔
1054
}
1055

1056
PluginHandle::~PluginHandle()
70 ✔
1057
{
1058
  // Before its library goes
1059
  destroy();
70 !
1060

1061
  if(entry)
70 ✔
1062
  {
1063
    release_entry(entry);
69 !
1064
    entry = nullptr;
69 ✔
1065
  }
69 ✔
1066

1067
  if(library)
70 ✔
1068
  {
1069
#if defined(_WIN32)
1070
    FreeLibrary((HMODULE)library);
1071
#elif defined(__APPLE__)
1072
    // Never unloaded: Cocoa keeps references into the image of a plug-in
1073
    // that showed an editor (its Objective-C classes, in weak tables and
1074
    // notification observers) past the plug-in's life. dyld ignores
1075
    // RTLD_NODELETE: the handle is kept instead.
1076
#else
1077
    dlclose(library);
69 ✔
1078
#endif
1079
    library = nullptr;
69 ✔
1080
  }
69 ✔
1081
}
70 ✔
1082

1083
static void loadCLAPState(const clap_plugin_t& plugin, const QByteArray& state)
4 ✔
1084
{
1085
  if(state.isEmpty())
4 !
1086
    return;
×
1087

1088
  // Get state extension
1089
  auto state_ext
4 ✔
1090
      = (const clap_plugin_state_t*)plugin.get_extension(&plugin, CLAP_EXT_STATE);
4 ✔
1091
  if(!state_ext)
4 !
1092
    return;
×
1093

1094
  // Create input stream
1095
  struct stream_context
1096
  {
1097
    const QByteArray* data;
1098
    int64_t position;
1099
  };
1100

1101
  stream_context ctx{&state, 0};
4 ✔
1102

1103
  clap_istream_t stream{};
4 ✔
1104
  stream.ctx = &ctx;
4 ✔
1105
  stream.read
4 ✔
1106
      = [](const clap_istream_t* stream, void* buffer, uint64_t size) -> int64_t {
12 ✔
1107
    auto* ctx = static_cast<stream_context*>(stream->ctx);
4 ✔
1108
    int64_t remaining = ctx->data->size() - ctx->position;
4 ✔
1109
    int64_t to_read = std::min(static_cast<int64_t>(size), remaining);
4 ✔
1110

1111
    if(to_read <= 0)
4 !
1112
      return 0;
×
1113

1114
    std::memcpy(buffer, ctx->data->constData() + ctx->position, to_read);
4 ✔
1115
    ctx->position += to_read;
4 ✔
1116
    return to_read;
4 ✔
1117
  };
4 ✔
1118

1119
  // Load plugin state
1120
  state_ext->load(&plugin, &stream);
4 ✔
1121
}
4 ✔
1122

1123
Model::Model(
66 !
1124
    const TimeVal& duration, const QString& pluginId,
1125
    const Id<Process::ProcessModel>& id, QObject* parent)
1126
    : Process::ProcessModel{duration, id, "ClapProcess", parent}
66 !
1127
    , m_plugin{std::make_shared<PluginHandle>()}
66 !
1128
{
66 ✔
1129
  // "<path>:::<id>" is what the library gives us, but a process can also be
1130
  // created before anything is chosen -- the object gallery does exactly that,
1131
  // and so does a document that lost the setting. Stay empty instead of
1132
  // aborting the application.
1133
  auto plug = pluginId.split(":::");
66 !
1134
  if(plug.size() == 2)
66 ✔
1135
  {
1136
    m_pluginPath = plug[0];
65 !
1137
    m_pluginId = plug[1];
65 !
1138
    loadPlugin();
65 !
1139
  }
65 ✔
1140
  createControls(false);
66 !
1141
}
66 ✔
1142

1143
Model::Model(DataStream::Deserializer& vis, QObject* parent)
4 !
1144
    : Process::ProcessModel{vis, parent}
2 ✔
1145
    , m_plugin{std::make_shared<PluginHandle>()}
2 !
1146
{
2 ✔
1147
  vis.writeTo(*this);
2 !
1148
  loadPlugin();
2 !
1149
  createControls(true);
2 !
1150
}
2 ✔
1151

1152
Model::Model(JSONObject::Deserializer& vis, QObject* parent)
4 !
1153
    : Process::ProcessModel{vis, parent}
2 ✔
1154
    , m_plugin{std::make_shared<PluginHandle>()}
2 !
1155
{
2 ✔
1156
  vis.writeTo(*this);
2 !
1157
  loadPlugin();
2 !
1158
  createControls(true);
2 !
1159
}
2 ✔
1160

1161
Model::Model(DataStream::Deserializer&& vis, QObject* parent)
×
1162
    : Process::ProcessModel{vis, parent}
×
1163
    , m_plugin{std::make_shared<PluginHandle>()}
×
1164
{
×
1165
  vis.writeTo(*this);
×
1166
  loadPlugin();
×
1167
  createControls(true);
×
1168
}
×
1169

1170
Model::Model(JSONObject::Deserializer&& vis, QObject* parent)
×
1171
    : Process::ProcessModel{vis, parent}
×
1172
    , m_plugin{std::make_shared<PluginHandle>()}
×
1173
{
×
1174
  vis.writeTo(*this);
×
1175
  loadPlugin();
×
1176
  createControls(true);
×
1177
}
×
1178

1179
Model::~Model()
140 ✔
1180
{
70 ✔
1181
  closeUI();
70 !
1182

1183
  // A node that still runs it keeps the handle, and deactivates it once it
1184
  // stopped
1185
  m_plugin->model = nullptr;
70 !
1186
  m_plugin->reconcile();
70 !
1187

1188
  // Clean up timers
1189
  for(auto& [id, timer] : timers)
70 !
1190
  {
1191
    delete timer;
×
1192
  }
1193
  timers.clear();
70 ✔
1194

1195
  // Clean up fd notifiers (automatically handled by unique_ptr destructors)
1196
  fd_notifiers.clear();
70 !
1197
}
140 ✔
1198

1199
bool Model::hasExternalUI() const noexcept
56 ✔
1200
{
1201
  if(!m_plugin->plugin)
56 ✔
1202
    return false;
2 ✔
1203

1204
  auto gui = (const clap_plugin_gui_t*)m_plugin->plugin->get_extension(
108 !
1205
      m_plugin->plugin, CLAP_EXT_GUI);
54 ✔
1206
  return gui != nullptr;
54 ✔
1207
}
56 ✔
1208

1209
void Model::closeUI() const
70 ✔
1210
{
1211
  if(this->externalUI)
70 !
1212
    this->externalUI->close();
×
1213
}
70 ✔
1214

1215
void PluginHandle::load(Model& context, QByteArray path, QByteArray id)
69 ✔
1216
{
1217
  this->model = &context;
69 ✔
1218

1219
  // Helper to roll back partial-load state. CLAP entry init/deinit is
1220
  // refcounted (see clap/entry.h): we must NOT call deinit unless init
1221
  // returned true, otherwise we corrupt the refcount and eventually crash
1222
  // other plug-ins that share the .clap bundle. Same idea for
1223
  // dlclose(library) — only meaningful if dlopen succeeded.
1224
  auto rollback = [this](bool entry_inited) {
69 ✔
1225
    if(!entry_inited)
×
1226
      entry = nullptr;
×
1227
    if(!library)
×
1228
      return;
×
1229
    // If we never reached entry->init() successfully, don't deinit; just
1230
    // release the library handle so ~PluginHandle doesn't redo it.
1231
  };
×
1232

1233
  // Load the library
1234
#if defined(_WIN32)
1235
  library = LoadLibraryA(path.data());
1236
  if(!library)
1237
    return;
1238
  entry = (const clap_plugin_entry_t*)GetProcAddress((HMODULE)library, "clap_entry");
1239
#else
1240
  library = dlopen(path.data(), RTLD_LAZY);
69 ✔
1241
  if(!library)
69 !
1242
    return;
×
1243
  entry = (const clap_plugin_entry_t*)dlsym(library, "clap_entry");
69 ✔
1244
#endif
1245

1246
  if(!entry)
69 !
1247
  {
1248
    // No clap_entry symbol — drop the library handle and bail.
1249
    rollback(false);
×
1250
    return;
×
1251
  }
1252

1253
  if(!acquire_entry(entry, path.data()))
69 !
1254
  {
1255
    // init() failed: entry pointer is valid but the DSO is uninitialized,
1256
    // so we must NOT call entry->deinit() later. Forget the entry pointer
1257
    // so ~PluginHandle's `if(entry) entry->deinit();` is skipped.
1258
    rollback(false);
×
1259
    return;
×
1260
  }
1261

1262
  factory = (const clap_plugin_factory_t*)entry->get_factory(CLAP_PLUGIN_FACTORY_ID);
69 ✔
1263
  if(!factory)
69 !
1264
    return;
×
1265

1266
  plugin = factory->create_plugin(factory, &host, id.data());
69 ✔
1267
  if(!plugin)
69 !
1268
    return;
×
1269

1270
  if(!plugin->init(plugin))
69 !
1271
  {
1272
    plugin->destroy(plugin);
×
1273
    plugin = nullptr;
×
1274
    return;
×
1275
  }
1276

1277
  // Juce calls it during init??
1278
  ext_timer_support = (const clap_plugin_timer_support_t*)plugin->get_extension(
138 ✔
1279
      plugin, CLAP_EXT_TIMER_SUPPORT);
69 ✔
1280
  ext_params
69 ✔
1281
      = (const clap_plugin_params_t*)plugin->get_extension(plugin, CLAP_EXT_PARAMS);
138 ✔
1282
  ext_thread_pool = (const clap_plugin_thread_pool_t*)plugin->get_extension(
138 ✔
1283
      plugin, CLAP_EXT_THREAD_POOL);
69 ✔
1284

1285
  desc = plugin->desc;
69 ✔
1286
}
69 ✔
1287

1288
void Model::loadPlugin()
69 ✔
1289
{
1290
  if(m_pluginPath.isEmpty() || m_pluginId.isEmpty())
69 !
1291
    return;
×
1292

1293
  m_plugin->load(*this, m_pluginPath.toUtf8(), m_pluginId.toUtf8());
69 !
1294

1295
  if(m_plugin->plugin && !m_loadedState.isEmpty())
69 !
1296
  {
1297
    loadCLAPState(*m_plugin->plugin, m_loadedState);
4 ✔
1298
  }
4 ✔
1299

1300
  // Connect parameter value feedback from executor to GUI
1301
  if(auto params = m_plugin->ext_params)
69 ✔
1302
  {
1303
    auto& ctx = score::IDocument::documentContext(*this);
61 ✔
1304
    auto c = connect(&ctx.coarseUpdateTimer, &QTimer::timeout, this, [this] {
220 ✔
1305
      auto h = handle();
159 ✔
1306
      if(!h)
159 !
1307
        return;
×
1308
      auto plugin = h->plugin;
159 ✔
1309
      if(!plugin)
159 !
1310
        return;
×
1311
      auto params = m_plugin->ext_params;
159 ✔
1312
      if(!params || !params->get_value)
159 !
1313
        return;
×
1314

1315
      // Writable params -> ControlInlets.
1316
      std::size_t inlet_idx = 0;
159 ✔
1317
      for(auto* inlet : inlets())
482 ✔
1318
      {
1319
        if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
323 !
1320
        {
1321
          if(inlet_idx < m_plugin->m_parameters_ins.size())
164 !
1322
          {
1323
            const auto& param_info = m_plugin->m_parameters_ins[inlet_idx];
164 ✔
1324
            double current_value = 0.0;
164 ✔
1325
            if(params->get_value(plugin, param_info.id, &current_value))
164 !
1326
            {
1327
              currentlyReadingValues = true;
164 ✔
1328
              control->setValue(current_value);
164 !
1329
              currentlyReadingValues = false;
164 ✔
1330
            }
164 ✔
1331
          }
164 ✔
1332
          inlet_idx++;
164 ✔
1333
        }
164 ✔
1334
      }
1335

1336
      // Read-only params -> ControlOutlets (Bargraph meters etc.).
1337
      std::size_t outlet_idx = 0;
159 ✔
1338
      for(auto* outlet : outlets())
475 ✔
1339
      {
1340
        if(auto* control = qobject_cast<Process::ControlOutlet*>(outlet))
316 !
1341
        {
1342
          if(outlet_idx < m_plugin->m_parameters_outs.size())
157 !
1343
          {
1344
            const auto& param_info = m_plugin->m_parameters_outs[outlet_idx];
157 ✔
1345
            double current_value = 0.0;
157 ✔
1346
            if(params->get_value(plugin, param_info.id, &current_value))
157 !
1347
            {
1348
              currentlyReadingValues = true;
157 ✔
1349
              control->setValue(current_value);
157 !
1350
              currentlyReadingValues = false;
157 ✔
1351
            }
157 ✔
1352
          }
157 ✔
1353
          outlet_idx++;
157 ✔
1354
        }
157 ✔
1355
      }
1356
    });
159 !
1357
  }
61 ✔
1358
}
69 ✔
1359

1360
void Model::onDeactivated()
44 ✔
1361
{
1362
  // clap/ext/params.h: CLAP_PARAM_RESCAN_ALL "can only be used while the
1363
  // plugin is deactivated"
1364
  if(m_pendingRescanFlags != 0)
44 !
1365
  {
1366
    auto pending = std::exchange(m_pendingRescanFlags, 0u);
×
1367
    onParamRescan(pending);
×
1368
  }
×
1369
}
44 ✔
1370

1371
namespace
1372
{
1373
// Build a clap_input_events_t backed by a std::vector of event pointers.
1374
struct ParamInputCtx
1375
{
1376
  std::vector<const clap_event_header_t*> events;
1377
};
1378
inline clap_input_events_t make_input_events(ParamInputCtx& ctx)
18 ✔
1379
{
1380
  return {
72 ✔
1381
      .ctx = &ctx,
18 ✔
1382
      .size = +[](const clap_input_events* list) -> uint32_t {
36 ✔
1383
    return static_cast<const ParamInputCtx*>(list->ctx)->events.size();
18 ✔
1384
  },
1385
      .get = +[](const clap_input_events* list,
36 ✔
1386
                 uint32_t index) -> const clap_event_header_t* {
1387
    auto* c = static_cast<const ParamInputCtx*>(list->ctx);
18 ✔
1388
    return index < c->events.size() ? c->events[index] : nullptr;
18 !
1389
  }};
1390
}
1391

1392
inline clap_event_param_value_t
1393
make_param_value(const clap_param_info_t& info, double value)
18 ✔
1394
{
1395
  clap_event_param_value_t ev{};
18 ✔
1396
  ev.header.size = sizeof(clap_event_param_value_t);
18 ✔
1397
  ev.header.time = 0;
18 ✔
1398
  ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
18 ✔
1399
  ev.header.type = CLAP_EVENT_PARAM_VALUE;
18 ✔
1400
  ev.header.flags = CLAP_EVENT_IS_LIVE;
18 ✔
1401
  ev.param_id = info.id;
18 ✔
1402
  ev.cookie = info.cookie;
18 ✔
1403
  ev.note_id = -1;
18 ✔
1404
  ev.port_index = -1;
18 ✔
1405
  ev.channel = -1;
18 ✔
1406
  ev.key = -1;
18 ✔
1407
  ev.value = value;
18 ✔
1408
  return ev;
18 ✔
1409
}
1410
} // namespace
1411

1412
// clap/ext/params.h: a knob turned on the host's interface is a value sent
1413
// through process() or flush(). Gestures are the plug-in telling the host its
1414
// own editor is being used: they are not sent to it.
1415
void Model::sendParamChange(const clap_param_info_t& info, double value)
21 ✔
1416
{
1417
  // Active, the plug-in is flushed from the audio thread only: its node
1418
  // sends it the control's value
1419
  auto plugin = m_plugin->plugin;
21 ✔
1420
  if(!plugin || m_plugin->state.load(std::memory_order_acquire) != PluginInstance::Inactive)
21 !
1421
    return;
3 ✔
1422
  auto params
18 ✔
1423
      = (const clap_plugin_params_t*)plugin->get_extension(plugin, CLAP_EXT_PARAMS);
18 ✔
1424
  if(!params || !params->flush)
18 !
1425
    return;
×
1426

1427
  clap_event_param_value_t value_ev = make_param_value(info, value);
18 ✔
1428
  ParamInputCtx ctx;
18 ✔
1429
  ctx.events.push_back(&value_ev.header);
18 !
1430

1431
  clap_input_events_t ip = make_input_events(ctx);
18 !
1432
  clap_output_events_t op{
36 ✔
1433
      .ctx = this,
1434
      .try_push = [](const struct clap_output_events*,
18 ✔
1435
                     const clap_event_header_t*) { return false; }};
×
1436
  params->flush(plugin, &ip, &op);
18 !
1437
}
21 ✔
1438

1439
void Model::setupControlInlet(
107 ✔
1440
    const clap_plugin_params_t& params, const clap_param_info_t& info, int index,
1441
    Process::ControlInlet* inlet)
1442
{
1443
  inlet->displayHandledExplicitly = true; //(info.flags & CLAP_PARAM_IS_HIDDEN) != 0;
107 ✔
1444

1445
  // Set default value, min, and max for the control inlet
1446
  double val{};
107 ✔
1447
  // FIXME if we load we do not want to change the GUI inlet value, instead we
1448
  // want to reapply it to the state (so that an inlet with a LFO as input does not
1449
  // change its value randomly on every load
1450
  if(params.get_value && params.get_value(m_plugin->plugin, info.id, &val))
107 !
1451
  {
1452
    inlet->setValue(val);
107 !
1453
  }
107 ✔
1454
  else
1455
  {
1456
    inlet->setValue(info.default_value);
×
1457
  }
1458

1459
  inlet->setDomain(ossia::make_domain(info.min_value, info.max_value));
107 !
1460

1461
  connect(
107 ✔
1462
      inlet, &Process::ControlInlet::valueChanged, this,
107 ✔
1463
      [this, i = index](const ossia::value& v) {
164 ✔
1464
    if(executing())
57 ✔
1465
      return;
23 ✔
1466
    if(currentlyReadingValues)
34 ✔
1467
      return;
13 ✔
1468
    SCORE_ASSERT(this->parameterInputs().size() > i);
21 !
1469
    auto& param_info = this->parameterInputs()[i];
21 ✔
1470
    double val
21 ✔
1471
        = std::clamp(ossia::convert<double>(v), param_info.min_value, param_info.max_value);
21 ✔
1472
    sendParamChange(param_info, val);
21 ✔
1473
  });
57 ✔
1474
}
107 ✔
1475

1476
void Model::setupControlOutlet(
43 ✔
1477
    const clap_plugin_params_t& params, const clap_param_info_t& info, int index,
1478
    Process::ControlOutlet* port)
1479
{
1480
  port->displayHandledExplicitly = true; //(info.flags & CLAP_PARAM_IS_HIDDEN) != 0;
43 ✔
1481

1482
  // Set default value, min, and max for the control inlet
1483
  double val{};
43 ✔
1484
  // FIXME if we load we do not want to change the GUI inlet value, instead we
1485
  // want to reapply it to the state (so that an inlet with a LFO as input does not
1486
  // change its value randomly on every load
1487
  if(params.get_value && params.get_value(m_plugin->plugin, info.id, &val))
43 !
1488
  {
1489
    port->setValue(val);
43 !
1490
  }
43 ✔
1491
  else
1492
  {
1493
    port->setValue(info.default_value);
×
1494
  }
1495

1496
  port->setDomain(ossia::make_domain(info.min_value, info.max_value));
43 !
1497
}
43 ✔
1498

1499
void Model::createControls(bool loading)
70 ✔
1500
{
1501
  if(!m_plugin->plugin)
70 ✔
1502
    return;
1 ✔
1503

1504
  int cur_inlet = 0;
69 ✔
1505
  int cur_outlet = 0;
69 ✔
1506

1507
  // Get audio ports extension
1508
  auto audio_ports = (const clap_plugin_audio_ports_t*)m_plugin->plugin->get_extension(
138 ✔
1509
      m_plugin->plugin, CLAP_EXT_AUDIO_PORTS);
69 ✔
1510
  m_supports64 = true;
69 ✔
1511
  m_plugin->m_audio_ins.clear();
69 ✔
1512
  m_plugin->m_audio_outs.clear();
69 ✔
1513
  if(audio_ports)
69 ✔
1514
  {
1515
    auto input_count = audio_ports->count(m_plugin->plugin, true);
61 ✔
1516
    for(uint32_t i = 0; i < input_count; ++i)
114 ✔
1517
    {
1518
      clap_audio_port_info_t info{};
53 ✔
1519
      if(audio_ports->get(m_plugin->plugin, i, true, &info))
53 !
1520
      {
1521
        m_supports64 &= (info.flags & CLAP_AUDIO_PORT_SUPPORTS_64BITS);
53 ✔
1522

1523
        if(!loading)
53 ✔
1524
        {
1525
          QString name = clap_safe_name(
51 !
1526
              info.name, input_count == 1 ? QStringLiteral("Audio In")
51 !
1527
                                          : QStringLiteral("Audio In %1").arg(i + 1));
×
1528
          if(i == 0 && name.toLower() == "audio input")
51 !
1529
            name = "Audio In";
9 !
1530
          auto inlet = new Process::AudioInlet(
102 !
1531
              name, Id<Process::Port>(getStrongId(m_inlets)), this);
51 !
1532
          m_inlets.push_back(inlet);
51 !
1533
        }
51 ✔
1534

1535
        m_plugin->m_audio_ins.push_back(info);
53 ✔
1536
        cur_inlet++;
53 ✔
1537
      }
53 ✔
1538
    }
53 ✔
1539
    auto output_count = audio_ports->count(m_plugin->plugin, false);
61 ✔
1540
    for(uint32_t i = 0; i < output_count; ++i)
122 ✔
1541
    {
1542
      clap_audio_port_info_t info{};
61 ✔
1543
      if(audio_ports->get(m_plugin->plugin, i, false, &info))
61 !
1544
      {
1545
        m_supports64 &= (info.flags & CLAP_AUDIO_PORT_SUPPORTS_64BITS);
61 ✔
1546

1547
        if(!loading)
61 ✔
1548
        {
1549
          QString name = clap_safe_name(
57 !
1550
              info.name, output_count == 1 ? QStringLiteral("Audio Out")
57 !
1551
                                           : QStringLiteral("Audio Out %1").arg(i + 1));
×
1552
          if(i == 0 && name.toLower() == "audio output")
57 !
1553
            name = "Audio Out";
14 !
1554
          auto outlet = new Process::AudioOutlet(
114 !
1555
              name, Id<Process::Port>(getStrongId(m_outlets)), this);
57 !
1556
          if(info.flags & CLAP_AUDIO_PORT_IS_MAIN)
57 !
1557
          {
1558
            outlet->setPropagate(true);
57 !
1559
          }
57 ✔
1560
          m_outlets.push_back(outlet);
57 !
1561
        }
57 ✔
1562

1563
        m_plugin->m_audio_outs.push_back(info);
61 ✔
1564
        cur_outlet++;
61 ✔
1565
      }
61 ✔
1566
    }
61 ✔
1567
  }
61 ✔
1568

1569
  // Get note ports extension
1570
  m_plugin->m_midi_ins.clear();
69 ✔
1571
  m_plugin->m_midi_outs.clear();
69 ✔
1572
  auto note_ports = (const clap_plugin_note_ports_t*)m_plugin->plugin->get_extension(
138 ✔
1573
      m_plugin->plugin, CLAP_EXT_NOTE_PORTS);
69 ✔
1574
  if(note_ports)
69 ✔
1575
  {
1576
    uint32_t input_count = note_ports->count(m_plugin->plugin, true);
8 ✔
1577
    for(uint32_t i = 0; i < input_count; ++i)
16 ✔
1578
    {
1579
      clap_note_port_info_t info{};
8 ✔
1580
      if(note_ports->get(m_plugin->plugin, i, true, &info))
8 !
1581
      {
1582
        if(!loading)
8 ✔
1583
        {
1584
          QString name = clap_safe_name(
6 !
1585
              info.name, input_count == 1 ? QStringLiteral("MIDI In")
6 !
1586
                                          : QStringLiteral("MIDI In %1").arg(i + 1));
×
1587
          if(i == 0 && name.toLower() == "midi input")
6 !
1588
            name = "MIDI In";
×
1589
          auto inlet = new Process::MidiInlet(
12 !
1590
              name, Id<Process::Port>(getStrongId(m_inlets)), this);
6 !
1591
          m_inlets.push_back(inlet);
6 !
1592
        }
6 ✔
1593

1594
        m_plugin->m_midi_ins.push_back(info);
8 ✔
1595
        cur_inlet++;
8 ✔
1596
      }
8 ✔
1597
    }
8 ✔
1598
    uint32_t output_count = note_ports->count(m_plugin->plugin, false);
8 ✔
1599
    for(uint32_t i = 0; i < output_count; ++i)
9 ✔
1600
    {
1601
      clap_note_port_info_t info{};
1 ✔
1602
      if(note_ports->get(m_plugin->plugin, i, false, &info))
1 !
1603
      {
1604
        if(!loading)
1 !
1605
        {
1606
          QString name = clap_safe_name(
1 !
1607
              info.name, output_count == 1 ? QStringLiteral("MIDI Out")
1 !
1608
                                           : QStringLiteral("MIDI Out %1").arg(i + 1));
×
1609
          if(i == 0 && name.toLower() == "midi output")
1 !
1610
            name = "MIDI Out";
×
1611
          auto outlet = new Process::MidiOutlet(
2 !
1612
              name, Id<Process::Port>(getStrongId(m_outlets)), this);
1 !
1613
          m_outlets.push_back(outlet);
1 !
1614
        }
1 ✔
1615

1616
        m_plugin->m_midi_outs.push_back(info);
1 ✔
1617
        cur_outlet++;
1 ✔
1618
      }
1 ✔
1619
    }
1 ✔
1620
  }
8 ✔
1621

1622
  // Get params extension
1623
  auto params = (const clap_plugin_params_t*)m_plugin->plugin->get_extension(
138 ✔
1624
      m_plugin->plugin, CLAP_EXT_PARAMS);
69 ✔
1625
  if(params)
69 ✔
1626
  {
1627
    uint32_t param_count = params->count(m_plugin->plugin);
61 ✔
1628
    for(uint32_t i = 0; i < param_count; ++i)
253 ✔
1629
    {
1630
      clap_param_info_t info{};
192 ✔
1631
      if(params->get_info(m_plugin->plugin, i, &info))
192 !
1632
      {
1633
        if(info.flags & CLAP_PARAM_IS_HIDDEN)
192 ✔
1634
          continue;
42 ✔
1635
        // A control finds its parameter by its rank among the writable
1636
        // parameters, an outlet among the read-only ones
1637
        const int index = int(
150 ✔
1638
            info.flags & CLAP_PARAM_IS_READONLY ? m_plugin->m_parameters_outs.size()
150 ✔
1639
                                                : m_plugin->m_parameters_ins.size());
107 ✔
1640
        if(!(info.flags & CLAP_PARAM_IS_READONLY))
150 ✔
1641
        {
1642
          if(!loading)
107 ✔
1643
          {
1644
            const QString param_name = clap_safe_name(
93 ✔
1645
                info.name, QStringLiteral("Param %1").arg(i + 1));
93 !
1646
            Process::ControlInlet* inlet{};
93 ✔
1647
            if(info.flags & CLAP_PARAM_IS_STEPPED)
93 ✔
1648
              inlet = new Process::IntSlider(
10 !
1649
                  param_name, Id<Process::Port>(getStrongId(m_inlets)), this);
5 !
1650
            else
1651
              inlet = new Process::FloatSlider(
176 !
1652
                  param_name, Id<Process::Port>(getStrongId(m_inlets)), this);
88 !
1653

1654
            setupControlInlet(*params, info, index, inlet);
93 !
1655

1656
            m_inlets.push_back(inlet);
93 !
1657
          }
93 ✔
1658
          else
1659
          {
1660
            setupControlInlet(
14 ✔
1661
                *params, info, index,
14 ✔
1662
                qobject_cast<Process::ControlInlet*>(m_inlets[cur_inlet]));
14 ✔
1663
          }
1664

1665
          // Store parameter info for executor
1666
          m_plugin->m_parameters_ins.push_back(info);
107 ✔
1667
          cur_inlet++;
107 ✔
1668
        }
107 ✔
1669
        else
1670
        {
1671
          if(!loading)
43 !
1672
          {
1673
            const QString param_name = clap_safe_name(
43 ✔
1674
                info.name, QStringLiteral("Out %1").arg(i + 1));
43 !
1675
            Process::ControlOutlet* port{};
43 ✔
1676
            port = new Process::Bargraph(
86 !
1677
                param_name, Id<Process::Port>(getStrongId(m_outlets)), this);
43 !
1678

1679
            setupControlOutlet(*params, info, index, port);
43 !
1680

1681
            m_outlets.push_back(port);
43 !
1682
          }
43 ✔
1683
          else
1684
          {
1685
            setupControlOutlet(
×
1686
                *params, info, index,
×
1687
                qobject_cast<Process::ControlOutlet*>(m_outlets[cur_outlet]));
×
1688
          }
1689

1690
          // Store parameter info for executor
1691
          m_plugin->m_parameters_outs.push_back(info);
43 ✔
1692
          cur_outlet++;
43 ✔
1693
        }
1694
      }
150 ✔
1695
    }
150 ✔
1696
  }
61 ✔
1697

1698
  m_plugin->param_outs_by_id.clear();
69 ✔
1699
  m_plugin->param_outs_by_id.reserve(m_plugin->m_parameters_outs.size());
69 ✔
1700
  for(std::size_t i = 0; i < m_plugin->m_parameters_outs.size(); ++i)
112 ✔
1701
    m_plugin->param_outs_by_id.emplace(
86 ✔
1702
        m_plugin->m_parameters_outs[i].id, static_cast<std::uint32_t>(i));
43 ✔
1703

1704
  inletsChanged();
69 ✔
1705
  outletsChanged();
69 ✔
1706
}
70 ✔
1707

1708
void Model::mapExternalFiles(Process::ExternalFileMap& map)
×
1709
{
1710
  Process::ProcessModel::mapExternalFiles(map);
×
1711

1712
  // Same as VST3: the plug-in binary has to exist on the other machine, it
1713
  // cannot travel with the project. Report it.
1714
  if(!m_pluginPath.isEmpty())
×
1715
    map.readOnly(m_pluginPath, score::FileKind::Plugin);
×
1716
}
×
1717

1718
QString Model::effect() const noexcept
95 ✔
1719
{
1720
  if(m_pluginPath.isEmpty() || m_pluginId.isEmpty())
95 !
1721
    return {};
5 ✔
1722
  return m_pluginPath + QStringLiteral(":::") + m_pluginId;
90 !
1723
}
95 ✔
1724

1725
Process::ProcessFlags Model::flags() const noexcept
605 ✔
1726
{
1727
  auto flags = Metadata<Process::ProcessFlags_k, Model>::get();
605 !
1728
  return flags;
605 ✔
1729
}
1730

1731
void Model::loadPreset(const Process::Preset& preset)
3 ✔
1732
{
1733
  if(!m_plugin || !m_plugin->plugin)
3 !
1734
    return;
×
1735

1736
  const rapidjson::Document doc = readJson(preset.data);
3 ✔
1737
  if(!doc.IsObject())
3 !
1738
    return;
×
1739
  auto obj = doc.GetObject();
3 !
1740

1741
  // Try to load using CLAP state (preferred method)
1742
  if(auto it = obj.FindMember("State"); it != obj.MemberEnd())
3 !
1743
  {
1744
    QByteArray data = QByteArray::fromBase64(JsonValue{it->value}.toByteArray());
3 !
1745
    if(!data.isEmpty())
3 !
1746
    {
1747
      // Get state extension and load the state
1748
      auto state = (const clap_plugin_state_t*)m_plugin->plugin->get_extension(
6 !
1749
          m_plugin->plugin, CLAP_EXT_STATE);
3 ✔
1750
      if(state)
3 !
1751
      {
1752
        struct stream_context
1753
        {
1754
          const char* data;
1755
          size_t size;
1756
          size_t pos;
1757
        };
1758

1759
        stream_context ctx{data.constData(), static_cast<size_t>(data.size()), 0};
3 ✔
1760

1761
        clap_istream_t stream{};
3 ✔
1762
        stream.ctx = &ctx;
3 ✔
1763
        stream.read
3 ✔
1764
            = [](const clap_istream_t* stream, void* buffer, uint64_t size) -> int64_t {
9 ✔
1765
          auto* ctx = static_cast<stream_context*>(stream->ctx);
3 ✔
1766
          if(ctx->pos >= ctx->size)
3 !
1767
            return 0;
×
1768

1769
          uint64_t to_read = std::min(int64_t(size), int64_t(ctx->size - ctx->pos));
3 ✔
1770
          std::memcpy(buffer, ctx->data + ctx->pos, to_read);
3 ✔
1771
          ctx->pos += to_read;
3 ✔
1772
          return static_cast<int64_t>(to_read);
3 ✔
1773
        };
3 ✔
1774

1775
        // Load the state, then show the values it set: the controls are in
1776
        // the order of the parameters, their ids are score's
1777
        if(state->load(m_plugin->plugin, &stream))
3 !
1778
        {
1779
          refreshParamValues();
3 !
1780
          presetLoaded();
3 !
1781
        }
3 ✔
1782
      }
3 ✔
1783
    }
3 ✔
1784
  }
3 ✔
1785
  // Try preset load extension (for file-based and builtin presets)
1786
  else if(auto loc_it = obj.FindMember("PresetLocation"); loc_it != obj.MemberEnd())
×
1787
  {
1788
    auto preset_load = (const clap_plugin_preset_load_t*)m_plugin->plugin->get_extension(
×
1789
        m_plugin->plugin, CLAP_EXT_PRESET_LOAD);
×
1790
    if(!preset_load)
×
1791
      preset_load = (const clap_plugin_preset_load_t*)m_plugin->plugin->get_extension(
×
1792
          m_plugin->plugin, "clap.preset-load.draft/2");
×
1793
    if(preset_load)
×
1794
    {
1795
      QString location = JsonValue{loc_it->value}.toString();
×
1796
      QString load_key;
×
1797
      uint32_t location_kind = CLAP_PRESET_DISCOVERY_LOCATION_FILE; // Default to file
×
1798

1799
      // Check for location kind (for builtin presets)
1800
      if(auto kind_it = obj.FindMember("LocationKind"); kind_it != obj.MemberEnd())
×
1801
      {
1802
        location_kind = static_cast<uint32_t>(JsonValue{kind_it->value}.toInt());
×
1803
      }
×
1804

1805
      if(auto key_it = obj.FindMember("LoadKey"); key_it != obj.MemberEnd())
×
1806
      {
1807
        load_key = JsonValue{key_it->value}.toString();
×
1808
      }
×
1809

1810
      // A file's path; nothing for a preset inside the plug-in
1811
      const QByteArray location_utf8 = location.toUtf8();
×
1812
      const QByteArray key_utf8 = load_key.toUtf8();
×
1813
      const char* location_str
×
1814
          = location_kind == CLAP_PRESET_DISCOVERY_LOCATION_FILE && !location.isEmpty()
×
1815
                ? location_utf8.constData()
×
1816
                : nullptr;
1817

1818
      if(preset_load->from_location(
×
1819
             m_plugin->plugin, location_kind, location_str,
×
1820
             load_key.isEmpty() ? nullptr : key_utf8.constData()))
×
1821
      {
1822
        refreshParamValues();
×
1823
        presetLoaded();
×
1824
      }
×
1825
    }
×
1826
  }
×
1827
}
3 ✔
1828

1829
bool Model::presetMatches(const Process::Preset& preset) const noexcept
6 ✔
1830
{
1831
  return preset.key.key == concreteKey()
12 !
1832
         && (preset.key.effect.isEmpty() || preset.key.effect == effect());
6 !
1833
}
1834

1835
Process::Preset Model::savePreset() const noexcept
6 ✔
1836
{
1837
  Process::Preset p;
6 ✔
1838
  p.name = this->metadata().getName();
6 ✔
1839
  p.key.key = this->concreteKey();
6 ✔
1840
  p.key.effect = this->effect();
6 ✔
1841

1842
  if(!m_plugin || !m_plugin->plugin)
6 !
1843
  {
1844
    p.data = "{}";
×
1845
    return p;
×
1846
  }
1847

1848
  // Save using CLAP state extension
1849
  QByteArray data = readCLAPState(*m_plugin->plugin);
6 !
1850

1851
  JSONReader r;
6 !
1852
  r.stream.StartObject();
6 !
1853
  r.obj["State"] = data.toBase64();
6 !
1854
  r.stream.EndObject();
6 !
1855
  p.data = r.toByteArray();
6 !
1856
  return p;
6 ✔
1857
}
6 ✔
1858

1859
std::vector<Process::Preset> Model::builtinPresets() const noexcept
2 ✔
1860
{
1861
  // A plug-in can index thousands of preset files: once per instance
1862
  if(!m_builtinPresets)
2 !
1863
    m_builtinPresets = discoverPresets();
2 ✔
1864
  return *m_builtinPresets;
2 !
1865
}
1866

1867
std::vector<Process::Preset> Model::discoverPresets() const noexcept
2 ✔
1868
{
1869
  std::vector<Process::Preset> presets;
2 ✔
1870

1871
  if(!m_plugin || !m_plugin->plugin || !m_plugin->entry)
2 !
1872
    return presets;
×
1873

1874
  auto preset_discovery_factory = static_cast<const clap_preset_discovery_factory_t*>(
2 ✔
1875
      m_plugin->entry->get_factory(CLAP_PRESET_DISCOVERY_FACTORY_ID));
2 !
1876
  if(!preset_discovery_factory)
2 ✔
1877
    preset_discovery_factory = static_cast<const clap_preset_discovery_factory_t*>(
1 ✔
1878
        m_plugin->entry->get_factory("clap.preset-discovery-factory/draft-2"));
1 !
1879
  // Some entries give their plug-in factory for any id
1880
  if(!preset_discovery_factory
2 ✔
1881
     || static_cast<const void*>(preset_discovery_factory)
2 !
1882
            == m_plugin->entry->get_factory(CLAP_PLUGIN_FACTORY_ID))
1 !
1883
    return presets;
2 ✔
1884

1885
  // What the providers declare, copied: their structs only live during the
1886
  // call that declares them
1887
  struct location
1888
  {
1889
    uint32_t kind{};
1890
    QString name;
1891
    QString path;
1892
  };
1893
  struct collector_t
1894
  {
1895
    std::vector<Process::Preset>* target_presets{};
1896
    UuidKey<Process::ProcessModel> process_key;
1897
    QString effect_name;
1898
    std::vector<location> locations;
1899
    QStringList extensions;
1900
    // The location being read, for the presets it gives
1901
    uint32_t kind{};
1902
    QString path;
1903
    QString category;
1904
  };
1905
  collector_t collector{&presets, this->concreteKey(), this->effect()};
×
1906

1907
  clap_preset_discovery_indexer_t indexer{};
×
1908
  indexer.clap_version = CLAP_VERSION;
×
1909
  indexer.name = "ossia score";
×
1910
  indexer.vendor = "ossia.io";
×
1911
  indexer.url = "https://ossia.io";
×
1912
  indexer.version = SCORE_TAG_NO_V;
×
1913
  indexer.indexer_data = &collector;
×
1914

1915
  indexer.declare_filetype = [](const clap_preset_discovery_indexer_t* indexer,
×
1916
                                const clap_preset_discovery_filetype_t* filetype) -> bool {
1917
    auto& self = *(collector_t*)indexer->indexer_data;
×
1918
    if(filetype && filetype->file_extension && *filetype->file_extension)
×
1919
      self.extensions.push_back(QString::fromUtf8(filetype->file_extension));
×
1920
    return true;
×
1921
  };
×
1922
  indexer.declare_location = [](const clap_preset_discovery_indexer_t* indexer,
×
1923
                                const clap_preset_discovery_location_t* loc) -> bool {
1924
    auto& self = *(collector_t*)indexer->indexer_data;
×
1925
    if(!loc)
×
1926
      return false;
×
1927
    self.locations.push_back(
×
1928
        {loc->kind, QString::fromUtf8(loc->name ? loc->name : ""),
×
1929
         QString::fromUtf8(loc->location ? loc->location : "")});
×
1930
    return true;
×
1931
  };
×
1932
  indexer.declare_soundpack
×
1933
      = [](const clap_preset_discovery_indexer_t*,
×
1934
           const clap_preset_discovery_soundpack_t*) -> bool { return true; };
×
1935
  indexer.get_extension
×
1936
      = [](const clap_preset_discovery_indexer_t*, const char*) -> const void* {
×
1937
    return nullptr;
×
1938
  };
1939

1940
  clap_preset_discovery_metadata_receiver_t receiver{};
×
1941
  receiver.receiver_data = &collector;
×
1942
  receiver.on_error = [](const clap_preset_discovery_metadata_receiver_t*, int32_t,
×
1943
                         const char* error_message) {
1944
    qWarning() << "CLAP preset discovery error:"
×
1945
               << (error_message ? error_message : "Unknown error");
×
1946
  };
×
1947
  receiver.begin_preset = [](const clap_preset_discovery_metadata_receiver_t* r,
×
1948
                             const char* name, const char* load_key) -> bool {
1949
    auto& self = *static_cast<collector_t*>(r->receiver_data);
×
1950

1951
    Process::Preset preset;
×
1952
    preset.name = QString::fromUtf8(name && *name ? name : "Unnamed Preset");
×
1953
    preset.category = self.category;
×
1954
    preset.key.key = self.process_key;
×
1955
    preset.key.effect = self.effect_name;
×
1956

1957
    // What preset-load needs to find it again
1958
    JSONReader w;
×
1959
    w.stream.StartObject();
×
1960
    w.obj["LocationKind"] = static_cast<int>(self.kind);
×
1961
    w.obj["PresetLocation"] = self.path;
×
1962
    if(load_key)
×
1963
      w.obj["LoadKey"] = QString::fromUtf8(load_key);
×
1964
    w.stream.EndObject();
×
1965
    preset.data = w.toByteArray();
×
1966

1967
    self.target_presets->push_back(std::move(preset));
×
1968
    return true;
1969
  };
×
1970
  // Metadata score does not show
1971
  receiver.add_plugin_id
×
1972
      = [](const clap_preset_discovery_metadata_receiver_t*,
×
1973
           const clap_universal_plugin_id_t*) { };
×
1974
  receiver.set_soundpack_id
×
1975
      = [](const clap_preset_discovery_metadata_receiver_t*, const char*) { };
×
1976
  receiver.set_flags = [](const clap_preset_discovery_metadata_receiver_t*, uint32_t) { };
×
1977
  receiver.add_creator = [](const clap_preset_discovery_metadata_receiver_t*, const char*) { };
×
1978
  receiver.set_description = [](const clap_preset_discovery_metadata_receiver_t* r,
×
1979
                                const char* description) {
1980
    auto& self = *static_cast<collector_t*>(r->receiver_data);
×
1981
    if(description && !self.target_presets->empty())
×
1982
      self.target_presets->back().description = QString::fromUtf8(description);
×
1983
  };
×
1984
  receiver.set_timestamps
×
1985
      = [](const clap_preset_discovery_metadata_receiver_t*, clap_timestamp,
×
1986
           clap_timestamp) { };
×
1987
  receiver.add_feature = [](const clap_preset_discovery_metadata_receiver_t*, const char*) { };
×
1988
  receiver.add_extra_info
×
1989
      = [](const clap_preset_discovery_metadata_receiver_t*, const char*, const char*) { };
×
1990

1991
  const uint32_t provider_count = preset_discovery_factory->count(preset_discovery_factory);
×
1992
  for(uint32_t i = 0; i < provider_count; ++i)
×
1993
  {
1994
    auto desc = preset_discovery_factory->get_descriptor(preset_discovery_factory, i);
×
1995
    if(!desc)
×
1996
      continue;
×
1997
    collector.locations.clear();
×
1998
    collector.extensions.clear();
×
1999
    auto provider
×
2000
        = preset_discovery_factory->create(preset_discovery_factory, &indexer, desc->id);
×
2001
    if(!provider)
×
2002
      continue;
×
2003

2004
    if(provider->init && provider->init(provider) && provider->get_metadata)
×
2005
    {
2006
      for(const auto& loc : collector.locations)
×
2007
      {
2008
        if(loc.kind == CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN)
×
2009
        {
2010
          collector.kind = loc.kind;
×
2011
          collector.path.clear();
×
2012
          collector.category.clear();
×
2013
          provider->get_metadata(provider, loc.kind, nullptr, &receiver);
×
2014
          continue;
×
2015
        }
2016

2017
        // A file location is a file, or a folder the host walks: each file
2018
        // of a declared type is asked about, in a folder named after where it is
2019
        const auto read = [&](const QString& file, const QString& category) {
×
2020
          collector.kind = CLAP_PRESET_DISCOVERY_LOCATION_FILE;
×
2021
          collector.path = file;
×
2022
          collector.category = category;
×
2023
          const QByteArray utf8 = file.toUtf8();
×
2024
          provider->get_metadata(provider, loc.kind, utf8.constData(), &receiver);
×
2025
        };
×
2026
        const QFileInfo root{loc.path};
×
2027
        if(root.isFile())
×
2028
        {
2029
          read(root.absoluteFilePath(), loc.name);
×
2030
          continue;
×
2031
        }
2032
        if(!root.isDir())
×
2033
          continue;
×
2034
        QStringList filters;
×
2035
        for(const auto& ext : collector.extensions)
×
2036
          filters.push_back("*." + ext);
×
2037
        QDirIterator it{
×
2038
            root.absoluteFilePath(), filters, QDir::Files | QDir::Readable,
×
2039
            QDirIterator::Subdirectories | QDirIterator::FollowSymlinks};
×
2040
        const QDir base{root.absoluteFilePath()};
×
2041
        while(it.hasNext())
×
2042
        {
2043
          const QString file = it.next();
×
2044
          QString sub = QFileInfo{base.relativeFilePath(file)}.path();
×
2045
          if(sub == ".")
×
2046
            sub.clear();
×
2047
          read(file, sub.isEmpty() ? loc.name : loc.name + "/" + sub);
×
2048
        }
×
2049
      }
×
2050
    }
×
2051

2052
    if(provider->destroy)
×
2053
      provider->destroy(provider);
×
2054
  }
×
2055

2056
  return presets;
×
2057
}
2 ✔
2058

2059
namespace
2060
{
2061
// Find and update the i-th ControlInlet / ControlOutlet on a Model under
2062
// the currentlyReadingValues guard, so the GUI handler does not echo the
2063
// value back into a fresh params->flush() call.
2064
template <typename Port>
2065
void apply_value_at(Model& self, std::size_t idx, double v)
×
2066
{
2067
  std::size_t found = 0;
×
2068
  if constexpr(std::is_same_v<Port, Process::ControlInlet>)
2069
  {
2070
    for(auto* inlet : self.inlets())
×
2071
    {
2072
      if(auto* ctl = qobject_cast<Process::ControlInlet*>(inlet))
×
2073
      {
2074
        if(found == idx)
×
2075
        {
2076
          self.currentlyReadingValues = true;
×
2077
          ctl->setValue(v);
×
2078
          self.currentlyReadingValues = false;
×
2079
          return;
×
2080
        }
2081
        ++found;
×
2082
      }
×
2083
    }
2084
  }
2085
  else
2086
  {
2087
    for(auto* outlet : self.outlets())
×
2088
    {
2089
      if(auto* ctl = qobject_cast<Process::ControlOutlet*>(outlet))
×
2090
      {
2091
        if(found == idx)
×
2092
        {
2093
          self.currentlyReadingValues = true;
×
2094
          ctl->setValue(v);
×
2095
          self.currentlyReadingValues = false;
×
2096
          return;
×
2097
        }
2098
        ++found;
×
2099
      }
×
2100
    }
2101
  }
2102
}
×
2103
} // namespace
2104

2105
void Model::refreshParamValues()
16 ✔
2106
{
2107
  if(!m_plugin || !m_plugin->plugin)
16 !
2108
    return;
×
2109
  auto* plugin = m_plugin->plugin;
16 ✔
2110
  auto params = m_plugin->ext_params;
16 ✔
2111
  if(!params || !params->get_value)
16 !
2112
    return;
×
2113

2114
  std::size_t inlet_idx = 0;
16 ✔
2115
  for(auto* inlet : inlets())
91 ✔
2116
  {
2117
    if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
75 ✔
2118
    {
2119
      if(inlet_idx < m_plugin->m_parameters_ins.size())
59 ✔
2120
      {
2121
        const auto& info = m_plugin->m_parameters_ins[inlet_idx];
45 ✔
2122
        double v = 0.0;
45 ✔
2123
        if(params->get_value(plugin, info.id, &v))
45 !
2124
        {
2125
          currentlyReadingValues = true;
45 ✔
2126
          control->setValue(v);
45 !
2127
          currentlyReadingValues = false;
45 ✔
2128
        }
45 ✔
2129
      }
45 ✔
2130
      ++inlet_idx;
59 ✔
2131
    }
59 ✔
2132
  }
2133

2134
  std::size_t outlet_idx = 0;
16 ✔
2135
  for(auto* outlet : outlets())
33 ✔
2136
  {
2137
    if(auto* control = qobject_cast<Process::ControlOutlet*>(outlet))
17 ✔
2138
    {
2139
      if(outlet_idx < m_plugin->m_parameters_outs.size())
1 !
2140
      {
2141
        const auto& info = m_plugin->m_parameters_outs[outlet_idx];
1 ✔
2142
        double v = 0.0;
1 ✔
2143
        if(params->get_value(plugin, info.id, &v))
1 !
2144
        {
2145
          currentlyReadingValues = true;
1 ✔
2146
          control->setValue(v);
1 !
2147
          currentlyReadingValues = false;
1 ✔
2148
        }
1 ✔
2149
      }
1 ✔
2150
      ++outlet_idx;
1 ✔
2151
    }
1 ✔
2152
  }
2153
}
16 ✔
2154

2155
bool Model::refreshParamInfoIfStable()
1 ✔
2156
{
2157
  if(!m_plugin || !m_plugin->plugin)
1 !
2158
    return true;
×
2159
  auto* plugin = m_plugin->plugin;
1 ✔
2160
  auto params = m_plugin->ext_params;
1 ✔
2161
  if(!params || !params->count || !params->get_info)
1 !
2162
    return true;
×
2163

2164
  // The hidden parameters have no port: only the shown ones are compared
2165
  const uint32_t new_count = params->count(plugin);
1 ✔
2166
  std::size_t in_idx = 0, out_idx = 0;
1 ✔
2167
  for(uint32_t i = 0; i < new_count; ++i)
4 ✔
2168
  {
2169
    clap_param_info_t info{};
3 ✔
2170
    if(!params->get_info(plugin, i, &info))
3 !
2171
      return false;
×
2172
    if(info.flags & CLAP_PARAM_IS_HIDDEN)
3 ✔
2173
      continue;
1 ✔
2174
    if(!(info.flags & CLAP_PARAM_IS_READONLY))
2 ✔
2175
    {
2176
      if(in_idx >= m_plugin->m_parameters_ins.size())
1 !
2177
        return false;
×
2178
      if(m_plugin->m_parameters_ins[in_idx].id != info.id)
1 !
2179
        return false;
×
2180
      m_plugin->m_parameters_ins[in_idx] = info;
1 ✔
2181
      ++in_idx;
1 ✔
2182
    }
1 ✔
2183
    else
2184
    {
2185
      if(out_idx >= m_plugin->m_parameters_outs.size())
1 !
2186
        return false;
×
2187
      if(m_plugin->m_parameters_outs[out_idx].id != info.id)
1 !
2188
        return false;
×
2189
      m_plugin->m_parameters_outs[out_idx] = info;
1 ✔
2190
      ++out_idx;
1 ✔
2191
    }
2192
  }
2 ✔
2193
  if(in_idx != m_plugin->m_parameters_ins.size()
1 ✔
2194
     || out_idx != m_plugin->m_parameters_outs.size())
1 !
2195
    return false;
×
2196

2197
  // Don't re-invoke setupControlInlet: it would duplicate valueChanged connections.
2198
  std::size_t inlet_idx = 0, outlet_idx = 0;
1 ✔
2199
  for(auto* inlet : inlets())
3 ✔
2200
  {
2201
    if(auto* ctl = qobject_cast<Process::ControlInlet*>(inlet))
2 ✔
2202
    {
2203
      if(inlet_idx < m_plugin->m_parameters_ins.size())
1 !
2204
      {
2205
        const auto& info = m_plugin->m_parameters_ins[inlet_idx];
1 ✔
2206
        ctl->setName(clap_safe_name(
2 !
2207
            info.name, QStringLiteral("Param %1").arg(inlet_idx + 1)));
1 !
2208
        ctl->setDomain(ossia::make_domain(info.min_value, info.max_value));
1 !
2209
      }
1 ✔
2210
      ++inlet_idx;
1 ✔
2211
    }
1 ✔
2212
  }
2213
  for(auto* outlet : outlets())
3 ✔
2214
  {
2215
    if(auto* ctl = qobject_cast<Process::ControlOutlet*>(outlet))
2 ✔
2216
    {
2217
      if(outlet_idx < m_plugin->m_parameters_outs.size())
1 !
2218
      {
2219
        const auto& info = m_plugin->m_parameters_outs[outlet_idx];
1 ✔
2220
        ctl->setName(clap_safe_name(
2 !
2221
            info.name, QStringLiteral("Out %1").arg(outlet_idx + 1)));
1 !
2222
        ctl->setDomain(ossia::make_domain(info.min_value, info.max_value));
1 !
2223
      }
1 ✔
2224
      ++outlet_idx;
1 ✔
2225
    }
1 ✔
2226
  }
2227
  return true;
1 ✔
2228
}
1 ✔
2229

2230
void Model::onParamRescan(clap_param_rescan_flags flags)
14 ✔
2231
{
2232
  if(!m_plugin || !m_plugin->plugin)
14 !
2233
    return;
×
2234

2235
  // RESCAN_ALL needs deactivation; defer if executing.
2236
  if((flags & CLAP_PARAM_RESCAN_ALL) && executing())
14 !
2237
  {
2238
    m_pendingRescanFlags |= flags;
×
2239
    return;
×
2240
  }
2241

2242
  // RESCAN_TEXT: nothing cached, display strings fetched on demand.
2243
  (void)CLAP_PARAM_RESCAN_TEXT;
2244

2245
  if(flags & CLAP_PARAM_RESCAN_INFO)
14 ✔
2246
  {
2247
    if(!refreshParamInfoIfStable())
1 !
2248
      flags |= CLAP_PARAM_RESCAN_ALL;
×
2249
  }
1 ✔
2250

2251
  if(flags & CLAP_PARAM_RESCAN_ALL)
14 !
2252
  {
2253
    if(refreshParamInfoIfStable())
×
2254
    {
2255
      refreshParamValues();
×
2256
      return;
×
2257
    }
2258
    // FIXME score does not rebuild inlets dynamically (see VST2/VST3 backends).
2259
    qWarning() << "CLAP: parameter layout changed at runtime for"
×
2260
               << m_pluginId
×
2261
               << "— score doesn't yet rebuild inlets dynamically. "
×
2262
                  "Remove and re-add the plug-in to pick up the new "
2263
                  "parameter set.";
2264
    restartPlugin();
×
2265
    return;
×
2266
  }
2267

2268
  if(flags & CLAP_PARAM_RESCAN_VALUES)
14 ✔
2269
    refreshParamValues();
13 ✔
2270
}
14 ✔
2271

2272
void Model::markStateDirty()
×
2273
{
2274
  // Plug-ins (Vital, Surge XT) fire this on every UI tweak; debounce.
2275
  constexpr int kStateDirtyDebounceMs = 400;
×
2276

2277
  if(!m_stateDirtyTimer)
×
2278
  {
2279
    m_stateDirtyTimer = new QTimer(this);
×
2280
    m_stateDirtyTimer->setSingleShot(true);
×
2281
    m_stateDirtyTimer->setInterval(kStateDirtyDebounceMs);
×
2282
    connect(m_stateDirtyTimer, &QTimer::timeout, this, [this] {
×
2283
      if(!m_plugin || !m_plugin->plugin)
×
2284
        return;
×
2285
      QByteArray blob = Clap::readCLAPState(*m_plugin->plugin);
×
2286
      if(!blob.isEmpty())
×
2287
        stateSnapshotChanged(blob);
×
2288
    });
×
2289
  }
×
2290
  m_stateDirtyTimer->start();
×
2291
}
×
2292

2293
void Model::flushFromPluginToHost()
1 ✔
2294
{
2295
  auto plugin = m_plugin->plugin;
1 ✔
2296
  if(!plugin)
1 !
2297
    return;
×
2298
  auto params
1 ✔
2299
      = (const clap_plugin_params_t*)plugin->get_extension(plugin, CLAP_EXT_PARAMS);
1 ✔
2300
  if(!params || !params->flush)
1 !
2301
    return;
×
2302
  // Active, the plug-in is flushed from the audio thread only: what it says
2303
  // comes back through its node
2304
  if(this->executing()
1 ✔
2305
     || m_plugin->state.load(std::memory_order_acquire) != PluginInstance::Inactive)
1 !
2306
    return;
1 ✔
2307

2308
  ParamInputCtx in_ctx; // empty
×
2309
  clap_input_events_t ip = make_input_events(in_ctx);
×
2310

2311
  clap_output_events_t op{
×
2312
      .ctx = this,
2313
      .try_push = [](const struct clap_output_events* list,
×
2314
                     const clap_event_header_t* event) -> bool {
2315
    auto* self = static_cast<Model*>(list->ctx);
×
2316
    if(!event || event->space_id != CLAP_CORE_EVENT_SPACE_ID)
×
2317
      return true;
×
2318
    if(event->type != CLAP_EVENT_PARAM_VALUE)
×
2319
      return true;
×
2320
    if(event->size < sizeof(clap_event_param_value_t))
×
2321
      return true;
×
2322

2323
    auto* pv = reinterpret_cast<const clap_event_param_value_t*>(event);
×
2324

2325
    std::size_t idx = 0;
×
2326
    for(auto& info : self->m_plugin->m_parameters_ins)
×
2327
    {
2328
      if(info.id == pv->param_id)
×
2329
      {
2330
        apply_value_at<Process::ControlInlet>(*self, idx, pv->value);
×
2331
        return true;
×
2332
      }
2333
      ++idx;
×
2334
    }
2335
    idx = 0;
×
2336
    for(auto& info : self->m_plugin->m_parameters_outs)
×
2337
    {
2338
      if(info.id == pv->param_id)
×
2339
      {
2340
        apply_value_at<Process::ControlOutlet>(*self, idx, pv->value);
×
2341
        return true;
×
2342
      }
2343
      ++idx;
×
2344
    }
2345
    return true;
×
2346
  }};
×
2347

2348
  params->flush(plugin, &ip, &op);
×
2349

2350
  // Plugins that update internal state silently (without pushing events
2351
  // through `out`) still expose fresh values via get_value(); poll them so
2352
  // the GUI mirrors the plugin state, for both writable and read-only params.
2353
  std::size_t inlet_idx = 0;
×
2354
  for(auto* inlet : inlets())
×
2355
  {
2356
    if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
×
2357
    {
2358
      if(inlet_idx < m_plugin->m_parameters_ins.size())
×
2359
      {
2360
        const auto& param_info = m_plugin->m_parameters_ins[inlet_idx];
×
2361
        double current_value = 0.0;
×
2362
        if(params->get_value(plugin, param_info.id, &current_value))
×
2363
        {
2364
          currentlyReadingValues = true;
×
2365
          control->setValue(current_value);
×
2366
          currentlyReadingValues = false;
×
2367
        }
×
2368
      }
×
2369
      inlet_idx++;
×
2370
    }
×
2371
  }
2372
  std::size_t outlet_idx = 0;
×
2373
  for(auto* outlet : outlets())
×
2374
  {
2375
    if(auto* control = qobject_cast<Process::ControlOutlet*>(outlet))
×
2376
    {
2377
      if(outlet_idx < m_plugin->m_parameters_outs.size())
×
2378
      {
2379
        const auto& param_info = m_plugin->m_parameters_outs[outlet_idx];
×
2380
        double current_value = 0.0;
×
2381
        if(params->get_value(plugin, param_info.id, &current_value))
×
2382
        {
2383
          currentlyReadingValues = true;
×
2384
          control->setValue(current_value);
×
2385
          currentlyReadingValues = false;
×
2386
        }
×
2387
      }
×
2388
      outlet_idx++;
×
2389
    }
×
2390
  }
2391
}
1 ✔
2392
}
2393

2394
template <>
2395
QString
2396
Process::EffectProcessFactory_T<Clap::Model>::customConstructionData() const noexcept
×
2397
{
2398
  return "";
×
2399
}
2400
template <>
2401
Process::Descriptor
2402
Process::EffectProcessFactory_T<Clap::Model>::descriptor(QString txt) const noexcept
81 ✔
2403
{
2404
  Process::Descriptor d;
81 !
2405

2406
  auto t = txt.split(":::");
81 !
2407
  if(t.size() != 2)
81 ✔
2408
    return d;
5 ✔
2409
  auto pluginPath = t[0];
76 !
2410
  auto pluginId = t[1];
76 !
2411

2412
  auto& plug = score::GUIAppContext().guiApplicationPlugin<Clap::ApplicationPlugin>();
76 !
2413
  for(const auto& plugin : plug.plugins())
84 ✔
2414
  {
2415
    if(plugin.path == pluginPath && plugin.id == pluginId)
24 !
2416
    {
2417
      d.author = plugin.vendor;
16 ✔
2418
      d.prettyName = plugin.name;
16 ✔
2419
      d.description = plugin.description;
16 ✔
2420
      d.documentationLink = plugin.manual_url;
16 !
2421
      if(d.documentationLink.isEmpty())
16 !
2422
        d.documentationLink = plugin.url;
16 !
2423
      if(d.documentationLink.isEmpty())
16 !
2424
        d.documentationLink = plugin.support_url;
16 !
2425
      d.tags = plugin.features;
16 ✔
2426
      break;
16 ✔
2427
    }
2428
  }
2429
  return d;
76 ✔
2430
}
81 ✔
2431
template <>
2432
Process::Descriptor Process::EffectProcessFactory_T<Clap::Model>::descriptor(
80 ✔
2433
    const Process::ProcessModel& d) const noexcept
2434
{
2435
  Process::Descriptor desc;
80 !
2436
  return descriptor(d.effect());
80 ✔
2437
}
80 ✔
2438

2439
template <>
2440
void DataStreamReader::read(const Clap::Model& proc)
5 ✔
2441
{
2442
  QByteArray state;
5 ✔
2443
  if(proc.m_plugin && proc.m_plugin->plugin)
5 !
2444
  {
2445
    state = Clap::readCLAPState(*proc.m_plugin->plugin);
5 !
2446
  }
5 ✔
2447

2448
  m_stream << proc.m_pluginPath << proc.m_pluginId << state;
5 !
2449

2450
  readPorts(*this, proc.m_inlets, proc.m_outlets);
5 !
2451
  insertDelimiter();
5 !
2452
}
5 ✔
2453

2454
template <>
2455
void DataStreamWriter::write(Clap::Model& proc)
2 ✔
2456
{
2457
  m_stream >> proc.m_pluginPath >> proc.m_pluginId >> proc.m_loadedState;
2 ✔
2458

2459
  writePorts(
2 ✔
2460
      *this, components.interfaces<Process::PortFactoryList>(), proc.m_inlets,
2 ✔
2461
      proc.m_outlets, &proc);
2 ✔
2462

2463
  checkDelimiter();
2 ✔
2464
}
2 ✔
2465

2466
template <>
2467
void JSONReader::read(const Clap::Model& proc)
4 ✔
2468
{
2469
  obj["PluginPath"] = proc.m_pluginPath;
4 ✔
2470
  obj["PluginId"] = proc.m_pluginId;
4 ✔
2471

2472
  // FIXME CLAP_STATE_CONTEXT_FOR_PROJECT
2473
  // Save plugin state
2474
  QByteArray state;
4 ✔
2475
  if(proc.m_plugin && proc.m_plugin->plugin)
4 !
2476
  {
2477
    state = Clap::readCLAPState(*proc.m_plugin->plugin);
4 !
2478
  }
4 ✔
2479
  obj["State"] = state.toBase64();
4 !
2480

2481
  readPorts(*this, proc.m_inlets, proc.m_outlets);
4 !
2482
}
4 ✔
2483

2484
template <>
2485
void JSONWriter::write(Clap::Model& proc)
2 ✔
2486
{
2487
  proc.m_pluginPath = obj["PluginPath"].toString();
2 ✔
2488
  proc.m_pluginId = obj["PluginId"].toString();
2 ✔
2489
  proc.m_loadedState = QByteArray::fromBase64(obj["State"].toByteArray());
2 !
2490

2491
  writePorts(
2 ✔
2492
      *this, components.interfaces<Process::PortFactoryList>(), proc.m_inlets,
2 ✔
2493
      proc.m_outlets, &proc);
2 ✔
2494
}
2 ✔
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