File: zerberus.cpp

package info (click to toggle)
musescore2 2.3.2%2Bdfsg4-15~bpo10%2B1
  • links: PTS, VCS
  • area: main
  • in suites: buster-backports
  • size: 168,212 kB
  • sloc: cpp: 262,317; xml: 176,707; sh: 3,377; ansic: 1,384; python: 356; makefile: 228; perl: 82; pascal: 78
file content (467 lines) | stat: -rw-r--r-- 14,814 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//=============================================================================
//  Zerberus
//  Zample player
//
//  Copyright (C) 2013 Werner Schweer
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2
//  as published by the Free Software Foundation and appearing in
//  the file LICENCE.GPL
//=============================================================================

#include "mscore/preferences.h"
#include "synthesizer/event.h"
#include "synthesizer/midipatch.h"

#include "zerberus.h"
#include "zerberusgui.h"
#include "voice.h"
#include "channel.h"
#include "instrument.h"
#include "zone.h"

#include <stdio.h>

bool Zerberus::initialized = false;
// instruments can be shared between several zerberus instances
std::list<ZInstrument*> Zerberus::globalInstruments;

//---------------------------------------------------------
//   createZerberus
//---------------------------------------------------------

Ms::Synthesizer* createZerberus()
      {
      return new Zerberus();
      }

//---------------------------------------------------------
//   Zerberus
//---------------------------------------------------------

Zerberus::Zerberus()
   : Synthesizer()
      {
      if (!initialized) {
            initialized = true;
            Voice::init();
            }
      
      freeVoices.init(this);
      for (int i = 0; i < MAX_CHANNEL; ++i)
            _channel[i] = new Channel(this, i);
      busy = true;      // no sf loaded yet
      }

//---------------------------------------------------------
//   ~Zerberus
//---------------------------------------------------------

Zerberus::~Zerberus()
      {
      busy = true;
      while (!instruments.empty()) {
            auto i  = instruments.front();
            auto it = instruments.begin();
            instruments.erase(it);

            i->setRefCount(i->refCount() - 1);
            if (i->refCount() <= 0) {
                  delete i;
                  auto it = find(globalInstruments.begin(), globalInstruments.end(), i);
                  if (it != globalInstruments.end())
                        globalInstruments.erase(it);
                  }
            }
      for (Channel* c : _channel)
            delete c;
      }

//---------------------------------------------------------
//   programChange
//---------------------------------------------------------

void Zerberus::programChange(int channel, int program)
      {
      qDebug("Zerberus programChange %d %d", channel, program);
      }

//---------------------------------------------------------
//   trigger
//    gui
//---------------------------------------------------------

void Zerberus::trigger(Channel* channel, int key, int velo, Trigger trigger, int cc, int ccVal, double durSinceNoteOn)
      {
      ZInstrument* i = channel->instrument();
      double random = (double) rand() / (double) RAND_MAX;
      for (Zone* z : i->zones()) {
            if (z->match(channel, key, velo, trigger, random, cc, ccVal)) {
                  //
                  // handle offBy voices
                  //
                  if (z->group) {
                        for (Voice* v = activeVoices; v; v = v->next()) {
                              if (v->offBy() == z->group) {
                                    if (v->offMode() == OffMode::FAST)
                                          v->stop(1);
                                    else
                                          v->stop();
                                    }
                              }
                        }

                  if (freeVoices.empty()) {
                        qDebug("Zerberus: out of voices...");
                        return;
                        }

                  Voice* voice = freeVoices.pop();
                  Q_ASSERT(voice->isOff());
                  voice->start(channel, key, velo, z, durSinceNoteOn);
                  voice->setNext(activeVoices);
                  activeVoices = voice;
                  }
            }
      }

//---------------------------------------------------------
//   processNoteOff
//---------------------------------------------------------

void Zerberus::processNoteOff(Channel* cp, int key)
      {
      for (Voice* v = activeVoices; v; v = v->next()) {
            if ((v->channel() == cp)
               && (v->key() == key)
               && (v->loopMode() != LoopMode::ONE_SHOT)
               ) {
                  if (cp->sustain() < 0x40 && !v->isStopped()) {
                        v->stop();
                        double durSinceNoteOn = v->getSamplesSinceStart() / sampleRate();
                        trigger(cp, key, v->velocity(), Trigger::RELEASE, -1, -1, durSinceNoteOn);
                        }
                  else {
                        if (v->isPlaying())
                              v->sustained();
                        }
                  }
            }
      }

