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

ossia / score / 40987115292

30 Oct 2026 01:27AM UTC coverage: 51.229% (+2.1%) from 49.178%
40987115292

push

github

jcelerier
avendish: main

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

179452 of 350293 relevant lines covered (51.23%)

175809.48 hits per line

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

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

3
#include "MidiEvents.hpp"
4
#include "Transport.hpp"
5

6
#include <Process/Dataflow/Port.hpp>
7
#include <Process/ExecutionContext.hpp>
8

9
#include <ossia/audio/audio_parameter.hpp>
10
#include <ossia/dataflow/execution_state.hpp>
11
#include <ossia/dataflow/graph_node.hpp>
12
#include <ossia/dataflow/port.hpp>
13
#include <ossia/detail/hash_map.hpp>
14
#include <ossia/detail/lockfree_queue.hpp>
15
#include <ossia/detail/nullable_variant.hpp>
16

17
#include <QCoreApplication>
18
#include <QDebug>
19
#include <QThread>
20
#include <QTimer>
21

22
#include <clap/ext/state.h>
23
#include <libremidi/detail/conversion.hpp>
24

25
#include <atomic>
26
#include <ranges>
27

28
#if defined(_WIN32)
29
#include <windows.h>
30
#else
31
#include <dlfcn.h>
32
#endif
33

34
namespace Clap
35
{
36
namespace
37
{
38
// Snapshot a plug-in's state via clap.state (returns empty if the plug-in
39
// doesn't implement the extension). [main-thread]
40
inline QByteArray snapshot_clap_state(const clap_plugin_t* plugin)
×
41
{
42
  QByteArray out;
×
43
  if(!plugin)
×
44
    return out;
×
45
  auto state = static_cast<const clap_plugin_state_t*>(
×
46
      plugin->get_extension(plugin, CLAP_EXT_STATE));
×
47
  if(!state || !state->save)
×
48
    return out;
×
49

50
  clap_ostream_t stream{};
×
51
  stream.ctx = &out;
×
52
  stream.write
×
53
      = [](const clap_ostream_t* s, const void* buf, uint64_t sz) -> int64_t {
×
54
    auto* b = static_cast<QByteArray*>(s->ctx);
×
55
    const auto old = b->size();
×
56
    b->resize(old + sz);
×
57
    std::memcpy(b->data() + old, buf, sz);
×
58
    return static_cast<int64_t>(sz);
×
59
  };
60

61
  if(!state->save(plugin, &stream))
×
62
    out.clear();
×
63
  return out;
×
64
}
×
65

66
// Apply a previously-captured snapshot to a fresh plug-in instance.
67
// [main-thread]
68
inline void apply_clap_state(const clap_plugin_t* plugin, const QByteArray& blob)
×
69
{
70
  if(!plugin || blob.isEmpty())
×
71
    return;
×
72
  auto state = static_cast<const clap_plugin_state_t*>(
×
73
      plugin->get_extension(plugin, CLAP_EXT_STATE));
×
74
  if(!state || !state->load)
×
75
    return;
×
76

77
  struct read_ctx
78
  {
79
    const char* data;
80
    qsizetype size;
81
    qsizetype pos;
82
  } ctx{blob.constData(), blob.size(), 0};
×
83

84
  clap_istream_t stream{};
×
85
  stream.ctx = &ctx;
×
86
  stream.read
×
87
      = [](const clap_istream_t* s, void* buf, uint64_t sz) -> int64_t {
×
88
    auto* c = static_cast<read_ctx*>(s->ctx);
×
89
    const auto remaining = c->size - c->pos;
×
90
    if(remaining <= 0)
×
91
      return 0;
×
92
    const auto to_read = std::min<int64_t>(sz, remaining);
×
93
    std::memcpy(buf, c->data + c->pos, to_read);
×
94
    c->pos += to_read;
×
95
    return to_read;
×
96
  };
×
97

98
  state->load(plugin, &stream);
×
99
}
×
100

101
// Per-voice slice; mirrors LV2's voice_control_value in score-plugin-lv2/LV2/Node.hpp.
102
inline std::optional<double>
103
voice_control_value(const ossia::value& val, std::size_t voice_idx) noexcept
×
104
{
105
  return ossia::apply_nonnull(
×
106
      [voice_idx](const auto& v) -> std::optional<double> {
×
107
    using T = std::decay_t<decltype(v)>;
108
    if constexpr(std::is_same_v<T, std::vector<ossia::value>>)
109
    {
110
      if(v.empty())
×
111
        return std::nullopt;
×
112
      const auto& elem = (voice_idx < v.size()) ? v[voice_idx] : v.back();
×
113
      return ossia::convert<double>(elem);
×
114
    }
115
    else if constexpr(std::is_same_v<T, ossia::vec2f>)
116
      return v[std::min<std::size_t>(voice_idx, 1)];
×
117
    else if constexpr(std::is_same_v<T, ossia::vec3f>)
118
      return v[std::min<std::size_t>(voice_idx, 2)];
×
119
    else if constexpr(std::is_same_v<T, ossia::vec4f>)
120
      return v[std::min<std::size_t>(voice_idx, 3)];
×
121
    else if constexpr(
122
        std::is_same_v<T, float> || std::is_same_v<T, double>
123
        || std::is_same_v<T, int> || std::is_same_v<T, bool>)
124
      return double(v);
×
125
    else
126
      return std::nullopt;
×
127
  },
×
128
      val.v);
×
129
}
130

131
inline bool is_vector_value(const ossia::value& val) noexcept
×
132
{
133
  return ossia::apply_nonnull([](const auto& v) noexcept -> bool {
×
134
    using T = std::decay_t<decltype(v)>;
135
    return std::is_same_v<T, std::vector<ossia::value>>
×
136
           || std::is_same_v<T, ossia::vec2f>
137
           || std::is_same_v<T, ossia::vec3f>
138
           || std::is_same_v<T, ossia::vec4f>;
139
  }, val.v);
×
140
}
141
}
142

143
static auto dummy_audio_buffer() noexcept
×
144
{
145
  clap_audio_buffer_t buffer{};
×
146
  buffer.data32 = nullptr;
×
147
  buffer.data64 = nullptr;
×
148
  buffer.channel_count = 0;
×
149
  buffer.latency = 0;
×
150
  buffer.constant_mask = 0;
×
151
  return buffer;
×
152
}
153

154
struct event_storage
155
{
156
  std::vector<clap_event_midi_t> midi_events;
157
  std::vector<clap_event_midi2_t> midi2_events;
158
  std::vector<clap_event_note_t> note_events;
159
  std::vector<clap_event_param_value_t> param_events;
160
  // Sysex events captured from plug-in output. The CLAP spec says
161
  // clap_event_midi_sysex_t.buffer is only valid for the duration of
162
  // try_push, so we copy each payload into sysex_data and rewrite the
163
  // event to point at our copy.
164
  std::vector<clap_event_midi_sysex_t> sysex_events;
165
  std::vector<std::vector<uint8_t>> sysex_data;
166
  std::vector<clap_event_header_t*> all_events;
167

168
  void clear()
×
169
  {
170
    midi_events.clear();
×
171
    midi2_events.clear();
×
172
    note_events.clear();
×
173
    param_events.clear();
×
174
    sysex_events.clear();
×
175
    sysex_data.clear();
×
176
    all_events.clear();
×
177
  }
×
178
};
179

180
class clap_node_base : public ossia::graph_node
181
{
182
public:
183
  std::shared_ptr<Clap::PluginHandle> handle;
184
  explicit clap_node_base(const Clap::Model& proc)
×
185
      : handle{proc.handle()}
×
186
      , m_param_ins{handle->m_parameters_ins}
×
187
      , m_param_outs{handle->m_parameters_outs}
×
188
      , m_midi_ins{handle->m_midi_ins}
×
189
      , m_midi_outs{handle->m_midi_outs}
×
190
      , m_param_out_index{handle->param_outs_by_id}
×
191
  {
×
192
    set_not_fp_safe();
×
193
    midi_ins.reserve(m_midi_ins.size());
×
194
    m_sysex_streams.resize(m_midi_ins.size());
×
195
    m_input_events.sysex_events.reserve(max_sysex_events);
×
196
    midi_outs.reserve(m_midi_outs.size());
×
197
    parameter_ins.reserve(m_param_ins.size());
×
198
    parameter_outs.reserve(m_param_outs.size());
×
199
    m_input_events.all_events.reserve(4096);
×
200

201
    // Create ports based on the model
202
    for(auto inlet : proc.inlets())
×
203
    {
204
      if(qobject_cast<Process::AudioInlet*>(inlet))
×
205
      {
206
        audio_ins.push_back(new ossia::audio_inlet);
×
207
        m_inlets.push_back(audio_ins.back());
×
208
      }
×
209
      else if(qobject_cast<Process::MidiInlet*>(inlet))
×
210
      {
211
        midi_ins.push_back(new ossia::midi_inlet);
×
212
        m_inlets.push_back(midi_ins.back());
×
213
      }
×
214
      else if(auto inl = qobject_cast<Process::ControlInlet*>(inlet))
×
215
      {
216
        parameter_ins.push_back(new ossia::value_inlet);
×
217
        m_inlets.push_back(parameter_ins.back());
×
218
        parameter_ins.back()->data.write_value(inl->value(), 0);
×
219
      }
×
220
    }
221

222
    for(auto outlet : proc.outlets())
×
223
    {
224
      if(qobject_cast<Process::AudioOutlet*>(outlet))
×
225
      {
226
        audio_outs.push_back(new ossia::audio_outlet);
×
227
        m_outlets.push_back(audio_outs.back());
×
228
      }
×
229
      else if(qobject_cast<Process::MidiOutlet*>(outlet))
×
230
      {
231
        midi_outs.push_back(new ossia::midi_outlet);
×
232
        m_outlets.push_back(midi_outs.back());
×
233
      }
×
234
      else if(qobject_cast<Process::ControlOutlet*>(outlet))
×
235
      {
236
        parameter_outs.push_back(new ossia::value_outlet);
×
237
        m_outlets.push_back(parameter_outs.back());
×
238
      }
×
239
    }
240

241
    SCORE_ASSERT(parameter_ins.size() == m_param_ins.size());
×
242
    SCORE_ASSERT(parameter_outs.size() == m_param_outs.size());
×
243
    SCORE_ASSERT(audio_ins.size() == proc.audioInputs().size());
×
244
    SCORE_ASSERT(audio_outs.size() == proc.audioOutputs().size());
×
245
    SCORE_ASSERT(midi_ins.size() == proc.midiInputs().size());
×
246
    SCORE_ASSERT(midi_outs.size() == proc.midiOutputs().size());
×
247
  }
×
248

249
  std::string label() const noexcept override
×
250
  { //FIXME
251
    return "clap";
×
252
  }
253

254
  [[nodiscard]] bool activate_plugin(
×
255
      const clap_plugin_t* plugin, double sample_rate, uint32_t max_buffer_size)
256
  {
257
    if(!plugin)
×
258
      return false;
×
259

260
    m_sample_rate = sample_rate;
×
261
    m_buffer_size = max_buffer_size;
×
262

263
    if(plugin->activate(plugin, sample_rate, 1, max_buffer_size))
×
264
    {
265
      return true;
×
266
    }
267
    return false;
×
268
  }
×
269

270
  [[nodiscard]] bool start_plugin(const clap_plugin_t* plugin)
×
271
  {
272
    // CLAP spec (plugin.h): reset() "clears all buffers, performs a full
273
    // reset of the processing state (filters, oscillators, envelopes,
274
    // lfo, ...) and kills all voices" and is the right call when
275
    // clap_process.steady_time may jump backward — exactly what happens
276
    // when score (re)starts a transport that has been idle. It's a cheap
277
    // mandatory entry point, and gets rid of residual reverb tails /
278
    // filter ringing between plays.
279
    plugin->reset(plugin);
×
280

281
    if(plugin->start_processing(plugin))
×
282
    {
283
      init_parameter_values(plugin);
×
284
      return true;
×
285
    }
286
    return false;
×
287
  }
×
288

289
  void stop_plugin(const clap_plugin_t* plugin) { plugin->stop_processing(plugin); }
×
290

291
  void init_parameter_values(const clap_plugin_t* plugin)
×
292
  {
293
    if(!plugin || m_param_ins.empty())
×
294
      return;
×
295

296
    // Push initial parameter values via clap.params.flush, not process().
297
    // process() requires the plugin's declared audio port layout (a plugin may
298
    // assert on it, e.g. Floe), and the spec reserves process() for actual
299
    // audio rendering; flush() exists precisely to set parameters with no
300
    // audio. We're on the audio thread, active and not concurrently
301
    // processing, which is a legal context for flush.
302
    auto params = static_cast<const clap_plugin_params_t*>(
×
303
        plugin->get_extension(plugin, CLAP_EXT_PARAMS));
×
304
    if(!params || !params->flush)
×
305
      return;
×
306

307
    event_storage in;
×
308
    in.param_events.reserve(m_param_ins.size());
×
309
    in.all_events.reserve(m_param_ins.size());
×
310
    for(std::size_t i = 0; i < m_param_ins.size(); ++i)
×
311
    {
312
      const auto& param_info = m_param_ins[i];
×
313
      clap_event_param_value_t ev{};
×
314
      ev.header.size = sizeof(clap_event_param_value_t);
×
315
      ev.header.time = 0;
×
316
      ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
317
      ev.header.type = CLAP_EVENT_PARAM_VALUE;
×
318
      ev.header.flags = 0;
×
319
      ev.param_id = param_info.id;
×
320
      ev.cookie = param_info.cookie;
×
321
      ev.note_id = -1;
×
322
      ev.port_index = -1;
×
323
      ev.channel = -1;
×
324
      ev.key = -1;
×
325
      const auto& v = parameter_ins[i]->data.get_data();
×
326
      ev.value = v.empty() ? param_info.default_value
×
327
                           : ossia::convert<float>(v.back().value);
×
328
      in.param_events.push_back(ev);
×
329
    }
×
330
    for(auto& ev : in.param_events)
×
331
      in.all_events.push_back(reinterpret_cast<clap_event_header_t*>(&ev));
×
332

333
    clap_input_events evs{
×
334
        .ctx = &in,
335
        .size = +[](const clap_input_events* list) -> uint32_t {
×
336
      return static_cast<event_storage*>(list->ctx)->all_events.size();
×
337
    },
338
        .get = +[](const clap_input_events* list,
×
339
                   uint32_t index) -> const clap_event_header_t* {
340
      auto* storage = static_cast<event_storage*>(list->ctx);
×
341
      return index < storage->all_events.size() ? storage->all_events[index]
×
342
                                                : nullptr;
343
    }};
344
    clap_output_events_t o_evs{
×
345
        .ctx = nullptr,
346
        .try_push = [](const struct clap_output_events*,
×
347
                       const clap_event_header_t*) -> bool { return false; }};
×
348

349
    params->flush(plugin, &evs, &o_evs);
×
350
  }
×
351

352
  [[nodiscard]]
353
  bool deactivate_plugin(const clap_plugin_t* plugin)
×
354
  {
355
    if(!plugin)
×
356
      return false;
×
357

358
    plugin->deactivate(plugin);
×
359
    return true;
×
360
  }
×
361

362
  auto make_transport(const ossia::token_request& tk, ossia::exec_state_facade st)
×
363
  {
364
    (void)st;
365
    return Clap::make_transport(tk);
×
366
  }
367
  void process_controls(uint32_t samples)
×
368
  {
369
    // Process control inlets and create parameter events. Each ossia
370
    // timed_value carries its own frame offset within the block, so emit
371
    // one CLAP_EVENT_PARAM_VALUE per timestamp instead of collapsing them
372
    // all to frame 0 — that lets sample-accurate automation (LFO, curve,
373
    // MIDI mapping) drive plug-in smoothers correctly.
374
    for(std::size_t i = 0; i < parameter_ins.size(); ++i)
×
375
    {
376
      const auto& data = parameter_ins[i]->data.get_data();
×
377
      if(data.empty())
×
378
        continue;
×
379
      const auto& param_info = m_param_ins[i];
×
380
      for(const auto& tv : data)
×
381
      {
382
        // Vector values are addressed per-voice by prepare_voice_overrides.
383
        if(is_vector_value(tv.value))
×
384
          continue;
×
385
        double value = std::clamp(
×
386
            ossia::convert<double>(tv.value), param_info.min_value,
×
387
            param_info.max_value);
×
388

389
        // Map ossia's signed frame offset onto CLAP's unsigned uint32 time
390
        // field. Port timestamps are relative to the audio buffer while the
391
        // plug-in only sees [m_tick_start; m_tick_start + samples[ of it, so
392
        // rebase first; anything outside still clamps into the block.
393
        const int64_t t = tv.timestamp - m_tick_start;
×
394
        const uint32_t time
×
395
            = t <= 0 ? 0u
×
396
                     : static_cast<uint32_t>(
397
                           std::min<int64_t>(t, samples > 0 ? samples - 1 : 0));
×
398

399
        clap_event_param_value_t param_event{};
×
400
        param_event.header.size = sizeof(clap_event_param_value_t);
×
401
        param_event.header.time = time;
×
402
        param_event.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
403
        param_event.header.type = CLAP_EVENT_PARAM_VALUE;
×
404
        param_event.header.flags = CLAP_EVENT_IS_LIVE;
×
405
        param_event.param_id = param_info.id;
×
406
        param_event.cookie = param_info.cookie;
×
407
        param_event.note_id = -1;
×
408
        param_event.port_index = -1;
×
409
        param_event.channel = -1;
×
410
        param_event.key = -1;
×
411
        param_event.value = value;
×
412

413
        m_input_events.param_events.push_back(param_event);
×
414
        m_input_events.all_events.push_back(
×
415
            reinterpret_cast<clap_event_header_t*>(
×
416
                &m_input_events.param_events.back()));
×
417
      }
418
    }
×
419
  }
×
420

421
  void process_midi()
×
422
  {
423
    const auto stamp = [this](int64_t ts) -> uint32_t {
×
424
      return uint32_t(std::clamp<int64_t>(
×
425
          ts - m_tick_start, 0, m_tick_frames > 0 ? m_tick_frames - 1 : 0));
×
426
    };
427
    uint16_t midi_port_index = 0;
×
428
    for(ossia::midi_inlet* midi_in : midi_ins)
×
429
    {
430
      const auto& spec = m_midi_ins[midi_port_index];
×
431
      const auto& msgs = midi_in->data.messages;
×
432

433
      // Anything held back from a tick that covered no whole sample belongs to
434
      // the first sample of this block.
435
      ossia::small_vector<std::pair<const libremidi::ump*, uint32_t>, 16> to_send;
×
436
      for(const auto& [port, held] : m_deferred_midi)
×
437
        if(port == midi_port_index)
×
438
          to_send.push_back({&held, 0u});
×
439
      for(const auto& m : msgs)
×
440
        to_send.push_back({&m, stamp(m.timestamp)});
×
441

442
      // Notes exist in all three dialects; control changes, pitch bend and
443
      // channel pressure exist only in the MIDI one. A plug-in advertising
444
      // CLAP|MIDI - which most synths do - therefore still needs its non-note
445
      // traffic as raw MIDI, otherwise the CLAP branch below silently drops
446
      // everything that is not a note on/off.
447
      const auto push_midi1 = [&](const libremidi::ump& m, uint32_t m_time) {
×
448
        if(Process::MidiSysexArena::isSysex(m))
×
449
        {
450
          auto& sysex_events = m_input_events.sysex_events;
×
451
          auto ev = toSysexEvent(
×
452
              m, m_time, midi_port_index, m_sysex_arena,
×
453
              m_sysex_streams[midi_port_index]);
×
454
          if(!ev || sysex_events.size() >= sysex_events.capacity())
×
455
            return;
×
456
          sysex_events.push_back(*ev);
×
457
          m_input_events.all_events.push_back(
×
458
              reinterpret_cast<clap_event_header_t*>(&sysex_events.back()));
×
459
          return;
×
460
        }
461

462
        uint8_t midi_bytes[16];
463
        const auto bytes_written = cmidi2_convert_single_ump_to_midi1(
×
464
            midi_bytes, sizeof(midi_bytes), (cmidi2_ump*)m.data);
×
465
        if(bytes_written <= 0 || bytes_written > 3)
×
466
          return;
×
467

468
        clap_event_midi_t ev{};
×
469
        ev.header.size = sizeof(clap_event_midi_t);
×
470
        ev.header.time = m_time;
×
471
        ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
472
        ev.header.type = CLAP_EVENT_MIDI;
×
473
        ev.header.flags = 0;
×
474
        ev.port_index = midi_port_index;
×
475
        std::memcpy(ev.data, midi_bytes, bytes_written);
×
476

477
        m_input_events.midi_events.push_back(ev);
×
478
        m_input_events.all_events.push_back(
×
479
            reinterpret_cast<clap_event_header_t*>(
×
480
                &m_input_events.midi_events.back()));
×
481
      };
×
482

483
      if(spec.supported_dialects & clap_note_dialect::CLAP_NOTE_DIALECT_MIDI2)
×
484
      {
485
        for(const auto& [m_ptr, m_time] : to_send)
×
486
        {
487
          const auto& m = *m_ptr;
×
488
          clap_event_midi2_t ev{};
×
489
          ev.header.size = sizeof(clap_event_midi2_t);
×
490
          ev.header.time = m_time;
×
491
          ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
492
          ev.header.type = CLAP_EVENT_MIDI2;
×
493
          ev.header.flags = 0;
×
494
          ev.port_index = midi_port_index;
×
495
          ev.data[0] = m.data[0];
×
496
          ev.data[1] = m.data[1];
×
497
          ev.data[2] = m.data[2];
×
498
          ev.data[3] = m.data[3];
×
499

500
          m_input_events.midi2_events.push_back(ev);
×
501
          m_input_events.all_events.push_back(
×
502
              reinterpret_cast<clap_event_header_t*>(
×
503
                  &m_input_events.midi2_events.back()));
×
504
        }
505
      }
×
506
      else if(spec.supported_dialects & clap_note_dialect::CLAP_NOTE_DIALECT_CLAP)
×
507
      {
508
        for(const auto& [m_ptr, m_time] : to_send)
×
509
        {
510
          const auto& m = *m_ptr;
×
511
          if(Process::MidiSysexArena::isSysex(m))
×
512
          {
513
            if(spec.supported_dialects & clap_note_dialect::CLAP_NOTE_DIALECT_MIDI)
×
514
              push_midi1(m, m_time);
×
515
            continue;
×
516
          }
517
          if(m.get_type() != libremidi::midi2::message_type::MIDI_2_CHANNEL)
×
518
            continue;
×
519
          clap_event_note_t ev{};
×
520
          ev.header.size = sizeof(clap_event_note_t);
×
521
          ev.header.time = m_time;
×
522
          ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
523
          ev.header.flags = 0;
×
524
          ev.port_index = midi_port_index;
×
525
          ev.note_id = -1;
×
526
          switch(libremidi::message_type(m.get_status_code()))
×
527
          {
528
            case libremidi::message_type::NOTE_ON: {
529
              auto [channel, note, value] = libremidi::as_01::note_off(m);
×
530
              if(value > 0)
×
531
              {
532
                ev.header.type = CLAP_EVENT_NOTE_ON;
×
533
                ev.channel = channel;
×
534
                ev.key = note;
×
535
                ev.velocity = value;
×
536
              }
×
537
              else
538
              {
539
                ev.header.type = CLAP_EVENT_NOTE_OFF;
×
540
                ev.channel = channel;
×
541
                ev.key = note;
×
542
                ev.velocity = 0.0;
×
543
              }
544
              m_input_events.note_events.push_back(ev);
×
545
              m_input_events.all_events.push_back(
×
546
                  reinterpret_cast<clap_event_header_t*>(
×
547
                      &m_input_events.note_events.back()));
×
548
              break;
×
549
            }
550
            case libremidi::message_type::NOTE_OFF: {
551
              auto [channel, note, value] = libremidi::as_01::note_off(m);
×
552
              ev.header.type = CLAP_EVENT_NOTE_OFF;
×
553
              ev.channel = channel;
×
554
              ev.key = note;
×
555
              ev.velocity = value;
×
556
              m_input_events.note_events.push_back(ev);
×
557
              m_input_events.all_events.push_back(
×
558
                  reinterpret_cast<clap_event_header_t*>(
×
559
                      &m_input_events.note_events.back()));
×
560
              break;
×
561
            }
562
            default: {
563
              // Poly pressure, CC, pitch bend, channel pressure: no CLAP-note
564
              // representation, so pass them through in the MIDI dialect when
565
              // the port also accepts it.
566
              if(spec.supported_dialects & clap_note_dialect::CLAP_NOTE_DIALECT_MIDI)
×
567
                push_midi1(m, m_time);
×
568
              break;
×
569
            }
570
          }
571
        }
572
      }
×
573
      else if(spec.supported_dialects & clap_note_dialect::CLAP_NOTE_DIALECT_MIDI)
×
574
      {
575
        for(const auto& [m_ptr, m_time] : to_send)
×
576
          push_midi1(*m_ptr, m_time);
×
577
      }
×
578
      midi_port_index++;
×
579
    }
×
580
    // Not cleared here: converting an event is not delivering it. run() can
581
    // still return before process(), and anything held back has to survive
582
    // that and go out with the block that actually reaches the plug-in.
583
  }
×
584

585
  //! Keep this tick's events for the next block rather than dropping them: the
586
  //! span covers no whole sample, so every date in the tick maps to the sample
587
  //! the span starts on, which is offset 0 of the next block that covers one.
588
  void stash_midi()
×
589
  {
590
    uint16_t midi_port_index = 0;
×
591
    for(ossia::midi_inlet* midi_in : midi_ins)
×
592
    {
593
      for(const auto& m : midi_in->data.messages)
×
594
      {
595
        if(m_deferred_midi.size() >= 1024)
×
596
          return;
×
597
        m_deferred_midi.push_back({midi_port_index, m});
×
598
      }
599
      midi_port_index++;
×
600
    }
601
  }
×
602

603
  void prepare_input_events(int64_t offset, int samples)
×
604
  {
605
    m_tick_start = offset;
×
606
    m_tick_frames = samples;
×
607
    m_input_events.clear();
×
608
    m_output_events.clear();
×
609
    m_sysex_arena.clear();
×
610

611
    int param_event_count = 0;
×
612
    // all_events holds pointers into the per-kind vectors, so these
613
    // reservations have to cover what is held back as well: a reallocation
614
    // would leave every pointer already pushed dangling.
615
    int midi_event_count = int(m_deferred_midi.size());
×
616
    for(auto port : this->parameter_ins)
×
617
      param_event_count += port->data.get_data().size();
×
618
    for(auto port : this->midi_ins)
×
619
      midi_event_count += port->data.messages.size();
×
620
    m_input_events.midi_events.reserve(midi_event_count * 1.1);
×
621
    m_input_events.midi2_events.reserve(midi_event_count * 1.1);
×
622
    m_input_events.note_events.reserve(midi_event_count * 1.1);
×
623
    m_input_events.param_events.reserve(
×
624
        param_event_count * 1.1
×
625
        + 2
×
626
              * this->parameter_ins
×
627
                    .size()); // Important to reserve one additional buffer of parameters for the mono case
×
628
    m_input_events.all_events.reserve((param_event_count + midi_event_count + 1) * 1.1);
×
629

630
    if(m_pending_all_notes_off.exchange(false, std::memory_order_acq_rel))
×
631
      inject_all_notes_off();
×
632

633
    // Process parameter changes
634
    process_controls(samples);
×
635
    process_midi();
×
636

637
    // Events need to be sorted. Stably: events sharing a time must keep the
638
    // order they were queued in, or a note-off can end up after the note-on
639
    // that follows it. Deferral makes that routine rather than rare, since it
640
    // puts everything it held back at time 0 alongside the block's own.
641
    std::stable_sort(
×
642
        m_input_events.all_events.begin(), m_input_events.all_events.end(),
×
643
        [](const clap_event_header_t* a, const clap_event_header_t* b) {
×
644
      return a->time < b->time;
×
645
    });
646
  }
×
647

648
  // NOTE_CHOKE wildcard + CC#120/123 on all 16 channels covers every dialect.
649
  void inject_all_notes_off()
×
650
  {
651
    {
652
      clap_event_note_t ev{};
×
653
      ev.header.size = sizeof(clap_event_note_t);
×
654
      ev.header.time = 0;
×
655
      ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
656
      ev.header.type = CLAP_EVENT_NOTE_CHOKE;
×
657
      ev.header.flags = 0;
×
658
      ev.note_id = -1;
×
659
      ev.port_index = -1;
×
660
      ev.channel = -1;
×
661
      ev.key = -1;
×
662
      ev.velocity = 0.0;
×
663
      m_input_events.note_events.push_back(ev);
×
664
      m_input_events.all_events.push_back(
×
665
          reinterpret_cast<clap_event_header_t*>(&m_input_events.note_events.back()));
×
666
    }
667
    for(uint8_t ch = 0; ch < 16; ++ch)
×
668
    {
669
      for(uint8_t cc : {uint8_t(120), uint8_t(123)})
×
670
      {
671
        clap_event_midi_t ev{};
×
672
        ev.header.size = sizeof(clap_event_midi_t);
×
673
        ev.header.time = 0;
×
674
        ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
675
        ev.header.type = CLAP_EVENT_MIDI;
×
676
        ev.header.flags = 0;
×
677
        ev.port_index = 0;
×
678
        ev.data[0] = uint8_t(0xB0 | ch);
×
679
        ev.data[1] = cc;
×
680
        ev.data[2] = 0;
×
681
        m_input_events.midi_events.push_back(ev);
×
682
        m_input_events.all_events.push_back(
×
683
            reinterpret_cast<clap_event_header_t*>(&m_input_events.midi_events.back()));
×
684
      }
685
    }
×
686
  }
×
687

688
  void all_notes_off() noexcept override
×
689
  {
690
    m_pending_all_notes_off.store(true, std::memory_order_release);
×
691
  }
×
692

693
  // Forward any CLAP_EVENT_PARAM_VALUE events the plugin emitted during
694
  // process() to the matching `parameter_outs` value_outlet so downstream
695
  // ossia nodes (and the GUI bargraphs) see live values.
696
  void dispatch_param_outputs()
×
697
  {
698
    if(m_output_events.param_events.empty())
×
699
      return;
×
700

701
    for(const auto& ev : m_output_events.param_events)
×
702
    {
703
      auto it = m_param_out_index.find(ev.param_id);
×
704
      if(it == m_param_out_index.end())
×
705
        continue;
×
706
      const auto idx = it->second;
×
707
      if(idx < parameter_outs.size())
×
708
        parameter_outs[idx]->data.write_value(
×
709
            ossia::value{ev.value}, static_cast<int64_t>(ev.header.time));
×
710
    }
711
  }
×
712

713
  ossia::small_vector<ossia::audio_inlet*, 2> audio_ins;
714
  ossia::small_vector<ossia::audio_outlet*, 2> audio_outs;
715
  ossia::small_vector<ossia::midi_inlet*, 2> midi_ins;
716
  ossia::small_vector<ossia::midi_outlet*, 2> midi_outs;
717
  std::vector<ossia::value_inlet*> parameter_ins;
718
  std::vector<ossia::value_outlet*> parameter_outs;
719
  clap_event_transport_t m_current_transport{};
×
720

721
  // Buffer span this tick was given, as reported by exec_state_facade::timings().
722
  int64_t m_tick_start{};
×
723
  int64_t m_tick_frames{};
×
724

725
  //! Events from ticks that covered no whole sample, with the port they came in
726
  //! on, waiting for the next block that does cover one.
727
  ossia::small_vector<std::pair<uint16_t, libremidi::ump>, 8> m_deferred_midi;
728

729
  //! The bytes of the system-exclusive messages of one process call, until
730
  //! the next; one stream per MIDI input port. The sysex events of a call stay
731
  //! within the capacity reserved up front, since all_events points at them.
732
  static constexpr std::size_t max_sysex_events = 128;
733
  Process::MidiSysexArena m_sysex_arena;
734
  std::vector<Process::MidiSysexArena::stream> m_sysex_streams;
735

736
  event_storage m_input_events;
737
  event_storage m_output_events;
738

739
  const std::vector<clap_param_info_t>& m_param_ins;
740
  const std::vector<clap_param_info_t>& m_param_outs;
741
  const std::vector<clap_note_port_info_t>& m_midi_ins;
742
  const std::vector<clap_note_port_info_t>& m_midi_outs;
743
  const ossia::flat_map<clap_id, std::uint32_t>& m_param_out_index;
744
  double m_sample_rate{44100.0};
×
745
  uint32_t m_buffer_size{512};
×
746

747
  // Last clap_process_status returned by the plugin. CLAP_PROCESS_SLEEP
748
  // tells us "no more processing needed until next event or audio input
749
  // variation" — we use this to skip plugin->process on instruments that
750
  // are idle (audio_ins empty + no events). For effects (audio_ins
751
  // non-empty) we always process: detecting "audio input variation"
752
  // accurately would require a per-frame scan we don't want to pay for.
753
  clap_process_status m_last_status{CLAP_PROCESS_CONTINUE};
×
754

755
  std::atomic<bool> m_pending_all_notes_off{false};
×
756
};
757

758
// Normal implementation
759
class clap_node : public clap_node_base
760
{
761
public:
762
  std::vector<double> dummy_io_buffer;
763
  clap_node(const Clap::Model& proc, Clap::PluginHandle& handle, int sampleRate, int bs)
×
764
      : clap_node_base{proc}
×
765
      , m_instance{handle}
×
766
  {
×
767
    m_expected_audio_inputs = proc.audioInputs();
×
768
    m_expected_audio_outputs = proc.audioOutputs();
×
769

770
    if(handle.activated)
×
771
      (void)deactivate_plugin(handle.plugin);
×
772
    m_activated = activate_plugin(m_instance.plugin, sampleRate, bs);
×
773
    handle.activated = m_activated;
×
774
    dummy_io_buffer.resize(2 * bs);
×
775
  }
×
776

777
  ~clap_node()
×
778
  {
×
779
    // We do not deactivate in the audio thread where the dtor of clap_node runs
780
    // but later in the main thread (driven by Model::resetExecution / ~Model
781
    // through the synced handle.activated flag set in the constructor).
782
  }
×
783

784
  void do_process(
×
785
      clap_process_t& process, event_storage& input_storage,
786
      event_storage& output_storage)
787
  {
788
    // Process audio
789
    process.steady_time = -1;
×
790
    process.transport = &m_current_transport;
×
791

792
    // Setup input events
793
    clap_input_events evs{
×
794
        .ctx = &input_storage,
×
795
        .size = +[](const clap_input_events* list) -> uint32_t {
×
796
      auto* storage = static_cast<event_storage*>(list->ctx);
×
797
      return storage->all_events.size();
×
798
    },
799
        .get = +[](const clap_input_events* list,
×
800
                   uint32_t index) -> const clap_event_header_t* {
801
      auto* storage = static_cast<event_storage*>(list->ctx);
×
802
      if(index < storage->all_events.size())
×
803
        return storage->all_events[index];
×
804
      return nullptr;
×
805
    }};
×
806

807
    // Setup output events
808
    clap_output_events_t o_evs{
×
809
        .ctx = &output_storage,
×
810
        .try_push = [](const struct clap_output_events* list,
×
811
                       const clap_event_header_t* event) -> bool {
812
      auto* storage = static_cast<event_storage*>(list->ctx);
×
813
      if(!event || event->space_id != CLAP_CORE_EVENT_SPACE_ID)
×
814
        return false;
×
815
      switch(event->type)
×
816
      {
817
        case CLAP_EVENT_MIDI:
818
          if(event->size >= sizeof(clap_event_midi_t))
×
819
          {
820
            storage->midi_events.push_back(
×
821
                *reinterpret_cast<const clap_event_midi_t*>(event));
×
822
            return true;
×
823
          }
824
          return false;
×
825
        case CLAP_EVENT_PARAM_VALUE:
826
          if(event->size >= sizeof(clap_event_param_value_t))
×
827
          {
828
            storage->param_events.push_back(
×
829
                *reinterpret_cast<const clap_event_param_value_t*>(event));
×
830
            return true;
×
831
          }
832
          return false;
×
833
        case CLAP_EVENT_NOTE_ON:
834
        case CLAP_EVENT_NOTE_OFF:
835
        case CLAP_EVENT_NOTE_END:
836
        case CLAP_EVENT_NOTE_CHOKE:
837
          // Plug-in voice events: useful both as plain MIDI fanout to a
838
          // downstream MidiOutlet (we convert later) and, for NOTE_END
839
          // specifically, so polyphonic hosts can release a voice slot.
840
          if(event->size >= sizeof(clap_event_note_t))
×
841
          {
842
            storage->note_events.push_back(
×
843
                *reinterpret_cast<const clap_event_note_t*>(event));
×
844
            return true;
×
845
          }
846
          return false;
×
847
        case CLAP_EVENT_MIDI2:
848
          // MIDI 2.0 / UMP packets — forward 1:1 to libremidi::ump in
849
          // the post-process step below.
850
          if(event->size >= sizeof(clap_event_midi2_t))
×
851
          {
852
            storage->midi2_events.push_back(
×
853
                *reinterpret_cast<const clap_event_midi2_t*>(event));
×
854
            return true;
×
855
          }
856
          return false;
×
857
        case CLAP_EVENT_MIDI_SYSEX:
858
          // The buffer pointer is only valid for the duration of this
859
          // try_push call (clap/events.h), so copy the bytes into our
860
          // own storage and rewrite the event to point there.
861
          if(event->size >= sizeof(clap_event_midi_sysex_t))
×
862
          {
863
            auto* sx
×
864
                = reinterpret_cast<const clap_event_midi_sysex_t*>(event);
×
865
            if(sx->size == 0 || sx->buffer == nullptr)
×
866
              return false;
×
867
            storage->sysex_data.emplace_back(
×
868
                sx->buffer, sx->buffer + sx->size);
×
869
            clap_event_midi_sysex_t copy = *sx;
×
870
            copy.buffer = storage->sysex_data.back().data();
×
871
            storage->sysex_events.push_back(copy);
×
872
            return true;
×
873
          }
874
          return false;
×
875
        default:
876
          return false;
×
877
      }
878
    }};
×
879

880
    process.in_events = &evs;
×
881
    process.out_events = &o_evs;
×
882

883
    m_last_status = m_instance.plugin->process(m_instance.plugin, &process);
×
884
    // Delivered: anything held back from an empty tick has now reached the
885
    // plug-in and must not be sent again.
886
    m_deferred_midi.clear();
×
887

888
    dispatch_param_outputs();
×
889

890
    // Process MIDI output
891
    forward_midi_outputs();
×
892
  }
×
893

894
  // Fan plug-in MIDI / note / sysex output events out to score's MIDI
895
  // outlets, converting to UMP packets. Shared between clap_node and
896
  // clap_node_mono so they don't drift.
897
  void forward_midi_outputs()
×
898
  {
899
    std::size_t midi_port_index = 0;
×
900
    for(std::size_t i = 0; i < m_outlets.size(); ++i)
×
901
    {
902
      if(auto midi_out = m_outlets[i]->target<ossia::midi_port>())
×
903
      {
904
        auto& port_messages = midi_out->messages;
×
905
        port_messages.clear();
×
906

907
        // CLAP_EVENT_MIDI: MIDI 1.0 → UMP via cmidi2.
908
        for(const auto& midi_event : m_output_events.midi_events)
×
909
        {
910
          if(midi_event.port_index != midi_port_index)
×
911
            continue;
×
912
          libremidi::ump msg;
×
913
          if(cmidi2_midi1_channel_voice_to_midi2(midi_event.data, 3, msg.data))
×
914
          {
915
            msg.timestamp = m_tick_start + midi_event.header.time;
×
916
            port_messages.push_back(msg);
×
917
          }
×
918
        }
919

920
        // CLAP_EVENT_NOTE_*: synthesize a MIDI 1.0 message and convert.
921
        // NOTE_END / NOTE_CHOKE have no direct MIDI equivalent — both
922
        // mean "this voice is over", so emit NOTE_OFF (velocity 0) so a
923
        // downstream MIDI device sees the voice released.
924
        for(const auto& ne : m_output_events.note_events)
×
925
        {
926
          if(ne.port_index != midi_port_index)
×
927
            continue;
×
928
          const uint8_t ch = static_cast<uint8_t>(ne.channel & 0x0F);
×
929
          const uint8_t key = static_cast<uint8_t>(std::clamp<int>(ne.key, 0, 127));
×
930
          uint8_t bytes[3]{};
×
931
          switch(ne.header.type)
×
932
          {
933
            case CLAP_EVENT_NOTE_ON: {
934
              const uint8_t vel = static_cast<uint8_t>(std::clamp(
×
935
                  static_cast<int>(ne.velocity * 127.0 + 0.5), 0, 127));
×
936
              bytes[0] = 0x90 | ch;
×
937
              bytes[1] = key;
×
938
              bytes[2] = vel;
×
939
              break;
×
940
            }
941
            case CLAP_EVENT_NOTE_OFF: {
942
              const uint8_t vel = static_cast<uint8_t>(std::clamp(
×
943
                  static_cast<int>(ne.velocity * 127.0 + 0.5), 0, 127));
×
944
              bytes[0] = 0x80 | ch;
×
945
              bytes[1] = key;
×
946
              bytes[2] = vel;
×
947
              break;
×
948
            }
949
            case CLAP_EVENT_NOTE_END:
950
            case CLAP_EVENT_NOTE_CHOKE:
951
              bytes[0] = 0x80 | ch;
×
952
              bytes[1] = key;
×
953
              bytes[2] = 0;
×
954
              break;
×
955
            default:
956
              continue;
×
957
          }
958
          libremidi::ump msg;
×
959
          if(cmidi2_midi1_channel_voice_to_midi2(bytes, 3, msg.data))
×
960
          {
961
            msg.timestamp = m_tick_start + ne.header.time;
×
962
            port_messages.push_back(msg);
×
963
          }
×
964
        }
965

966
        // CLAP_EVENT_MIDI2: already UMP-shaped — copy verbatim.
967
        for(const auto& m2 : m_output_events.midi2_events)
×
968
        {
969
          if(m2.port_index != midi_port_index)
×
970
            continue;
×
971
          libremidi::ump msg;
×
972
          std::memcpy(msg.data, m2.data, sizeof(m2.data));
×
973
          msg.timestamp = m_tick_start + m2.header.time;
×
974
          port_messages.push_back(msg);
×
975
        }
976

977
        // CLAP_EVENT_MIDI_SYSEX: encode the captured byte buffer into
978
        // one or more UMP sysex7 packets (6 data bytes per packet).
979
        for(const auto& sx : m_output_events.sysex_events)
×
980
        {
981
          if(sx.port_index != midi_port_index)
×
982
            continue;
×
983
          if(sx.size == 0 || sx.buffer == nullptr)
×
984
            continue;
×
985
          const std::size_t num_packets
×
986
              = cmidi2_ump_sysex_get_num_packets(sx.size, 6);
×
987
          for(std::size_t pkt = 0; pkt < num_packets; ++pkt)
×
988
          {
989
            libremidi::ump msg{};
×
990
            uint64_t r1 = 0, r2 = 0;
×
991
            cmidi2_ump_sysex_get_packet_of(
×
992
                &r1, &r2, /*group*/ 0, sx.size, sx.buffer,
×
993
                static_cast<int32_t>(pkt), CMIDI2_MESSAGE_TYPE_SYSEX7, 6,
×
994
                /*hasStreamId*/ false, /*streamId*/ 0);
995
            // sysex7 packets are 64-bit; libremidi::ump.data[0..1] holds it.
996
            msg.data[0] = static_cast<uint32_t>(r1 >> 32);
×
997
            msg.data[1] = static_cast<uint32_t>(r1 & 0xFFFFFFFFu);
×
998
            msg.timestamp = sx.header.time;
×
999
            port_messages.push_back(msg);
×
1000
          }
×
1001
        }
1002

1003
        midi_port_index++;
×
1004
      }
×
1005
    }
×
1006
  }
×
1007

1008
  PluginHandle& m_instance;
1009
  std::vector<clap_audio_port_info_t> m_expected_audio_inputs{};
×
1010
  std::vector<clap_audio_port_info_t> m_expected_audio_outputs{};
×
1011

1012
  std::vector<clap_audio_buffer_t> input_buffers;
1013
  std::vector<clap_audio_buffer_t> output_buffers;
1014

1015
  bool m_activated{};
×
1016
  bool m_processing{};
×
1017
};
1018

1019
class clap_node_32 final : public clap_node
1020
{
1021
  std::vector<std::vector<float>> input_channel_storage;
1022
  std::vector<std::vector<float>> output_channel_storage;
1023
  std::vector<std::vector<float*>> input_channel_ptrs;
1024
  std::vector<std::vector<float*>> output_channel_ptrs;
1025

1026
public:
1027
  using clap_node::clap_node;
1028

1029
  void run(const ossia::token_request& t, ossia::exec_state_facade e) noexcept override
×
1030
  {
1031
    if(!m_instance.plugin)
×
1032
      return;
×
1033

1034
    // Activate plugin if needed
1035
    if(!m_activated)
×
1036
      return;
×
1037
    if(!m_processing)
×
1038
    {
1039
      m_processing = start_plugin(m_instance.plugin);
×
1040
      if(!m_processing)
×
1041
        return;
×
1042
    }
×
1043

1044
    auto [offset, samples] = e.timings(t);
×
1045
    if(samples == 0)
×
1046
    {
1047
      // Never call a plug-in with an empty block; CLAP bounds the frame count
1048
      // at [1, INT32_MAX]. What the tick carried goes out at the top of the
1049
      // next real one.
1050
      stash_midi();
×
1051
      return;
×
1052
    }
1053

1054
    m_current_transport = make_transport(t, e);
×
1055

1056
    // Clear previous data
1057
    input_buffers.clear();
×
1058
    output_buffers.clear();
×
1059
    input_channel_storage.clear();
×
1060
    output_channel_storage.clear();
×
1061
    input_channel_ptrs.clear();
×
1062
    output_channel_ptrs.clear();
×
1063

1064
    prepare_input_events(offset, samples);
×
1065

1066
    // Honour CLAP_PROCESS_SLEEP: the plug-in told us it needs no further
1067
    // work until an event arrives or audio input varies. We trust the
1068
    // event check; for audio-input variation we conservatively bail only
1069
    // on instruments (no audio input ports) — for effects, scanning every
1070
    // input frame for non-zero content would cost more than just running
1071
    // the plug-in's process() and is exactly what plug-ins themselves do.
1072
    if(m_last_status == CLAP_PROCESS_SLEEP && audio_ins.empty()
×
1073
       && m_input_events.all_events.empty())
×
1074
    {
1075
      // Stay asleep — emit silence on the audio outputs so downstream
1076
      // sees a clean signal instead of stale data from the last block.
1077
      std::size_t out_idx = 0;
×
1078
      for(ossia::audio_outlet* audio_out : audio_outs)
×
1079
      {
1080
        if(out_idx >= m_expected_audio_outputs.size())
×
1081
          break;
×
1082
        const auto& info = m_expected_audio_outputs[out_idx];
×
1083
        audio_out->data.set_channels(info.channel_count);
×
1084
        for(auto& ch : audio_out->data.get())
×
1085
        {
1086
          ch.resize(std::max<std::size_t>(ch.size(), e.bufferSize()));
×
1087
          std::fill_n(ch.data() + offset, samples, 0.0);
×
1088
        }
1089
        out_idx++;
×
1090
      }
1091
      // Also clear any midi outlets so we don't repeat last block's MIDI.
1092
      for(ossia::midi_outlet* midi_out : midi_outs)
×
1093
        midi_out->data.messages.clear();
×
1094
      return;
×
1095
    }
1096

1097
    // Setup audio input buffers
1098
    // We must create exactly the number of buffers the plugin expects
1099
    int audio_in_idx = 0;
×
1100
    for(ossia::audio_inlet* audio_in : audio_ins)
×
1101
    {
1102
      const auto& audio_info = this->m_expected_audio_inputs[audio_in_idx];
×
1103
      clap_audio_buffer_t buffer = dummy_audio_buffer();
×
1104
      buffer.channel_count = audio_info.channel_count;
×
1105

1106
      audio_in->data.set_channels(buffer.channel_count);
×
1107
      auto& channels = audio_in->data.get();
×
1108
      if(!channels.empty())
×
1109
      {
1110
        auto& storage = input_channel_storage.emplace_back();
×
1111
        storage.resize(buffer.channel_count);
×
1112

1113
        auto& ptrs = input_channel_ptrs.emplace_back();
×
1114
        ptrs.resize(buffer.channel_count);
×
1115

1116
        storage.resize(samples * buffer.channel_count + 16);
×
1117
        for(uint32_t c = 0; c < buffer.channel_count; ++c)
×
1118
        {
1119
          ptrs[c] = storage.data() + c * samples;
×
1120

1121
          // Convert from double to float
1122
          if(c < channels.size())
×
1123
          {
1124
            auto& channel = channels[c];
×
1125
            //SCORE_SOFT_ASSERT(channel.size() >= e.bufferSize());
1126
            channel.resize(std::max((int)channel.size(), (int)e.bufferSize()));
×
1127
            const double* src = channels[c].data() + offset;
×
1128
            float* dst = ptrs[c];
×
1129
            for(uint32_t s = 0; s < samples; ++s)
×
1130
            {
1131
              dst[s] = static_cast<float>(src[s]);
×
1132
            }
×
1133
          }
×
1134
          else
1135
          {
1136
            // Zero fill if no input data
1137
            std::fill(ptrs[c], ptrs[c] + samples, 0.0f);
×
1138
          }
1139
        }
×
1140

1141
        buffer.data32 = ptrs.data();
×
1142
      }
×
1143

1144
      input_buffers.push_back(buffer);
×
1145
      audio_in_idx++;
×
1146
    }
1147

1148
    // Setup output buffers
1149
    int audio_out_idx = 0;
×
1150
    const bool needs_stereo_main_out
×
1151
        = audio_ins.empty() && !audio_outs.empty()
×
1152
          && !midi_ins.empty(); // FIXME check if instrument?
×
1153
    for(ossia::audio_outlet* audio_out : audio_outs)
×
1154
    {
1155
      const auto& audio_info = this->m_expected_audio_outputs[audio_out_idx];
×
1156
      clap_audio_buffer_t buffer = dummy_audio_buffer();
×
1157
      buffer.channel_count = audio_info.channel_count;
×
1158

1159
      const int ossia_channel_count = audio_out_idx == 0 && needs_stereo_main_out
×
1160
                                          ? std::max((int)buffer.channel_count, 2)
×
1161
                                          : buffer.channel_count;
×
1162
      audio_out->data.set_channels(ossia_channel_count);
×
1163
      auto& channels = audio_out->data.get();
×
1164

1165
      // Allocate float storage for output
1166
      auto& storage = output_channel_storage.emplace_back();
×
1167
      storage.resize(buffer.channel_count);
×
1168

1169
      auto& ptrs = output_channel_ptrs.emplace_back();
×
1170
      ptrs.resize(buffer.channel_count);
×
1171

1172
      storage.clear();
×
1173
      storage.resize(samples * buffer.channel_count + 16);
×
1174
      for(uint32_t c = 0; c < ossia_channel_count; ++c)
×
1175
      {
1176
        channels[c].resize(e.bufferSize());
×
1177
      }
×
1178
      for(uint32_t c = 0; c < buffer.channel_count; ++c)
×
1179
      {
1180
        ptrs[c] = storage.data() + c * samples;
×
1181
      }
×
1182

1183
      buffer.data32 = ptrs.data();
×
1184
      output_buffers.push_back(buffer);
×
1185
      audio_out_idx++;
×
1186
    }
1187

1188
    // Ensure we have exactly the number of buffers the plugin expects
1189
    // *before* taking .data() pointers below.
1190
    while(input_buffers.size() < m_expected_audio_inputs.size())
×
1191
      input_buffers.push_back(dummy_audio_buffer());
×
1192
    while(output_buffers.size() < m_expected_audio_outputs.size())
×
1193
      output_buffers.push_back(dummy_audio_buffer());
×
1194

1195
    clap_process_t process{};
×
1196
    process.frames_count = samples;
×
1197
    process.audio_inputs = input_buffers.data();
×
1198
    process.audio_outputs = output_buffers.data();
×
1199
    process.audio_inputs_count = m_expected_audio_inputs.size();
×
1200
    process.audio_outputs_count = m_expected_audio_outputs.size();
×
1201
    do_process(process, m_input_events, m_output_events);
×
1202

1203
    // Convert audio output from float back to double
1204
    audio_out_idx = 0;
×
1205
    for(ossia::audio_outlet* audio_out : audio_outs)
×
1206
    {
1207
      if(audio_out_idx < output_channel_storage.size())
×
1208
      {
1209
        auto& channels = audio_out->data.get();
×
1210
        const auto& storage = output_channel_storage[audio_out_idx];
×
1211
        const uint32_t plugin_channels
×
1212
            = m_expected_audio_outputs[audio_out_idx].channel_count;
×
1213

1214
        if(audio_out_idx == 0 && needs_stereo_main_out && plugin_channels == 1)
×
1215
        {
1216
          // Basic mono instrument case (e.g. Nekobi): duplicate L → R only
1217
          // when the plugin's main out is actually mono. For ≥2-channel
1218
          // outs the second channel holds valid audio.
1219
          const float* src = storage.data();
×
1220
          double* dst_l = channels[0].data() + offset;
×
1221
          double* dst_r = channels[1].data() + offset;
×
1222
          for(uint32_t s = 0; s < samples; ++s)
×
1223
          {
1224
            dst_l[s] = static_cast<double>(src[s]);
×
1225
            dst_r[s] = dst_l[s];
×
1226
          }
×
1227
        }
×
1228
        else
1229
        {
1230
          const uint32_t channel_max
×
1231
              = std::min<uint32_t>(channels.size(), plugin_channels);
×
1232
          for(uint32_t c = 0; c < channel_max; ++c)
×
1233
          {
1234
            const float* src = storage.data() + c * samples;
×
1235
            double* dst = channels[c].data() + offset;
×
1236
            for(uint32_t s = 0; s < samples; ++s)
×
1237
              dst[s] = static_cast<double>(src[s]);
×
1238
          }
×
1239
        }
1240
      }
×
1241
      audio_out_idx++;
×
1242
    }
1243
  }
×
1244
};
1245

1246
class clap_node_64 final : public clap_node
1247
{
1248
  std::vector<std::vector<double*>> input_channel_ptrs;
1249
  std::vector<std::vector<double*>> output_channel_ptrs;
1250

1251
public:
1252
  using clap_node::clap_node;
1253
  ~clap_node_64() { }
×
1254
  void run(const ossia::token_request& t, ossia::exec_state_facade e) noexcept override
×
1255
  {
1256
    if(!m_instance.plugin)
×
1257
      return;
×
1258

1259
    // Activate plugin if needed
1260
    if(!m_activated)
×
1261
      return;
×
1262
    if(!m_processing)
×
1263
    {
1264
      m_processing = start_plugin(m_instance.plugin);
×
1265
      if(!m_processing)
×
1266
        return;
×
1267
    }
×
1268

1269
    auto [offset, samples] = e.timings(t);
×
1270
    if(samples == 0)
×
1271
    {
1272
      // Never call a plug-in with an empty block; CLAP bounds the frame count
1273
      // at [1, INT32_MAX]. What the tick carried goes out at the top of the
1274
      // next real one.
1275
      stash_midi();
×
1276
      return;
×
1277
    }
1278

1279
    m_current_transport = make_transport(t, e);
×
1280

1281
    // Prepare buffers
1282
    input_buffers.clear();
×
1283
    output_buffers.clear();
×
1284
    m_input_events.clear();
×
1285
    m_output_events.clear();
×
1286

1287
    // Process parameter changes
1288
    prepare_input_events(offset, samples);
×
1289

1290
    // Honour CLAP_PROCESS_SLEEP — see clap_node_32::run for rationale.
1291
    if(m_last_status == CLAP_PROCESS_SLEEP && audio_ins.empty()
×
1292
       && m_input_events.all_events.empty())
×
1293
    {
1294
      std::size_t out_idx = 0;
×
1295
      for(ossia::audio_outlet* audio_out : audio_outs)
×
1296
      {
1297
        if(out_idx >= m_expected_audio_outputs.size())
×
1298
          break;
×
1299
        const auto& info = m_expected_audio_outputs[out_idx];
×
1300
        audio_out->data.set_channels(info.channel_count);
×
1301
        for(auto& ch : audio_out->data.get())
×
1302
        {
1303
          ch.resize(std::max<std::size_t>(ch.size(), e.bufferSize()));
×
1304
          std::fill_n(ch.data() + offset, samples, 0.0);
×
1305
        }
1306
        out_idx++;
×
1307
      }
1308
      for(ossia::midi_outlet* midi_out : midi_outs)
×
1309
        midi_out->data.messages.clear();
×
1310
      return;
×
1311
    }
1312

1313
    // Setup audio input buffers
1314
    std::size_t audio_in_idx = 0;
×
1315
    for(ossia::audio_inlet* audio_in : audio_ins)
×
1316
    {
1317
      const auto& audio_info = this->m_expected_audio_inputs[audio_in_idx];
×
1318
      clap_audio_buffer_t buffer = dummy_audio_buffer();
×
1319
      buffer.channel_count = audio_info.channel_count;
×
1320

1321
      audio_in->data.set_channels(buffer.channel_count);
×
1322
      auto& channels = audio_in->data.get();
×
1323
      if(!channels.empty())
×
1324
      {
1325
        // Pass exactly what the plugin expects. The previous code clamped
1326
        // this to 2 channels, dropping surround / multi-channel inputs.
1327
        auto& ptrs = input_channel_ptrs.emplace_back();
×
1328
        ptrs.resize(buffer.channel_count);
×
1329

1330
        for(uint32_t c = 0; c < buffer.channel_count; ++c)
×
1331
        {
1332
          if(c < channels.size())
×
1333
          {
1334
            auto& channel = channels[c];
×
1335
            channel.resize(std::max<std::size_t>(channel.size(), e.bufferSize()));
×
1336
            ptrs[c] = const_cast<double*>(channels[c].data() + offset);
×
1337
          }
×
1338
          else
1339
          {
1340
            ptrs[c] = dummy_io_buffer.data();
×
1341
          }
1342
        }
×
1343

1344
        buffer.data64 = ptrs.data();
×
1345
      }
×
1346

1347
      this->input_buffers.push_back(buffer);
×
1348
      audio_in_idx++;
×
1349
    }
1350

1351
    // Setup output buffers
1352
    std::size_t audio_out_idx = 0;
×
1353
    const bool needs_stereo_main_out
×
1354
        = audio_ins.empty() && !audio_outs.empty()
×
1355
          && !midi_ins.empty(); // FIXME check if instrument?
×
1356
    for(ossia::audio_outlet* audio_out : audio_outs)
×
1357
    {
1358
      const auto& audio_info = this->m_expected_audio_outputs[audio_out_idx];
×
1359
      clap_audio_buffer_t buffer = dummy_audio_buffer();
×
1360
      buffer.channel_count = audio_info.channel_count;
×
1361

1362
      const int ossia_channel_count = audio_out_idx == 0 && needs_stereo_main_out
×
1363
                                          ? std::max((int)buffer.channel_count, 2)
×
1364
                                          : buffer.channel_count;
×
1365
      audio_out->data.set_channels(ossia_channel_count);
×
1366
      auto& channels = audio_out->data.get();
×
1367

1368
      auto& ptrs = output_channel_ptrs.emplace_back();
×
1369
      ptrs.resize(buffer.channel_count);
×
1370

1371
      for(uint32_t c = 0; c < ossia_channel_count; ++c)
×
1372
      {
1373
        channels[c].resize(e.bufferSize());
×
1374
      }
×
1375
      for(uint32_t c = 0; c < buffer.channel_count; ++c)
×
1376
      {
1377
        ptrs[c] = channels[c].data() + offset;
×
1378
      }
×
1379

1380
      buffer.data64 = ptrs.data();
×
1381
      this->output_buffers.push_back(buffer);
×
1382
      audio_out_idx++;
×
1383
    }
1384

1385
    // Pad both buffer lists *before* taking .data() pointers so we don't
1386
    // hand the plugin a stale pointer after a reallocation, and so the two
1387
    // counts actually match what the plugin is told below.
1388
    while(this->input_buffers.size() < m_expected_audio_inputs.size())
×
1389
      this->input_buffers.push_back(dummy_audio_buffer());
×
1390
    while(this->output_buffers.size() < m_expected_audio_outputs.size())
×
1391
      this->output_buffers.push_back(dummy_audio_buffer());
×
1392

1393
    clap_process_t process{};
×
1394
    process.frames_count = samples;
×
1395
    process.audio_inputs = this->input_buffers.data();
×
1396
    process.audio_outputs = this->output_buffers.data();
×
1397
    process.audio_inputs_count = m_expected_audio_inputs.size();
×
1398
    process.audio_outputs_count = m_expected_audio_outputs.size();
×
1399
    do_process(process, m_input_events, m_output_events);
×
1400

1401
    // Basic mono instrument case (e.g. Nekobi): only duplicate if the plug-in
1402
    // really has a mono main out. For ≥2-channel outputs the right channel is
1403
    // valid and must not be clobbered.
1404
    if(needs_stereo_main_out && !m_expected_audio_outputs.empty()
×
1405
       && m_expected_audio_outputs[0].channel_count == 1)
×
1406
    {
1407
      auto& l = audio_outs[0]->data.channel(0);
×
1408
      auto& r = audio_outs[0]->data.channel(1);
×
1409
      r.assign(l.begin(), l.end());
×
1410
    }
×
1411
  }
×
1412
};
1413

1414
// Special case for monophonic nodes
1415
class clap_node_mono : public clap_node_base
1416
{
1417
public:
1418
  // Declared early so member function signatures (make_poly_instance) and the
1419
  // m_incoming queue declared further down can refer to it.
1420
  struct poly_plugin
1421
  {
1422
    const clap_plugin_t* plugin{};
1423
    bool activated{};
1424
    bool processing{};
1425
    operator const clap_plugin_t*() const noexcept { return plugin; }
×
1426
  };
1427

1428
  clap_node_mono(
×
1429
      const Clap::Model& proc, Clap::PluginHandle& handle, int sampleRate, int bs)
1430
      : clap_node_base{proc}
×
1431
      , m_instance{handle}
×
1432
      , m_plugin_id{proc.pluginId().toUtf8()}
×
1433
  {
×
1434
    // Pre-reserve enough capacity that the dynamic grower (which feeds
1435
    // m_poly from the audio thread via drain_incoming → push_back) never
1436
    // triggers a reallocation in normal use. 256 * sizeof(poly_plugin)
1437
    // ≈ 4 kB up front, and covers up to 256 channels of polyphony without
1438
    // any audio-thread malloc; beyond that vector will still grow, just
1439
    // with a non-RT-friendly reallocation cost each doubling.
1440
    m_poly.reserve(256);
×
1441
    m_poly.push_back({handle.plugin, false});
×
1442
    if(handle.activated)
×
1443
      (void)deactivate_plugin(handle.plugin);
×
1444
    m_poly.back().activated = activate_plugin(m_instance.plugin, sampleRate, bs);
×
1445
    // Mirror the activation state on the shared handle so that
1446
    // Clap::Model::~Model / resetExecution can drive the deactivate of
1447
    // m_poly[0] from the main thread, symmetrically with clap_node.
1448
    handle.activated = m_poly.back().activated;
×
1449

1450
    // The constructor runs on the main thread, so create_plugin/init are
1451
    // spec-correct here. If any of the extra instances fail to construct we
1452
    // tear down the ones we already built so we never leak plugin handles.
1453
    try
1454
    {
1455
      for(int i = 0; i < 7; i++)
×
1456
        add_poly_instance(sampleRate, bs);
×
1457
    }
×
1458
    catch(...)
1459
    {
1460
      destroy_extra_instances();
×
1461
      throw;
×
1462
    }
×
1463
  }
×
1464

1465
  void add_poly_instance(int sampleRate, int bs)
×
1466
  {
1467
    m_poly.push_back(make_poly_instance(sampleRate, bs, /*state*/ {}));
×
1468
  }
×
1469

1470
  // [main-thread] Build a fresh, init'd, activated polyphonic instance.
1471
  // Optionally clones state into it via clap.state (so AIDA-X & friends
1472
  // keep their loaded model / preset on each instance).
1473
  // Throws std::runtime_error on create_plugin / init failure.
1474
  poly_plugin make_poly_instance(int sampleRate, int bs, const QByteArray& state)
×
1475
  {
1476
    poly_plugin p{nullptr, false, false};
×
1477
    p.plugin = m_instance.factory->create_plugin(
×
1478
        m_instance.factory, &m_instance.host, m_plugin_id.data());
×
1479
    if(!p.plugin)
×
1480
      throw std::runtime_error("Could not create plug-in instance");
×
1481

1482
    if(!p.plugin->init(p.plugin))
×
1483
    {
1484
      p.plugin->destroy(p.plugin);
×
1485
      throw std::runtime_error("Could not init plug-in instance");
×
1486
    }
1487
    // Apply the snapshot *before* activate, matching how Model::loadPlugin
1488
    // restores state for the primary instance.
1489
    apply_clap_state(p.plugin, state);
×
1490
    p.activated = activate_plugin(p.plugin, sampleRate, bs);
×
1491
    return p;
×
1492
  }
×
1493

1494
  // [audio-thread] Called by grow_pool_tick via in_exec.
1495
  void append_poly(poly_plugin p) noexcept { m_poly.push_back(p); }
×
1496

1497
  // [audio-thread] Tell the grower we need at least `n` total instances.
1498
  // Monotonically-increasing: a brief drop to a smaller channel count
1499
  // does not cause us to shrink the pool.
1500
  void request_pool_size(std::size_t n) noexcept
×
1501
  {
1502
    auto prev = m_requested_pool.load(std::memory_order_relaxed);
×
1503
    while(n > prev
×
1504
          && !m_requested_pool.compare_exchange_weak(
×
1505
              prev, n, std::memory_order_release, std::memory_order_relaxed))
×
1506
      ;
1507
  }
×
1508

1509
  // Tear down extra polyphonic instances (skipping m_poly[0], which is
1510
  // owned by the Clap::Model). Used by the constructor's catch and by the
1511
  // destructor's queued main-thread cleanup.
1512
  void destroy_extra_instances() noexcept
×
1513
  {
1514
    for(std::size_t i = 1; i < m_poly.size(); ++i)
×
1515
    {
1516
      auto& p = m_poly[i];
×
1517
      if(!p.plugin)
×
1518
        continue;
×
1519
      if(p.processing)
×
1520
      {
1521
        p.plugin->stop_processing(p.plugin);
×
1522
        p.processing = false;
×
1523
      }
×
1524
      if(p.activated)
×
1525
      {
1526
        p.plugin->deactivate(p.plugin);
×
1527
        p.activated = false;
×
1528
      }
×
1529
      p.plugin->destroy(p.plugin);
×
1530
      p.plugin = nullptr;
×
1531
    }
×
1532
  }
×
1533

1534
  ~clap_node_mono()
×
1535
  {
×
1536
    // Stop any instance that was still processing. ~clap_node_mono runs on
1537
    // the audio thread, so stop_processing is allowed here (it is the only
1538
    // CLAP entry point we may call from there). Deactivation and destruction
1539
    // of the extra instances is deferred to the main thread below.
1540
    for(std::size_t i = 0; i < m_poly.size(); ++i)
×
1541
    {
1542
      if(m_poly[i].processing)
×
1543
      {
1544
        m_poly[i].plugin->stop_processing(m_poly[i].plugin);
×
1545
        m_poly[i].processing = false;
×
1546
      }
×
1547
    }
×
1548

1549
    // m_poly[0] is the Model's shared handle; deactivated by Model::~Model.
1550
    // Orphaned grower output is cleaned up via grow_pool_tick's weak_ptr.
1551
    QMetaObject::invokeMethod(
×
1552
        QCoreApplication::instance(),
×
1553
        [poly = std::move(m_poly)]() mutable {
×
1554
      auto destroy = [](const poly_plugin& p) {
×
1555
        if(!p.plugin)
×
1556
          return;
×
1557
        if(p.activated)
×
1558
          p.plugin->deactivate(p.plugin);
×
1559
        p.plugin->destroy(p.plugin);
×
1560
      };
×
1561
      for(std::size_t i = 1; i < poly.size(); ++i)
×
1562
        destroy(poly[i]);
×
1563
    });
×
1564
  }
×
1565

1566
  void do_process(
×
1567
      const clap_plugin_t* plug, clap_process_t& process, event_storage& input_storage,
1568
      event_storage& output_storage, int current_channel)
1569
  {
1570
    // Process audio
1571
    process.steady_time = -1;
×
1572
    process.transport = &m_current_transport;
×
1573

1574
    // Setup input events
1575
    clap_input_events evs{
×
1576
        .ctx = &input_storage,
×
1577
        .size = +[](const clap_input_events* list) -> uint32_t {
×
1578
      auto* storage = static_cast<event_storage*>(list->ctx);
×
1579
      return storage->all_events.size();
×
1580
    },
1581
        .get = +[](const clap_input_events* list,
×
1582
                   uint32_t index) -> const clap_event_header_t* {
1583
      auto* storage = static_cast<event_storage*>(list->ctx);
×
1584
      if(index < storage->all_events.size())
×
1585
        return storage->all_events[index];
×
1586
      return nullptr;
×
1587
    }};
×
1588

1589
    clap_output_events_t o_evs{
×
1590
        .ctx = &output_storage,
×
1591
        .try_push = [](const struct clap_output_events* list,
×
1592
                       const clap_event_header_t* event) -> bool {
1593
      auto* storage = static_cast<event_storage*>(list->ctx);
×
1594
      if(!event || event->space_id != CLAP_CORE_EVENT_SPACE_ID)
×
1595
        return false;
×
1596
      if(event->type == CLAP_EVENT_PARAM_VALUE
×
1597
         && event->size >= sizeof(clap_event_param_value_t))
×
1598
      {
1599
        storage->param_events.push_back(
×
1600
            *reinterpret_cast<const clap_event_param_value_t*>(event));
×
1601
        return true;
×
1602
      }
1603
      return false;
×
1604
    }};
×
1605

1606
    process.in_events = &evs;
×
1607
    process.out_events = &o_evs;
×
1608

1609
    // We track m_last_status mainly for diagnostics in the mono path. We
1610
    // don't act on CLAP_PROCESS_SLEEP for monophonic-faked plugins because
1611
    // each m_poly[i] has independent processing state and a per-channel
1612
    // skip would require per-channel status tracking + audio-input
1613
    // variation detection per channel — more bookkeeping than it's worth.
1614
    m_last_status = plug->process(plug, &process);
×
1615
    m_deferred_midi.clear();
×
1616
    (void)current_channel;
1617
  }
×
1618

1619
  // Snapshot voice-0 params into voices 1+ so UI edits propagate (CLAP UI binds to voice 0).
1620
  void replicate_voice0_state(
×
1621
      const clap_plugin_t* plug, event_storage& input_storage) noexcept
1622
  {
1623
    auto params = this->handle->ext_params;
×
1624
    if(!params)
×
1625
      return;
×
1626
    const int param_count = params->count(plug);
×
1627
    if(param_count <= 0)
×
1628
      return;
×
1629

1630
    const int orig = input_storage.param_events.size();
×
1631
    int cur = orig;
×
1632
    input_storage.param_events.resize(orig + param_count);
×
1633
    clap_event_param_value_t* cur_p = &input_storage.param_events[cur];
×
1634
    for(auto& p : m_param_ins)
×
1635
    {
1636
      // Per-voice slice would be clobbered by voice-0's value here.
1637
      if(m_overridden_params.contains(p.id))
×
1638
        continue;
×
1639
      double current_value;
1640
      if(params->get_value(plug, p.id, &current_value))
×
1641
      {
1642
        clap_event_param_value_t& param_event = *cur_p;
×
1643
        param_event.header.size = sizeof(clap_event_param_value_t);
×
1644
        param_event.header.time = 0;
×
1645
        param_event.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
1646
        param_event.header.type = CLAP_EVENT_PARAM_VALUE;
×
1647
        param_event.header.flags = CLAP_EVENT_IS_LIVE;
×
1648
        param_event.param_id = p.id;
×
1649
        param_event.cookie = p.cookie;
×
1650
        param_event.note_id = -1;
×
1651
        param_event.port_index = -1;
×
1652
        param_event.channel = -1;
×
1653
        param_event.key = -1;
×
1654
        param_event.value = current_value;
×
1655
        ++cur;
×
1656
        ++cur_p;
×
1657
      }
×
1658
    }
1659

1660
    if(cur > orig)
×
1661
    {
1662
      auto it = std::upper_bound(
×
1663
          input_storage.all_events.begin(), input_storage.all_events.end(), 0,
×
1664
          [](auto& t1, auto& ev2) { return t1 < ev2->time; });
×
1665
      const auto r = std::span<clap_event_param_value_t>(
×
1666
                         input_storage.param_events.data() + orig,
×
1667
                         input_storage.param_events.data() + cur)
×
1668
                     | std::views::transform([](clap_event_param_value_t& elem) {
×
1669
        return &elem.header;
×
1670
      });
1671
      input_storage.all_events.insert(it, std::begin(r), std::end(r));
×
1672
    }
×
1673
  }
×
1674

1675
  // Must run after prepare_input_events and before the per-voice loop.
1676
  void prepare_voice_overrides(uint32_t samples) noexcept
×
1677
  {
1678
    m_voice_overrides.resize(m_poly.size());
×
1679
    for(auto& vec : m_voice_overrides)
×
1680
      vec.clear();
×
1681
    m_overridden_params.clear();
×
1682

1683
    for(std::size_t i = 0; i < parameter_ins.size(); ++i)
×
1684
    {
1685
      const auto& data = parameter_ins[i]->data.get_data();
×
1686
      if(data.empty())
×
1687
        continue;
×
1688
      const auto& param_info = m_param_ins[i];
×
1689
      for(const auto& tv : data)
×
1690
      {
1691
        if(!is_vector_value(tv.value))
×
1692
          continue;
×
1693
        m_overridden_params.insert(param_info.id);
×
1694
        const int64_t t = tv.timestamp;
×
1695
        const uint32_t time
×
1696
            = t <= 0
×
1697
                  ? 0u
1698
                  : static_cast<uint32_t>(
1699
                        std::min<int64_t>(t, samples > 0 ? samples - 1 : 0));
×
1700
        for(std::size_t v = 0; v < m_poly.size(); ++v)
×
1701
        {
1702
          auto sliced = voice_control_value(tv.value, v);
×
1703
          if(!sliced)
×
1704
            continue;
×
1705
          const double value = std::clamp(
×
1706
              *sliced, param_info.min_value, param_info.max_value);
×
1707
          clap_event_param_value_t ev{};
×
1708
          ev.header.size = sizeof(clap_event_param_value_t);
×
1709
          ev.header.time = time;
×
1710
          ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
×
1711
          ev.header.type = CLAP_EVENT_PARAM_VALUE;
×
1712
          ev.header.flags = CLAP_EVENT_IS_LIVE;
×
1713
          ev.param_id = param_info.id;
×
1714
          ev.cookie = param_info.cookie;
×
1715
          ev.note_id = -1;
×
1716
          ev.port_index = -1;
×
1717
          ev.channel = -1;
×
1718
          ev.key = -1;
×
1719
          ev.value = value;
×
1720
          m_voice_overrides[v].push_back(ev);
×
1721
        }
×
1722
      }
1723
    }
×
1724
  }
×
1725

1726
  // Compose shared base + this voice's overrides into one sorted event stream.
1727
  void build_voice_input(event_storage& dst, std::size_t voice_idx)
×
1728
  {
1729
    dst.midi_events = m_input_events.midi_events;
×
1730
    dst.midi2_events = m_input_events.midi2_events;
×
1731
    dst.note_events = m_input_events.note_events;
×
1732
    dst.param_events = m_input_events.param_events;
×
1733
    dst.sysex_events = m_input_events.sysex_events;
×
1734
    dst.sysex_data = m_input_events.sysex_data;
×
1735
    const auto& overrides = m_voice_overrides[voice_idx];
×
1736
    dst.param_events.insert(
×
1737
        dst.param_events.end(), overrides.begin(), overrides.end());
×
1738

1739
    dst.all_events.clear();
×
1740
    dst.all_events.reserve(
×
1741
        dst.midi_events.size() + dst.midi2_events.size() + dst.note_events.size()
×
1742
        + dst.param_events.size() + dst.sysex_events.size());
×
1743
    for(auto& ev : dst.midi_events)
×
1744
      dst.all_events.push_back(reinterpret_cast<clap_event_header_t*>(&ev));
×
1745
    for(auto& ev : dst.midi2_events)
×
1746
      dst.all_events.push_back(reinterpret_cast<clap_event_header_t*>(&ev));
×
1747
    for(auto& ev : dst.note_events)
×
1748
      dst.all_events.push_back(reinterpret_cast<clap_event_header_t*>(&ev));
×
1749
    for(auto& ev : dst.param_events)
×
1750
      dst.all_events.push_back(reinterpret_cast<clap_event_header_t*>(&ev));
×
1751
    for(auto& ev : dst.sysex_events)
×
1752
      dst.all_events.push_back(reinterpret_cast<clap_event_header_t*>(&ev));
×
1753
    std::sort(
×
1754
        dst.all_events.begin(), dst.all_events.end(),
×
1755
        [](const clap_event_header_t* a, const clap_event_header_t* b) {
×
1756
      return a->time < b->time;
×
1757
    });
1758
  }
×
1759

1760
  PluginHandle& m_instance;
1761
  std::vector<poly_plugin> m_poly;
1762
  std::string m_plugin_id;
1763

1764
  std::atomic<std::size_t> m_requested_pool{0};
×
1765

1766
  std::vector<std::vector<clap_event_param_value_t>> m_voice_overrides;
1767

1768
  ossia::hash_set<clap_id> m_overridden_params;
1769

1770
  event_storage m_voice_input;
1771
};
1772

1773
class clap_node_mono_32 final : public clap_node_mono
1774
{
1775
  std::vector<float> input_channel_storage;
1776
  std::vector<float> output_channel_storage;
1777

1778
public:
1779
  using clap_node_mono::clap_node_mono;
1780

1781
  void run(const ossia::token_request& t, ossia::exec_state_facade e) noexcept override
×
1782
  {
1783
    if(!m_instance.plugin)
×
1784
      return;
×
1785

1786
    auto [offset, samples] = e.timings(t);
×
1787
    if(samples == 0)
×
1788
    {
1789
      // Never call a plug-in with an empty block; CLAP bounds the frame count
1790
      // at [1, INT32_MAX]. What the tick carried goes out at the top of the
1791
      // next real one.
1792
      stash_midi();
×
1793
      return;
×
1794
    }
1795

1796
    m_current_transport = make_transport(t, e);
×
1797

1798
    // Clear previous data
1799
    input_channel_storage.clear();
×
1800
    output_channel_storage.clear();
×
1801
    input_channel_storage.resize(samples);
×
1802
    output_channel_storage.resize(samples);
×
1803

1804
    prepare_input_events(offset, samples);
×
1805
    prepare_voice_overrides(samples);
×
1806

1807
    float* ins_pointer[1]{input_channel_storage.data()};
×
1808
    float* outs_pointer[1]{output_channel_storage.data()};
×
1809

1810
    // Setup audio input buffers
1811
    const auto audio_in = audio_ins[0];
×
1812
    const auto audio_out = audio_outs[0];
×
1813
    auto& in_channels = audio_in->data.get();
×
1814
    const auto upstream_channels = audio_in->data.channels();
×
1815
    if(upstream_channels == 0)
×
1816
      return;
×
1817
    request_pool_size(upstream_channels);
×
1818
    const std::size_t poly_channels
×
1819
        = std::min<std::size_t>(upstream_channels, m_poly.size());
×
1820
    // FIXME constant mode of audio inputs
1821
    if(std::all_of(
×
1822
           audio_in->data.begin(), audio_in->data.end(),
×
1823
           [](const auto& channel) { return channel.size() == 0; }))
×
1824
      return;
×
1825
    audio_out->data.set_channels(poly_channels);
×
1826
    auto& out_channels = audio_out->data.get();
×
1827
    const uint32_t buffer_size = e.bufferSize();
×
1828
    clap_audio_buffer_t in_buffer = dummy_audio_buffer();
×
1829
    clap_audio_buffer_t out_buffer = dummy_audio_buffer();
×
1830
    in_buffer.channel_count = 1;
×
1831
    in_buffer.data32 = ins_pointer;
×
1832
    out_buffer.channel_count = 1;
×
1833
    out_buffer.data32 = outs_pointer;
×
1834

1835
    for(std::size_t current_channel = 0; current_channel < poly_channels;
×
1836
        ++current_channel)
×
1837
    {
1838
      // 0. Activate plug-in if necessary
1839
      auto& cur = m_poly[current_channel];
×
1840
      if(!cur.activated)
×
1841
        return;
×
1842

1843
      if(!cur.processing)
×
1844
      {
1845
        cur.processing = start_plugin(cur.plugin);
×
1846
        if(!cur.processing)
×
1847
          return;
×
1848
      }
×
1849

1850
      auto& channel = in_channels[current_channel];
×
1851

1852
      // 1. Copy input (extend the upstream buffer to the full block size in
1853
      //    case the producer wrote fewer frames than the engine block).
1854
      {
1855
        channel.resize(std::max<std::size_t>(channel.size(), buffer_size));
×
1856
        SCORE_ASSERT(input_channel_storage.size() >= samples);
×
1857
        const double* src = channel.data() + offset;
×
1858
        float* dst = input_channel_storage.data();
×
1859
        for(uint32_t s = 0; s < samples; ++s)
×
1860
          dst[s] = static_cast<float>(src[s]);
×
1861
      }
1862

1863
      // 2. Clear output
1864
      std::fill_n(output_channel_storage.data(), samples, 0);
×
1865

1866
      // 3. Process this channel
1867
      clap_process_t process{};
×
1868
      process.frames_count = samples;
×
1869
      process.audio_inputs = &in_buffer;
×
1870
      process.audio_outputs = &out_buffer;
×
1871
      process.audio_inputs_count = 1;
×
1872
      process.audio_outputs_count = 1;
×
1873
      build_voice_input(m_voice_input, current_channel);
×
1874
      do_process(cur, process, m_voice_input, m_output_events, current_channel);
×
1875
      if(current_channel == 0)
×
1876
        replicate_voice0_state(cur, m_input_events);
×
1877

1878
      // 4. Copy float back to matching output channel. Resize to the full
1879
      //    block size first — writing samples frames starting at `offset`
1880
      //    would otherwise overflow when `offset > 0`.
1881
      {
1882
        auto& out_channel = out_channels[current_channel];
×
1883
        out_channel.resize(std::max<std::size_t>(out_channel.size(), buffer_size));
×
1884
        const float* src = output_channel_storage.data();
×
1885
        double* dst = out_channel.data() + offset;
×
1886
        for(uint32_t s = 0; s < samples; ++s)
×
1887
          dst[s] = static_cast<double>(src[s]);
×
1888
      }
1889
    }
×
1890

1891
    dispatch_param_outputs();
×
1892
  }
×
1893
};
1894

1895
class clap_node_mono_64 final : public clap_node_mono
1896
{
1897
public:
1898
  using clap_node_mono::clap_node_mono;
1899
  void run(const ossia::token_request& t, ossia::exec_state_facade e) noexcept override
×
1900
  {
1901
    if(!m_instance.plugin)
×
1902
      return;
×
1903

1904
    auto [offset, samples] = e.timings(t);
×
1905
    if(samples == 0)
×
1906
    {
1907
      // Never call a plug-in with an empty block; CLAP bounds the frame count
1908
      // at [1, INT32_MAX]. What the tick carried goes out at the top of the
1909
      // next real one.
1910
      stash_midi();
×
1911
      return;
×
1912
    }
1913

1914
    m_current_transport = make_transport(t, e);
×
1915

1916
    prepare_input_events(offset, samples);
×
1917
    prepare_voice_overrides(samples);
×
1918

1919
    double* ins_pointer[1]{};
×
1920
    double* outs_pointer[1]{};
×
1921

1922
    // Setup audio input buffers
1923
    const auto audio_in = audio_ins[0];
×
1924
    const auto audio_out = audio_outs[0];
×
1925
    const auto upstream_channels = audio_in->data.channels();
×
1926
    if(upstream_channels == 0)
×
1927
      return;
×
1928
    request_pool_size(upstream_channels);
×
1929
    const std::size_t poly_channels
×
1930
        = std::min<std::size_t>(upstream_channels, m_poly.size());
×
1931
    // FIXME constant mode of audio inputs
1932
    if(std::all_of(
×
1933
           audio_in->data.begin(), audio_in->data.end(),
×
1934
           [](const auto& channel) { return channel.size() == 0; }))
×
1935
      return;
×
1936
    const uint32_t buffer_size = e.bufferSize();
×
1937
    for(auto& channel : audio_in->data.get())
×
1938
    {
1939
      channel.resize(std::max<std::size_t>(channel.size(), buffer_size));
×
1940
    }
1941
    audio_out->data.set_channels(poly_channels);
×
1942
    auto& out_channels = audio_out->data.get();
×
1943
    for(std::size_t c = 0; c < poly_channels; ++c)
×
1944
    {
1945
      out_channels[c].resize(
×
1946
          std::max<std::size_t>(out_channels[c].size(), buffer_size));
×
1947
    }
×
1948
    clap_audio_buffer_t in_buffer = dummy_audio_buffer();
×
1949
    clap_audio_buffer_t out_buffer = dummy_audio_buffer();
×
1950
    in_buffer.channel_count = 1;
×
1951
    in_buffer.data64 = ins_pointer;
×
1952
    out_buffer.channel_count = 1;
×
1953
    out_buffer.data64 = outs_pointer;
×
1954

1955
    auto& in_channels = audio_in->data.get();
×
1956
    for(std::size_t current_channel = 0; current_channel < poly_channels;
×
1957
        ++current_channel)
×
1958
    {
1959
      // 0. Activate plug-in if necessary
1960
      auto& cur = m_poly[current_channel];
×
1961
      if(!cur.activated)
×
1962
        return;
×
1963

1964
      if(!cur.processing)
×
1965
      {
1966
        cur.processing = start_plugin(cur.plugin);
×
1967
        if(!cur.processing)
×
1968
          return;
×
1969
      }
×
1970

1971
      // 1. Point the plugin at the right slice of the buffer.
1972
      //    The previous code passed channel.data()/out_channel.data() with
1973
      //    no `offset`, which made the plugin process frames 0..samples
1974
      //    regardless of where the current tick actually started.
1975
      ins_pointer[0] = const_cast<double*>(in_channels[current_channel].data())
×
1976
                       + offset;
×
1977
      auto* out_chan = out_channels[current_channel].data() + offset;
×
1978
      outs_pointer[0] = out_chan;
×
1979
      std::fill_n(out_chan, samples, 0.0);
×
1980

1981
      // 2. Process this channel
1982
      clap_process_t process{};
×
1983
      process.frames_count = samples;
×
1984
      process.audio_inputs = &in_buffer;
×
1985
      process.audio_outputs = &out_buffer;
×
1986
      process.audio_inputs_count = 1;
×
1987
      process.audio_outputs_count = 1;
×
1988
      build_voice_input(m_voice_input, current_channel);
×
1989
      do_process(cur, process, m_voice_input, m_output_events, current_channel);
×
1990
      if(current_channel == 0)
×
1991
        replicate_voice0_state(cur, m_input_events);
×
1992
    }
×
1993

1994
    dispatch_param_outputs();
×
1995
  }
×
1996
};
1997

1998
struct clap_process final : public ossia::node_process
1999
{
2000
  using ossia::node_process::node_process;
2001
  void start() override { }
×
2002
  void stop() override
×
2003
  {
2004
    auto* clap = static_cast<clap_node*>(this->node.get());
×
2005

2006
    if(clap->m_processing)
×
2007
    {
2008
      clap->stop_plugin(clap->m_instance.plugin);
×
2009
      clap->m_processing = false;
×
2010
    }
×
2011
  }
×
2012
  void pause() override { }
×
2013
  void resume() override { }
×
2014
};
2015
struct clap_mono_process final : public ossia::node_process
2016
{
2017
  using ossia::node_process::node_process;
2018
  void start() override { }
×
2019
  void stop() override
×
2020
  {
2021
    auto* clap = static_cast<clap_node_mono*>(this->node.get());
×
2022

2023
    // Stop each polyphonic instance individually. The old version always
2024
    // stopped m_instance.plugin (m_poly[0]) once per processing entry,
2025
    // leaving instances 1..N in {active, processing} on shutdown, which
2026
    // violates the CLAP state machine.
2027
    for(auto& plug : clap->m_poly)
×
2028
    {
2029
      if(plug.processing && plug.plugin)
×
2030
      {
2031
        plug.plugin->stop_processing(plug.plugin);
×
2032
        plug.processing = false;
×
2033
      }
×
2034
    }
2035
  }
×
2036
  void pause() override { }
×
2037
  void resume() override { }
×
2038
};
2039

2040
Executor::Executor(Clap::Model& proc, const Execution::Context& ctx, QObject* parent)
×
2041
    : Execution::ProcessComponent_T<Clap::Model, ossia::node_process>{
×
2042
          proc, ctx, "ClapComponent", parent}
×
2043
{
×
2044
  proc.setExecuting(true);
×
2045

2046
  const auto& h = proc.handle();
×
2047
  if(!h)
×
2048
    throw std::runtime_error("Plug-in unavailable");
×
2049

2050
  const bool monophonic = proc.midiInputs().size() == 0 && proc.audioInputs().size() == 1
×
2051
                          && proc.audioInputs()[0].channel_count == 1
×
2052
                          && proc.audioOutputs().size() == 1
×
2053
                          && proc.audioOutputs()[0].channel_count == 1;
×
2054

2055
  auto& e = *ctx.execState;
×
2056
  std::shared_ptr<clap_node_base> clap{};
×
2057
  if(monophonic)
×
2058
  {
2059
    if(proc.supports64())
×
2060
    {
2061
      qDebug() << "CLAP: clap_node_mono_64";
×
2062
      auto node = ossia::make_node<clap_node_mono_64>(
×
2063
          *ctx.execState, proc, *h, e.sampleRate, e.bufferSize);
×
2064
      clap = node;
×
2065
      this->node = node;
×
2066
      m_ossia_process = std::make_shared<clap_mono_process>(node);
×
2067
    }
×
2068
    else
2069
    {
2070
      qDebug() << "CLAP: clap_node_mono_32";
×
2071
      auto node = ossia::make_node<clap_node_mono_32>(
×
2072
          *ctx.execState, proc, *h, e.sampleRate, e.bufferSize);
×
2073
      clap = node;
×
2074
      this->node = node;
×
2075
      m_ossia_process = std::make_shared<clap_mono_process>(node);
×
2076
    }
×
2077

2078
    // Drive the polyphonic-pool grower on the main thread. The mono node
2079
    // pre-allocates 8 instances in its constructor; if the upstream channel
2080
    // count exceeds that the audio thread bumps m_requested_pool and this
2081
    // timer creates more on the main thread (CLAP requires create_plugin /
2082
    // init / activate / state.load to all run there).
2083
    constexpr std::size_t kInitialPoly = 8;
×
2084
    m_pool_sample_rate = e.sampleRate;
×
2085
    m_pool_buffer_size = e.bufferSize;
×
2086
    m_pool_pushed = kInitialPoly;
×
2087
    m_pool_max_requested = kInitialPoly;
×
2088
    m_grow_timer = new QTimer(this);
×
2089
    m_grow_timer->setInterval(50);
×
2090
    connect(m_grow_timer, &QTimer::timeout, this, [this] { grow_pool_tick(); });
×
2091
    m_grow_timer->start();
×
2092
  }
×
2093
  else
2094
  {
2095
    if(proc.supports64())
×
2096
    {
2097
      qDebug() << "CLAP: clap_node_64";
×
2098
      auto node = ossia::make_node<clap_node_64>(
×
2099
          *ctx.execState, proc, *h, e.sampleRate, e.bufferSize);
×
2100
      clap = node;
×
2101
      this->node = node;
×
2102
      m_ossia_process = std::make_shared<clap_process>(node);
×
2103
    }
×
2104
    else
2105
    {
2106
      qDebug() << "CLAP: clap_node_32";
×
2107
      auto node = ossia::make_node<clap_node_32>(
×
2108
          *ctx.execState, proc, *h, e.sampleRate, e.bufferSize);
×
2109
      clap = node;
×
2110
      this->node = node;
×
2111
      m_ossia_process = std::make_shared<clap_process>(node);
×
2112
    }
×
2113
  }
2114

2115
  SCORE_ASSERT(clap);
×
2116

2117
  // Connect control inlet changes to the executor
2118
  // Note: only reelvant for the polyphonic mode as the main mode is done on the
2119
  // main thread
2120
  std::size_t control_idx = 0;
×
2121
  for(auto* inlet : proc.inlets())
×
2122
  {
2123
    if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
×
2124
    {
2125
      auto* inl = clap->parameter_ins[control_idx];
×
2126

2127
      control->setupExecution(*inl, this);
×
2128
      connect(
×
2129
          control, &Process::ControlInlet::valueChanged, this,
×
2130
          [this, inl](const ossia::value& v) {
×
2131
        if(this->process().currentlyReadingValues)
×
2132
          return;
×
2133
        auto weak_self = std::weak_ptr{this->node};
×
2134
        in_exec([inl, val = v, node = weak_self]() mutable {
×
2135
          if(auto n = node.lock())
×
2136
          {
2137
            inl->target<ossia::value_port>()->write_value(std::move(val), 0);
×
2138
          }
×
2139
        });
×
2140
      });
×
2141
      control_idx++;
×
2142
    }
×
2143
  }
2144
}
×
2145

2146
void Executor::grow_pool_tick()
×
2147
{
2148
  auto mono = std::dynamic_pointer_cast<clap_node_mono>(this->node);
×
2149
  if(!mono)
×
2150
    return;
×
2151

2152
  // Promote brief spikes into the long-term high-water mark so we don't
2153
  // miss a 2 → 512 → 2 transient.
2154
  const auto requested
×
2155
      = mono->m_requested_pool.load(std::memory_order_acquire);
×
2156
  if(requested > m_pool_max_requested)
×
2157
    m_pool_max_requested = requested;
×
2158

2159
  if(m_pool_pushed >= m_pool_max_requested)
×
2160
    return;
×
2161

2162
  // Snapshot primary's state so new instances inherit loaded models/presets.
2163
  auto handle = this->process().handle();
×
2164
  if(!handle || !handle->plugin)
×
2165
    return;
×
2166
  const QByteArray state = snapshot_clap_state(handle->plugin);
×
2167

2168
  // Few per tick: each instance can be expensive (e.g. AIDA-X neural model load).
2169
  constexpr std::size_t kBatch = 4;
×
2170
  const std::size_t to_add
×
2171
      = std::min(kBatch, m_pool_max_requested - m_pool_pushed);
×
2172
  auto weak_node = std::weak_ptr{this->node};
×
2173
  for(std::size_t i = 0; i < to_add; ++i)
×
2174
  {
2175
    try
2176
    {
2177
      auto p
2178
          = mono->make_poly_instance(m_pool_sample_rate, m_pool_buffer_size, state);
×
2179
      // Orphaned if the node dies before in_exec fires; post destroy to main thread.
2180
      in_exec([weak_node, p]() mutable {
×
2181
        if(auto n = weak_node.lock())
×
2182
        {
2183
          static_cast<clap_node_mono*>(n.get())->append_poly(p);
×
2184
        }
×
2185
        else
2186
        {
2187
          QMetaObject::invokeMethod(QCoreApplication::instance(), [p] {
×
2188
            if(!p.plugin)
×
2189
              return;
×
2190
            if(p.activated)
×
2191
              p.plugin->deactivate(p.plugin);
×
2192
            p.plugin->destroy(p.plugin);
×
2193
          });
×
2194
        }
2195
      });
×
2196
      ++m_pool_pushed;
×
2197
    }
×
2198
    catch(const std::exception& ex)
2199
    {
2200
      qWarning() << "CLAP: failed to grow polyphonic pool:" << ex.what();
×
2201
      break;
2202
    }
×
2203
  }
×
2204
}
×
2205
}
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