//---------------------------------------------------------
//   processNoteOn
//---------------------------------------------------------

void Zerberus::processNoteOn(Channel* cp, int key, int velo)
      {
      for (Voice* v = activeVoices; v; v = v->next()) {
            if (v->channel() == cp && v->key() == key) {
                  if (v->isSustained()) {
                        // if (v->isPlaying())
                        // printf("retrigger (stop) %p\n", v);
                        v->stop(100);     // fast stop
                        }
                  }
            }
      trigger(cp, key, velo, Trigger::ATTACK, -1, -1, 0);
      }

//---------------------------------------------------------
//   process
//---------------------------------------------------------

void Zerberus::play(const Ms::PlayEvent& event)
      {
      if (busy)
            return;
      if (event.channel() >= MAX_CHANNEL)
            return;
      Channel* cp = _channel[int(event.channel())];
      if (cp->instrument() == 0) {
            // qDebug("Zerberus::play(): no instrument for channel %d", event.channel());
            return;
            }

      switch(event.type()) {
            case Ms::ME_NOTEOFF:
                  processNoteOff(cp, event.dataA());
                  break;

            case Ms::ME_NOTEON: {
                  int key = event.dataA();
                  int vel = event.dataB();
                  if (vel)
                        processNoteOn(cp, key, vel);
                  else
                        processNoteOff(cp, key);
                  }
                  break;

            case Ms::ME_CONTROLLER:
                  cp->controller(event.dataA(), event.dataB());
                  trigger(cp, -1, -1, Trigger::CC, event.dataA(), event.dataB(), 0);
                  break;

            default:
                  qDebug("Zerberus: event type 0x%02x", event.type());
                  break;
            }
      }

//---------------------------------------------------------
//   process
//    realtime
//---------------------------------------------------------

void Zerberus::process(unsigned frames, float* p, float*, float*)
      {
      if (busy)
            return;
      Voice* v = activeVoices;
      Voice* pv = 0;
      while (v) {
            v->process(frames, p);
            if (v->isOff()) {
                  if (pv)
                        pv->setNext(v->next());
                  else
                        activeVoices = v->next();
                  freeVoices.push(v);
                  }
            else
                  pv = v;
            v = v->next();
            }
      }

//---------------------------------------------------------
//   name
//---------------------------------------------------------

const char* Zerberus::name() const
      {
      return "Zerberus";
      }

//---------------------------------------------------------
//   getPatchInfo
//---------------------------------------------------------

const QList<Ms::MidiPatch*>& Zerberus::getPatchInfo() const
      {
      static QList<Ms::MidiPatch*> pl;
      qDeleteAll(pl);
      pl.clear();
      int idx = 0;
      for (ZInstrument* i : instruments) {
            Ms::MidiPatch* p = new Ms::MidiPatch { false, name(), 0, idx, i->name() };
            pl.append(p);
            ++idx;
            }
      return pl;
      }

//---------------------------------------------------------
//   allSoundsOff
//---------------------------------------------------------

void Zerberus::allSoundsOff(int channel)
      {
      allNotesOff(channel);
      }

//---------------------------------------------------------
//   allNotesOff
//---------------------------------------------------------

void Zerberus::allNotesOff(int channel)
      {
      busy = true;
      for (Voice* v = activeVoices; v; v = v->next()) {
            if (channel == -1 || (v->channel()->idx() == channel))
                  v->stop();
            }
      busy = false;
      }

//---------------------------------------------------------
//   loadSoundFonts
//---------------------------------------------------------

bool Zerberus::loadSoundFonts(const QStringList& sl)
      {
      foreach (const QString& s, sl) {
            if (!loadInstrument(s))
                  return false;
            }
      return true;
      }

//---------------------------------------------------------
//   soundFonts
//---------------------------------------------------------

QStringList Zerberus::soundFonts() const
      {
      QStringList sl;
      for (ZInstrument* i : instruments)
            sl.append(i->path());
      return sl;
      }

//---------------------------------------------------------
//   addSoundFont
//---------------------------------------------------------

bool Zerberus::addSoundFont(const QString& s)
      {
      return loadInstrument(s);
      }

//---------------------------------------------------------
//   removeSoundFont
//---------------------------------------------------------

bool Zerberus::removeSoundFont(const QString& s)
      {
      for (ZInstrument* i : instruments) {
            if (i->path() == s) {
                  auto it = find(instruments.begin(), instruments.end(), i);
                  if (it == instruments.end())
                        return false;
                  instruments.erase(it);
                  for (int k = 0; k < MAX_CHANNEL; ++k) {
                        if (_channel[k]->instrument() == i)
                              _channel[k]->setInstrument(0);
                        }
                  if (!instruments.empty()) {
                        for (int i = 0; i < MAX_CHANNEL; ++i) {
                              if (_channel[i]->instrument() == 0)
                                    _channel[i]->setInstrument(instruments.front());
                              }
                        }
                  i->setRefCount(i->refCount() - 1);
                  if (i->refCount() <= 0) {
                        auto it = find(globalInstruments.begin(), globalInstruments.end(), i);
                        if (it == globalInstruments.end())
                              return false;
                        globalInstruments.erase(it);
                        delete i;
                        }
                  return true;
                  }
            }
      return false;
      }

//---------------------------------------------------------
//   state
//---------------------------------------------------------

Ms::SynthesizerGroup Zerberus::state() const
      {
      Ms::SynthesizerGroup g;
      g.setName(name());

      QStringList sfl = soundFonts();
      foreach(QString sf, sfl)
            g.push_back(Ms::IdValue(0, sf));
      return g;
      }

//---------------------------------------------------------
//   setState
//---------------------------------------------------------

bool Zerberus::setState(const Ms::SynthesizerGroup& sp)
      {
      QStringList sfs;
      for (const Ms::IdValue& v : sp)
            sfs.append(v.data);
      return loadSoundFonts(sfs);
      }

//---------------------------------------------------------
//   instrument
//---------------------------------------------------------

ZInstrument* Zerberus::instrument(int n) const
      {
      int idx = 0;
      for (auto i = instruments.begin(); i != instruments.end(); ++i) {
            if (idx == n)
                  return *i;
            ++idx;
            }
      return 0;
      }

//---------------------------------------------------------
//   loadInstrument
//    return true on success
//---------------------------------------------------------

bool Zerberus::loadInstrument(const QString& s)
      {
      if (s.isEmpty())
            return false;
      QFileInfo fis(s);
      QString fileName = fis.fileName();
      for (ZInstrument* instr : instruments) {
            if (QFileInfo(instr->path()).fileName() == fileName) {   // already loaded?
                  return true;
                  }
            }
      for (ZInstrument* instr : globalInstruments) {
            if (QFileInfo(instr->path()).fileName() == fileName) {
                  instruments.push_back(instr);
                  instr->setRefCount(instr->refCount() + 1);
                  if (instruments.size() == 1) {
                        for (int i = 0; i < MAX_CHANNEL; ++i)
                              _channel[i]->setInstrument(instr);
                        }
                  busy = false;
                  return true;
                  }
            }

      QFileInfoList l = Zerberus::sfzFiles();
      QString path;
      foreach (const QFileInfo& fi, l) {
            if (fi.fileName() == fileName) {
                  path = fi.absoluteFilePath();
                  break;
                  }
            }
      busy = true;
      ZInstrument* instr = new ZInstrument(this);

      try {
            if (instr->load(path)) {
                  globalInstruments.push_back(instr);
                  instruments.push_back(instr);
                  instr->setRefCount(1);
                  //
                  // set default instrument for all channels:
                  //
                  if (instruments.size() == 1) {
                        for (int i = 0; i < MAX_CHANNEL; ++i)
                              _channel[i]->setInstrument(instr);
                        }
                  busy = false;
                  return true;
                  }
            }
      catch (std::bad_alloc& a) {
            qDebug("Unable to allocate memory when loading Zerberus soundfont %s", qPrintable(s));
            }
      catch (...) {
            }
      qDebug("Zerberus::loadInstrument failed");
      busy = false;
      delete instr;
      return false;
      }