1 /* B.Shapr
2 * Beat / envelope shaper LV2 plugin
3 *
4 * Copyright (C) 2019 by Sven Jähnichen
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20
21 #include <cstdio>
22 #include <string>
23 #include <stdexcept>
24 #include <algorithm>
25 #include "BShapr.hpp"
26 #include "BUtilities/stof.hpp"
27
28 #define LIM(g , min, max) ((g) > (max) ? (max) : ((g) < (min) ? (min) : (g)))
29 #define SGN(a) (((a) > 0) - ((a) < 0))
30 #define SQR(a) ((a) * (a))
31
db2co(const float value)32 inline float db2co (const float value) {return pow (10, 0.05 * value);}
33
floorfrac(const double value)34 inline double floorfrac (const double value) {return value - floor (value);}
35
AudioBuffer()36 AudioBuffer::AudioBuffer () : AudioBuffer (0) {}
37
AudioBuffer(const uint32_t size)38 AudioBuffer::AudioBuffer (const uint32_t size) : frames (nullptr), wPtr1 (0), wPtr2 (0), rPtr1 (0), rPtr2 (0), size (0)
39 {
40 if (size !=0)
41 {
42 try {resize (size);}
43 catch (std::bad_alloc& ba) {throw ba;}
44 }
45 }
46
~AudioBuffer()47 AudioBuffer::~AudioBuffer ()
48 {
49 if (frames) delete[] (frames);
50 }
51
resize(const uint32_t size)52 void AudioBuffer::resize (const uint32_t size)
53 {
54 if (frames) delete[] (frames);
55 frames = nullptr;
56 try {frames = new float[size];}
57 catch (std::bad_alloc& ba)
58 {
59 this->size = 0;
60 throw ba;
61 }
62
63 this->size = size;
64 }
65
reset()66 void AudioBuffer::reset ()
67 {
68 if (frames)
69 {
70 memset (frames, 0, size * sizeof (float));
71 memset (frames, 0, size * sizeof (float));
72 wPtr1 = wPtr2 = rPtr1 = rPtr2 = 0;
73 }
74 }
75
Message()76 Message::Message () : messageBits (0), scheduled (true) {}
77
clearMessages()78 void Message::clearMessages ()
79 {
80 messageBits = 0;
81 scheduled = true;
82 }
83
setMessage(MessageNr messageNr)84 void Message::setMessage (MessageNr messageNr)
85 {
86 if ((messageNr > NO_MSG) && (messageNr <= MAX_MSG) && (!isMessage (messageNr)))
87 {
88 messageBits = messageBits | (1 << (messageNr - 1));
89 scheduled = true;
90 }
91 }
92
deleteMessage(MessageNr messageNr)93 void Message::deleteMessage (MessageNr messageNr)
94 {
95 if ((messageNr > NO_MSG) && (messageNr <= MAX_MSG) && (isMessage (messageNr)))
96 {
97 messageBits = messageBits & (~(1 << (messageNr - 1)));
98 scheduled = true;
99 }
100 }
101
isMessage(MessageNr messageNr)102 bool Message::isMessage (MessageNr messageNr)
103 {
104 if ((messageNr > NO_MSG) && (messageNr <= MAX_MSG)) return ((messageBits & (1 << (messageNr - 1))) != 0);
105 else if (messageNr == NO_MSG) return (messageBits == 0);
106 else return false;
107 }
108
loadMessage()109 MessageNr Message::loadMessage ()
110 {
111 scheduled = false;
112 for (int i = NO_MSG + 1; i <= MAX_MSG; ++i)
113 {
114 MessageNr messageNr = MessageNr (i);
115 if (isMessage (messageNr)) return messageNr;
116 }
117 return NO_MSG;
118 }
119
isScheduled()120 bool Message::isScheduled () {return scheduled;}
121
122
Fader()123 Fader::Fader () : Fader (0, 1) {}
124
Fader(const float value,const float speed)125 Fader::Fader (const float value, const float speed) :
126 value (value),
127 target (value),
128 speed (speed)
129 {}
130
setTarget(const float target)131 inline void Fader::setTarget (const float target) {this->target = target;}
132
setSpeed(const float speed)133 inline void Fader::setSpeed (const float speed) {this->speed = speed;}
134
proceed()135 inline float Fader::proceed ()
136 {
137 if (fabsf (target - value) < speed) value = target;
138 else value += SGN (target - value) * speed;
139 return value;
140 }
141
getValue() const142 inline float Fader::getValue () const {return value;}
143
144
BShapr(double samplerate,const LV2_Feature * const * features)145 BShapr::BShapr (double samplerate, const LV2_Feature* const* features) :
146 map(NULL),
147 rate(samplerate), bpm(120.0f), speed(1), bar (0), barBeat (0), beatsPerBar (4), beatUnit (4),
148 position(0), offset(0), refFrame(0),
149 audioInput1(NULL), audioInput2(NULL), audioOutput1(NULL), audioOutput2(NULL),
150 new_controllers {NULL}, controllers {0},
151 shapes {Shape<MAXNODES> ()}, tempNodes {StaticArrayList<Node, MAXNODES> ()},
152 urids (), controlPort(NULL), notifyPort(NULL),
153
154 #ifdef SUPPORTS_CV
155 cvOutputs {NULL},
156 #endif
157
158 forge (), notify_frame (),
159 key (0xFF),
160 ui_on(false), message (), monitorPos(-1), notificationsCount(0), stepCount (0),
161 scheduleNotifyStatus (true)
162
163 {
164 std::fill (sendValue, sendValue + MAXSHAPES, 0xFF);
165 std::fill (factors, factors + MAXSHAPES, Fader (0, 1.0f / (0.02f * rate)));
166
167 for (int i = 0; i < MAXSHAPES; ++i)
168 {
169 shapes[i].setDefaultShape ();
170 shapes[i].setTransformation (methods[0].transformFactor, methods[0].transformOffset);
171
172 try {audioBuffer1[i].resize (samplerate);}
173 catch (std::bad_alloc& ba) {throw ba;}
174
175 try {audioBuffer2[i].resize (samplerate);}
176 catch (std::bad_alloc& ba) {throw ba;}
177 }
178 notifications.fill ({0.0f, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}});
179 fillFilterBuffer (filter1Buffer1, 0);
180 fillFilterBuffer (filter1Buffer2, 0);
181 fillFilterBuffer (filter2Buffer1, 0);
182 fillFilterBuffer (filter2Buffer2, 0);
183
184 //Scan host features for URID map
185 LV2_URID_Map* m = NULL;
186 for (int i = 0; features[i]; ++i)
187 {
188 if (strcmp(features[i]->URI, LV2_URID__map) == 0)
189 {
190 m = (LV2_URID_Map*) features[i]->data;
191 }
192 }
193 if (!m) throw std::invalid_argument ("Host does not support urid:map");
194
195 //Map URIS
196 map = m;
197 mapURIDs (m, &urids);
198
199 // Initialize forge
200 lv2_atom_forge_init (&forge, map);
201
202 for (int i = 0; i < MAXSHAPES; ++i) scheduleNotifyShapes[i] = true;
203 }
204
~BShapr()205 BShapr::~BShapr () {}
206
connect_port(uint32_t port,void * data)207 void BShapr::connect_port(uint32_t port, void *data)
208 {
209 switch (port) {
210 case CONTROL:
211 controlPort = (LV2_Atom_Sequence*) data;
212 break;
213 case NOTIFY:
214 notifyPort = (LV2_Atom_Sequence*) data;
215 break;
216
217 case AUDIO_IN_1:
218 audioInput1 = (float*) data;
219 break;
220 case AUDIO_IN_2:
221 audioInput2 = (float*) data;
222 break;
223 case AUDIO_OUT_1:
224 audioOutput1 = (float*) data;
225 break;
226 case AUDIO_OUT_2:
227 audioOutput2 = (float*) data;
228 break;
229 default:
230
231 #ifdef SUPPORTS_CV
232 if ((port >= CV_OUT) && (port < CV_OUT + MAXSHAPES)) cvOutputs[port - CV_OUT] = (float*) data;
233 #endif
234
235 if ((port >= CONTROLLERS) && (port < CONTROLLERS + NR_CONTROLLERS)) new_controllers[port - CONTROLLERS] = (float*) data;
236 }
237 }
238
fillFilterBuffer(float filterBuffer[MAXSHAPES][MAX_F_ORDER/2],const float value)239 void BShapr::fillFilterBuffer (float filterBuffer[MAXSHAPES] [MAX_F_ORDER / 2], const float value)
240 {
241 for (int i = 0; i < MAXSHAPES; ++ i)
242 {
243 for (int j = 0; j < MAX_F_ORDER / 2; ++ j)
244 {
245 filterBuffer[i][j] = value;
246 }
247 }
248 }
249
isAudioOutputConnected(int shapeNr)250 bool BShapr::isAudioOutputConnected (int shapeNr)
251 {
252 if (controllers[SHAPERS + shapeNr * SH_SIZE + SH_OUTPUT] != 0) return true;
253
254 for (int i = shapeNr + 1; i < MAXSHAPES; ++i)
255 {
256 bool status = false;
257 if (controllers[SHAPERS + i * SH_SIZE + SH_INPUT] == shapeNr + 3) status = isAudioOutputConnected (i);
258 if (status) {return true;}
259 }
260 return false;
261 }
262
getPositionFromBeats(double beats)263 double BShapr::getPositionFromBeats (double beats)
264 {
265 if (controllers[BASE_VALUE] == 0.0) return 0.0;
266
267 switch (int (controllers[BASE]))
268 {
269 case SECONDS: return (bpm ? beats / (controllers[BASE_VALUE] * (bpm / 60.0)) : 0.0);
270 case BEATS: return beats / controllers[BASE_VALUE];
271 case BARS: return (beatsPerBar ? beats / (controllers[BASE_VALUE] * beatsPerBar) : 0.0);
272 default: return 0.0;
273 }
274 }
275
getPositionFromFrames(uint64_t frames)276 double BShapr::getPositionFromFrames (uint64_t frames)
277 {
278 if ((controllers[BASE_VALUE] == 0.0) || (rate == 0)) return 0.0;
279
280 switch (int (controllers[BASE]))
281 {
282 case SECONDS: return frames * (1.0 / rate) / controllers[BASE_VALUE] ;
283 case BEATS: return (bpm ? frames * (speed / (rate / (bpm / 60))) / controllers[BASE_VALUE] : 0.0);
284 case BARS: return (bpm && beatsPerBar ? frames * (speed / (rate / (bpm / 60))) / (controllers[BASE_VALUE] * beatsPerBar) : 0.0);
285 default: return 0.0;
286 }
287 }
288
getPositionFromSeconds(double seconds)289 double BShapr::getPositionFromSeconds (double seconds)
290 {
291 if (controllers[BASE_VALUE] == 0.0) return 0.0;
292
293 switch (int (controllers[BASE]))
294 {
295 case SECONDS : return seconds / controllers[BASE_VALUE];
296 case BEATS: return seconds * (bpm / 60.0) / controllers[BASE_VALUE];
297 case BARS: return (beatsPerBar ? seconds * (bpm / 60.0 / beatsPerBar) / controllers[BASE_VALUE] : 0.0);
298 default: return 0;
299 }
300 }
301
run(uint32_t n_samples)302 void BShapr::run (uint32_t n_samples)
303 {
304 // Check ports
305 if ((!controlPort) || (!notifyPort) || (!audioInput1) || (!audioInput2) || (!audioOutput1) || (!audioOutput2)) return;
306
307 for (int i = 0; i < NR_CONTROLLERS; ++i) if (!new_controllers[i]) return;
308
309 // Prepare forge buffer and initialize atom sequence
310 const uint32_t space = notifyPort->atom.size;
311 lv2_atom_forge_set_buffer(&forge, (uint8_t*) notifyPort, space);
312 lv2_atom_forge_sequence_head(&forge, ¬ify_frame, 0);
313
314 // Update controller values
315 for (int i = 0; i < NR_CONTROLLERS; ++i)
316 {
317 if (controllers[i] != *new_controllers[i])
318 {
319 float newValue = *new_controllers[i];
320 int shapeNr = ((i >= SHAPERS) ? ((i - SHAPERS) / SH_SIZE) : -1);
321 int shapeControllerNr = ((i >= SHAPERS) ? ((i - SHAPERS) % SH_SIZE) : -1);
322
323 // Global controllers
324 if (i < SHAPERS)
325 {
326 newValue = globalControllerLimits[i].validate (newValue);
327
328 if (i == MIDI_CONTROL)
329 {
330 if (newValue == 0.0f)
331 {
332 // Hard set position back to offset-independent position
333 position = floorfrac (position + offset);
334 offset = 0;
335 }
336
337 else key = 0xFF;
338 }
339
340 else if (i == BASE)
341 {
342 if (newValue == SECONDS)
343 {
344 if (bpm < 1.0) message.setMessage (JACK_STOP_MSG);
345 else message.deleteMessage (JACK_STOP_MSG);
346 }
347 else
348 {
349 if ((speed == 0) || (bpm < 1.0)) message.setMessage (JACK_STOP_MSG);
350 else message.deleteMessage (JACK_STOP_MSG);
351 }
352 }
353 }
354
355 // Shape controllers
356 else
357 {
358 newValue = shapeControllerLimits[shapeControllerNr].validate (newValue);
359
360 // Target
361 if (shapeControllerNr == SH_TARGET)
362 {
363 // Change transformation
364 shapes[shapeNr].setTransformation (methods[int(newValue)].transformFactor, methods[int(newValue)].transformOffset);
365 const float sm = controllers[SHAPERS + shapeNr * SH_SIZE + SH_SMOOTHING];
366 factors[shapeNr] = Fader
367 (
368 methods[int(newValue)].transformOffset,
369 methods[int(newValue)].step / (0.001f * sm * rate)
370 );
371
372 // Clear audiobuffers, if needed
373 if
374 (
375 (newValue == BShaprTargetIndex::PITCH) ||
376 (newValue == BShaprTargetIndex::DELAY) ||
377 (newValue == BShaprTargetIndex::DOPPLER)
378 )
379 {
380 audioBuffer1[shapeNr].reset ();
381 audioBuffer2[shapeNr].reset ();
382 }
383
384 #ifndef SUPPORTS_CV
385 // Force update & send MIDI if switched to MIDI
386 else if (newValue == BShaprTargetIndex::SEND_MIDI) sendValue[shapeNr] = 0xff;
387 #endif
388 }
389
390 else if (shapeControllerNr == SH_SMOOTHING)
391 {
392 const int me = controllers[SHAPERS + shapeNr * SH_SIZE + SH_TARGET];
393 factors[shapeNr].setSpeed (methods[me].step/ (0.001f * newValue * rate));
394 }
395
396 // Options
397 else if ((shapeControllerNr >= SH_OPTION) && (shapeControllerNr < SH_OPTION + MAXOPTIONS))
398 {
399 int optionNr = shapeControllerNr - SH_OPTION;
400 newValue = options[optionNr].limit.validate (newValue);
401
402 // Force update & send MIDI if parameter changed
403 if ((optionNr == SEND_MIDI_CH) || (optionNr == SEND_MIDI_CC)) sendValue[shapeNr] = 0xff;
404 }
405 }
406
407 controllers[i] = newValue;
408 }
409 }
410
411 // Check for waiting tempNodes
412 for (int i = 0; i < MAXSHAPES; ++i)
413 {
414 while (!tempNodes[i].empty())
415 {
416 Node n = tempNodes[i].back();
417 shapes[i].insertNode (n);
418 tempNodes[i].pop_back();
419 }
420 }
421
422 // Check activeShape input
423 int activeShape = LIM (controllers[ACTIVE_SHAPE], 1, MAXSHAPES) - 1;
424 if (controllers[SHAPERS + activeShape * SH_SIZE + SH_INPUT] == 0) message.setMessage (NO_INPUT_MSG);
425 else message.deleteMessage (NO_INPUT_MSG);
426
427 // Check activeShape output
428 if (!isAudioOutputConnected (activeShape)) message.setMessage (NO_OUTPUT_MSG);
429 else message.deleteMessage (NO_OUTPUT_MSG);
430
431 // Control and MIDI messages
432 uint32_t last_t = 0;
433 LV2_ATOM_SEQUENCE_FOREACH(controlPort, ev)
434 {
435 // Read host & GUI events
436 if ((ev->body.type == urids.atom_Object) || (ev->body.type == urids.atom_Blank))
437 {
438 const LV2_Atom_Object* obj = (const LV2_Atom_Object*)&ev->body;
439
440 // Process GUI on status data
441 if (obj->body.otype == urids.ui_on)
442 {
443 ui_on = true;
444 for (int i = 0; i < MAXSHAPES; ++i) scheduleNotifyShapes[i] = true;
445 }
446
447 // Process GUI off status data
448 else if (obj->body.otype == urids.ui_off) ui_on = false;
449
450 // Process (full) shape data
451 else if (obj->body.otype == urids.notify_shapeEvent)
452 {
453 LV2_Atom *sNr = NULL, *sData = NULL;
454 lv2_atom_object_get
455 (
456 obj,
457 urids.notify_shapeNr, &sNr,
458 urids.notify_shapeData, &sData,
459 NULL
460 );
461
462 if (sNr && (sNr->type == urids.atom_Int) &&
463 sData && (sData->type == urids.atom_Vector))
464 {
465 int shapeNr = ((LV2_Atom_Int*)sNr)->body;
466
467 if ((shapeNr >= 0) && (shapeNr < MAXSHAPES))
468 {
469 const LV2_Atom_Vector* vec = (const LV2_Atom_Vector*) sData;
470 size_t vecSize = (sData->size - sizeof(LV2_Atom_Vector_Body)) / (7 * sizeof (float));
471 if (vec->body.child_type == urids.atom_Float)
472 {
473 shapes[shapeNr].clearShape ();
474 float* data = (float*)(&vec->body + 1);
475 for (unsigned int nodeNr = 0; (nodeNr < vecSize) && (nodeNr < MAXNODES); ++nodeNr)
476 {
477 Node node (&data[nodeNr * 7]);
478 shapes[shapeNr].appendRawNode (node);
479 }
480 shapes[shapeNr].validateShape();
481 }
482 }
483 }
484 }
485
486 // Process time / position data
487 else if (obj->body.otype == urids.time_Position)
488 {
489 bool scheduleUpdatePosition = false;
490
491 // Update bpm, speed, position
492 LV2_Atom *oBbeat = NULL, *oBpm = NULL, *oSpeed = NULL, *oBpb = NULL, *oBu = NULL, *oBar = NULL;
493 const LV2_Atom_Object* obj = (const LV2_Atom_Object*)&ev->body;
494 lv2_atom_object_get
495 (
496 obj, urids.time_bar, &oBar,
497 urids.time_barBeat, &oBbeat,
498 urids.time_beatsPerMinute, &oBpm,
499 urids.time_beatsPerBar, &oBpb,
500 urids.time_beatUnit, &oBu,
501 urids.time_speed, &oSpeed,
502 NULL
503 );
504
505 // BPM changed?
506 if (oBpm && (oBpm->type == urids.atom_Float))
507 {
508 float nbpm = ((LV2_Atom_Float*)oBpm)->body;
509
510 if (nbpm != bpm)
511 {
512 bpm = nbpm;
513
514 if (nbpm < 1.0)
515 {
516 message.setMessage (JACK_STOP_MSG);
517 fillFilterBuffer (filter1Buffer1, 0);
518 fillFilterBuffer (filter1Buffer2, 0);
519 fillFilterBuffer (filter2Buffer1, 0);
520 fillFilterBuffer (filter2Buffer2, 0);
521 }
522
523 else message.deleteMessage (JACK_STOP_MSG);
524 }
525 }
526
527 // Beats per bar changed?
528 if (oBpb && (oBpb->type == urids.atom_Float) && (((LV2_Atom_Float*)oBpb)->body > 0))
529 {
530 beatsPerBar = ((LV2_Atom_Float*)oBpb)->body;
531 scheduleNotifyStatus = true;
532 }
533
534 // BeatUnit changed?
535 if (oBu && (oBu->type == urids.atom_Int) && (((LV2_Atom_Int*)oBu)->body > 0))
536 {
537 beatUnit = ((LV2_Atom_Int*)oBu)->body;
538 scheduleNotifyStatus = true;
539 }
540
541 // Speed changed?
542 if (oSpeed && (oSpeed->type == urids.atom_Float))
543 {
544 float nspeed = ((LV2_Atom_Float*)oSpeed)->body;
545
546 if (nspeed != speed)
547 {
548
549 if (controllers[BASE] != SECONDS)
550 {
551
552 // Started ?
553 if (speed == 0)
554 {
555 for (int i = 0; i < MAXSHAPES; ++i)
556 {
557 audioBuffer1[i].reset ();
558 audioBuffer2[i].reset ();
559 }
560 }
561
562 // Stopped ?
563 if (nspeed == 0)
564 {
565 message.setMessage (JACK_STOP_MSG);
566 fillFilterBuffer (filter1Buffer1, 0);
567 fillFilterBuffer (filter1Buffer2, 0);
568 fillFilterBuffer (filter2Buffer1, 0);
569 fillFilterBuffer (filter2Buffer2, 0);
570 }
571
572 // Not stopped ?
573 else message.deleteMessage (JACK_STOP_MSG);
574 }
575
576 speed = nspeed;
577 }
578 }
579
580 // Bar position changed
581 if (oBar && (oBar->type == urids.atom_Long) && (bar != ((uint64_t)((LV2_Atom_Long*)oBar)->body)))
582 {
583 bar = ((LV2_Atom_Long*)oBar)->body;
584 scheduleUpdatePosition = true;
585 }
586
587 // Beat position changed (during playing) ?
588 if (oBbeat && (oBbeat->type == urids.atom_Float))
589 {
590 barBeat = ((LV2_Atom_Float*)oBbeat)->body;
591 scheduleUpdatePosition = true;
592 }
593
594 if (scheduleUpdatePosition)
595 {
596 // Hard set new position if new data received
597 double pos = getPositionFromBeats (barBeat + beatsPerBar * bar);
598 position = floorfrac (pos - offset);
599 refFrame = ev->time.frames;
600 }
601 }
602 }
603
604 // Read incoming MIDI events
605 if (ev->body.type == urids.midi_Event)
606 {
607 const uint8_t* const msg = (const uint8_t*)(ev + 1);
608
609 // Forward MIDI event
610 if (controllers[MIDI_THRU] != 0.0f)
611 {
612 LV2_Atom midiatom;
613 midiatom.type = urids.midi_Event;
614 midiatom.size = ev->body.size;
615
616 lv2_atom_forge_frame_time (&forge, ev->time.frames);
617 lv2_atom_forge_raw (&forge, &midiatom, sizeof (LV2_Atom));
618 lv2_atom_forge_raw (&forge, msg, midiatom.size);
619 lv2_atom_forge_pad (&forge, sizeof (LV2_Atom) + midiatom.size);
620 }
621
622 // Analyze MIDI event
623 if (controllers[MIDI_CONTROL] == 1.0f)
624 {
625 uint8_t typ = lv2_midi_message_type(msg);
626 // uint8_t chn = msg[0] & 0x0F;
627 uint8_t note = msg[1];
628 uint32_t filter = controllers[MIDI_KEYS];
629
630 switch (typ)
631 {
632 case LV2_MIDI_MSG_NOTE_ON:
633 {
634 if (filter & (1 << (note % 12)))
635 {
636 key = note;
637 offset = floorfrac (position + offset);
638 position = 0;
639 refFrame = ev->time.frames;
640 }
641 }
642 break;
643
644 case LV2_MIDI_MSG_NOTE_OFF:
645 {
646 if (key == note)
647 {
648 key = 0xFF;
649 }
650 }
651 break;
652
653 case LV2_MIDI_MSG_CONTROLLER:
654 {
655 if ((note == LV2_MIDI_CTL_ALL_NOTES_OFF) ||
656 (note == LV2_MIDI_CTL_ALL_SOUNDS_OFF))
657 {
658 key = 0xFF;
659 }
660 }
661 break;
662
663 default: break;
664 }
665 }
666 }
667
668 uint32_t next_t = (ev->time.frames < n_samples ? ev->time.frames : n_samples);
669 play (last_t, next_t);
670 last_t = next_t;
671 }
672
673 // Play remaining samples
674 if (last_t < n_samples) play (last_t, n_samples);
675
676 // Update position in case of no new barBeat submitted on next call
677 double relpos = getPositionFromFrames (n_samples - refFrame); // Position relative to reference frame
678 position = floorfrac (position + relpos);
679 refFrame = 0;
680
681 // Send collected data to GUI
682 if (ui_on)
683 {
684 notifyMonitorToGui ();
685 for (int i = 0; i < MAXSHAPES; ++i) if (scheduleNotifyShapes[i]) notifyShapeToGui (i);
686 if (message.isScheduled ()) notifyMessageToGui ();
687 if (scheduleNotifyStatus) notifyStatusToGui ();
688 }
689 lv2_atom_forge_pop (&forge, ¬ify_frame);
690 }
691
notifyMonitorToGui()692 void BShapr::notifyMonitorToGui()
693 {
694 if (notificationsCount > 0)
695 {
696 if (notificationsCount > NOTIFYBUFFERSIZE) notificationsCount = NOTIFYBUFFERSIZE;
697 LV2_Atom_Forge_Frame frame;
698 lv2_atom_forge_frame_time(&forge, 0);
699 lv2_atom_forge_object(&forge, &frame, 0, urids.notify_monitorEvent);
700 lv2_atom_forge_key(&forge, urids.notify_monitor);
701 lv2_atom_forge_vector(&forge, sizeof(float), urids.atom_Float, (uint32_t) (9 * notificationsCount), ¬ifications);
702 lv2_atom_forge_pop(&forge, &frame);
703
704 memset (¬ifications, 0, notificationsCount * sizeof (BShaprNotifications));
705 notificationsCount = 0;
706 stepCount = 0;
707 }
708 }
709
notifyShapeToGui(int shapeNr)710 void BShapr::notifyShapeToGui (int shapeNr)
711 {
712 size_t size = shapes[shapeNr].size ();
713
714 // Load shapeBuffer
715 for (unsigned int i = 0; i < size; ++i)
716 {
717 Node node = shapes[shapeNr].getRawNode (i);
718 shapeBuffer[i * 7] = (float)node.nodeType;
719 shapeBuffer[i * 7 + 1] = (float)node.point.x;
720 shapeBuffer[i * 7 + 2] = (float)node.point.y;
721 shapeBuffer[i * 7 + 3] = (float)node.handle1.x;
722 shapeBuffer[i * 7 + 4] = (float)node.handle1.y;
723 shapeBuffer[i * 7 + 5] = (float)node.handle2.x;
724 shapeBuffer[i * 7 + 6] = (float)node.handle2.y;
725 }
726
727 // Notify shapeBuffer
728 LV2_Atom_Forge_Frame frame;
729 lv2_atom_forge_frame_time(&forge, 0);
730 lv2_atom_forge_object(&forge, &frame, 0, urids.notify_shapeEvent);
731 lv2_atom_forge_key(&forge, urids.notify_shapeNr);
732 lv2_atom_forge_int(&forge, shapeNr);
733 lv2_atom_forge_key(&forge, urids.notify_shapeData);
734 lv2_atom_forge_vector(&forge, sizeof(float), urids.atom_Float, (uint32_t) (7 * size), &shapeBuffer);
735 lv2_atom_forge_pop(&forge, &frame);
736
737 scheduleNotifyShapes[shapeNr] = false;
738 }
739
notifyMessageToGui()740 void BShapr::notifyMessageToGui()
741 {
742 uint32_t messageNr = message.loadMessage ();
743
744 // Send notifications
745 LV2_Atom_Forge_Frame frame;
746 lv2_atom_forge_frame_time(&forge, 0);
747 lv2_atom_forge_object(&forge, &frame, 0, urids.notify_messageEvent);
748 lv2_atom_forge_key(&forge, urids.notify_message);
749 lv2_atom_forge_int(&forge, messageNr);
750 lv2_atom_forge_pop(&forge, &frame);
751 }
752
notifyStatusToGui()753 void BShapr::notifyStatusToGui()
754 {
755 // Send notifications
756 LV2_Atom_Forge_Frame frame;
757 lv2_atom_forge_frame_time(&forge, 0);
758 lv2_atom_forge_object(&forge, &frame, 0, urids.notify_statusEvent);
759 lv2_atom_forge_key(&forge, urids.time_beatsPerBar);
760 lv2_atom_forge_float(&forge, beatsPerBar);
761 lv2_atom_forge_key(&forge, urids.time_beatUnit);
762 lv2_atom_forge_int(&forge, beatUnit);
763 lv2_atom_forge_key(&forge, urids.time_beatsPerMinute);
764 lv2_atom_forge_float(&forge, bpm);
765 lv2_atom_forge_pop(&forge, &frame);
766
767 scheduleNotifyStatus = false;
768 }
769
audioLevel(const float input1,const float input2,float * output1,float * output2,const float amp)770 void BShapr::audioLevel (const float input1, const float input2, float* output1, float* output2, const float amp)
771 {
772 *output1 = input1 * LIM (amp, methods[LEVEL].limit.min, methods[LEVEL].limit.max);
773 *output2 = input2 * LIM (amp, methods[LEVEL].limit.min, methods[LEVEL].limit.max);
774 }
775
stereoBalance(const float input1,const float input2,float * output1,float * output2,const float balance)776 void BShapr::stereoBalance (const float input1, const float input2, float* output1, float* output2, const float balance)
777 {
778 float f = LIM (balance, methods[BALANCE].limit.min, methods[BALANCE].limit.max);
779 if (f < 0)
780 {
781 *output1 = input1 + (0 - f) * input2;
782 *output2 = (f + 1) * input2;
783 }
784
785 else
786 {
787 *output1 = (1 - f) * input1;
788 *output2 = input2 + f * input1;
789 }
790 }
791
stereoWidth(const float input1,const float input2,float * output1,float * output2,const float width)792 void BShapr::stereoWidth (const float input1, const float input2, float* output1, float* output2, const float width)
793 {
794 float f = LIM (width, methods[WIDTH].limit.min, methods[WIDTH].limit.max);
795 float m = (input1 + input2) / 2;
796 float s = (input1 - input2) * f / 2;
797
798 *output1 = m + s;
799 *output2 = m - s;
800 }
801
802 // Butterworth algorithm
lowPassFilter(const float input1,const float input2,float * output1,float * output2,const float cutoffFreq,const int shape)803 void BShapr::lowPassFilter (const float input1, const float input2, float* output1, float* output2, const float cutoffFreq, const int shape)
804 {
805 int order = controllers[SHAPERS + shape * SH_SIZE + SH_OPTION + DB_PER_OCT_OPT] / 6;
806 float f = LIM (cutoffFreq, methods[LOW_PASS].limit.min, methods[LOW_PASS].limit.max);
807 float a = tan (M_PI * f / rate);
808 float a2 = a * a;
809 float coeff0 [MAX_F_ORDER / 2];
810 float coeff1 [MAX_F_ORDER / 2];
811 float coeff2 [MAX_F_ORDER / 2];
812 float filter1Buffer0 [MAX_F_ORDER / 2];
813 float filter2Buffer0 [MAX_F_ORDER / 2];
814
815 for (int i = 0; i < int (order / 2); ++i)
816 {
817 float r = sin (M_PI * (2.0f * i + 1.0f) / (2.0f * order));
818 float s = a2 + 2.0f * a * r + 1.0f;
819 coeff0[i] = a2 / s;
820 coeff1[i] = 2.0f * (1 - a2) / s;
821 coeff2[i] = -(a2 - 2.0f * a * r + 1.0f) / s;
822 }
823
824 double f1 = input1;
825 double f2 = input2;
826 for (int i = 0; i < int (order / 2); ++i)
827 {
828 filter1Buffer0[i] = coeff1[i] * filter1Buffer1[shape][i] + coeff2[i] * filter1Buffer2[shape][i] + f1;
829 filter2Buffer0[i] = coeff1[i] * filter2Buffer1[shape][i] + coeff2[i] * filter2Buffer2[shape][i] + f2;
830 f1 = coeff0[i] * (filter1Buffer0[i] + 2.0f * filter1Buffer1[shape][i] + filter1Buffer2[shape][i]);
831 f2 = coeff0[i] * (filter2Buffer0[i] + 2.0f * filter2Buffer1[shape][i] + filter2Buffer2[shape][i]);
832 filter1Buffer2[shape][i] = filter1Buffer1[shape][i];
833 filter1Buffer1[shape][i] = filter1Buffer0[i];
834 filter2Buffer2[shape][i] = filter2Buffer1[shape][i];
835 filter2Buffer1[shape][i] = filter2Buffer0[i];
836 }
837
838 *output1 = f1;
839 *output2 = f2;
840 }
841
842 // Butterworth algorithm
highPassFilter(const float input1,const float input2,float * output1,float * output2,const float cutoffFreq,const int shape)843 void BShapr::highPassFilter (const float input1, const float input2, float* output1, float* output2, const float cutoffFreq, const int shape)
844 {
845 int order = controllers[SHAPERS + shape * SH_SIZE + SH_OPTION + DB_PER_OCT_OPT] / 6;
846 float f = LIM (cutoffFreq, methods[HIGH_PASS].limit.min, methods[HIGH_PASS].limit.max);
847 float a = tan (M_PI * f / rate);
848 float a2 = a * a;
849 float coeff0 [MAX_F_ORDER / 2];
850 float coeff1 [MAX_F_ORDER / 2];
851 float coeff2 [MAX_F_ORDER / 2];
852 float filter1Buffer0 [MAX_F_ORDER / 2];
853 float filter2Buffer0 [MAX_F_ORDER / 2];
854
855 for (int i = 0; i < int (order / 2); ++i)
856 {
857 float r = sin (M_PI * (2.0f * i + 1.0f) / (2.0f * order));
858 float s = a2 + 2.0f * a * r + 1.0f;
859 coeff0[i] = 1 / s;
860 coeff1[i] = 2.0f * (1 - a2) / s;
861 coeff2[i] = -(a2 - 2.0f * a * r + 1.0f) / s;
862 }
863
864 double f1 = input1;
865 double f2 = input2;
866 for (int i = 0; i < int (order / 2); ++i)
867 {
868 filter1Buffer0[i] = coeff1[i] * filter1Buffer1[shape][i] + coeff2[i] * filter1Buffer2[shape][i] + f1;
869 filter2Buffer0[i] = coeff1[i] * filter2Buffer1[shape][i] + coeff2[i] * filter2Buffer2[shape][i] + f2;
870 f1 = coeff0[i] * (filter1Buffer0[i] - 2.0f * filter1Buffer1[shape][i] + filter1Buffer2[shape][i]);
871 f2 = coeff0[i] * (filter2Buffer0[i] - 2.0f * filter2Buffer1[shape][i] + filter2Buffer2[shape][i]);
872 filter1Buffer2[shape][i] = filter1Buffer1[shape][i];
873 filter1Buffer1[shape][i] = filter1Buffer0[i];
874 filter2Buffer2[shape][i] = filter2Buffer1[shape][i];
875 filter2Buffer1[shape][i] = filter2Buffer0[i];
876 }
877
878 *output1 = f1;
879 *output2 = f2;
880 }
881
882 // Ring buffer method with least squares ring closure
pitch(const float input1,const float input2,float * output1,float * output2,const float semitone,const int shape)883 void BShapr::pitch (const float input1, const float input2, float* output1, float* output2, const float semitone, const int shape)
884 {
885 const int pitchBufferSize = rate * PITCHBUFFERTIME / 1000;
886 const int pitchFaderSize = rate * PITCHFADERTIME / 1000;
887 const float p = LIM (semitone, methods[PITCH].limit.min, methods[PITCH].limit.max);
888 const double pitchFactor = pow (2, p / 12);
889 const uint32_t wPtr = audioBuffer1[shape].wPtr1;
890 const double rPtr = audioBuffer1[shape].rPtr1;
891 const uint32_t rPtrInt = uint32_t (rPtr);
892 const double rPtrFrac = fmod (rPtr, 1);
893 double diff = rPtr - wPtr;
894 if (diff > pitchBufferSize / 2) diff = diff - pitchBufferSize;
895 if (diff < -pitchBufferSize / 2) diff = diff + pitchBufferSize;
896
897 // Write to buffers and output
898 audioBuffer1[shape].frames[wPtr % pitchBufferSize] = input1;
899 audioBuffer2[shape].frames[wPtr % pitchBufferSize] = input2;
900 *output1 = (1 - rPtrFrac) * audioBuffer1[shape].frames[rPtrInt % pitchBufferSize] +
901 rPtrFrac * audioBuffer1[shape].frames[(rPtrInt + 1) % pitchBufferSize];
902 *output2 = (1 - rPtrFrac) * audioBuffer2[shape].frames[rPtrInt % pitchBufferSize] +
903 rPtrFrac * audioBuffer2[shape].frames[(rPtrInt + 1) % pitchBufferSize];
904
905 // Update pointers
906 const double newWPtr = (wPtr + 1) % pitchBufferSize;
907 double newRPtr = fmod (rPtr + pitchFactor, pitchBufferSize);
908
909 double newDiff = newRPtr - newWPtr;
910 if (newDiff > pitchBufferSize / 2) newDiff = newDiff - pitchBufferSize;
911 if (newDiff < -pitchBufferSize / 2) newDiff = newDiff + pitchBufferSize;
912
913 // Run into new data area on positive pitch or
914 // run into old data area on negative pitch => find best point to continue
915 if (((diff < 0) && (newDiff >= 0) && (p > 0)) ||
916 ((diff >= 1) && (newDiff < 1) && (p < 0)))
917 {
918 int sig = (p > 0 ? -1 : 1);
919 double bestOverlayScore = 9999;
920 int bestI = 0;
921
922 // Calulate slopes for the reference sample points
923 double slope11[P_ORDER];
924 double slope12[P_ORDER];
925 for (int j = 0; j < P_ORDER; ++j)
926 {
927 double jpos = double (pitchBufferSize * (1 << j)) / 1000;
928 uint32_t jptr = rPtrInt + pitchBufferSize + sig * jpos;
929 slope11[j] = audioBuffer1[shape].frames[(jptr + 1) % pitchBufferSize] -
930 audioBuffer1[shape].frames[jptr % pitchBufferSize];
931 slope12[j] = audioBuffer2[shape].frames[(jptr + 1) % pitchBufferSize] -
932 audioBuffer2[shape].frames[jptr % pitchBufferSize];
933 }
934
935 // Iterate through the buffer to find the best match
936 for (int i = pitchFaderSize + 1; i < pitchBufferSize - pitchFaderSize; ++i)
937 {
938 double posDiff1 = audioBuffer1[shape].frames[rPtrInt % pitchBufferSize] - audioBuffer1[shape].frames[(rPtrInt + i) % pitchBufferSize];
939 double posDiff2 = audioBuffer2[shape].frames[rPtrInt % pitchBufferSize] - audioBuffer2[shape].frames[(rPtrInt + i) % pitchBufferSize];
940 double overlayScore = SQR (posDiff1) + SQR (posDiff2);
941
942 for (int j = 0; j < P_ORDER; ++j)
943 {
944 if (overlayScore > bestOverlayScore) break;
945
946 double jpos = double (pitchBufferSize * (1 << j)) / 1000;
947 uint32_t jptr = rPtrInt + pitchBufferSize + i + sig * jpos;
948 double slope21 = audioBuffer1[shape].frames[(jptr + 1) % pitchBufferSize] -
949 audioBuffer1[shape].frames[jptr % pitchBufferSize];
950 double slope22 = audioBuffer2[shape].frames[(jptr + 1) % pitchBufferSize] -
951 audioBuffer2[shape].frames[jptr % pitchBufferSize];
952 double slopeDiff1 = slope11[j] - slope21;
953 double slopeDiff2 = slope12[j] - slope22;
954 overlayScore += SQR (slopeDiff1) + SQR (slopeDiff2);
955 }
956
957 if (overlayScore < bestOverlayScore)
958 {
959 bestI = i;
960 bestOverlayScore = overlayScore;
961 }
962 }
963
964 newRPtr = fmod (rPtr + bestI + pitchFactor, pitchBufferSize);
965 }
966
967 audioBuffer1[shape].wPtr1 = newWPtr;
968 audioBuffer1[shape].rPtr1 = newRPtr;
969 audioBuffer2[shape].wPtr1 = newWPtr;
970 audioBuffer2[shape].rPtr1 = newRPtr;
971 }
972
973 // Ring buffer method with least squares ring closure
delay(const float input1,const float input2,float * output1,float * output2,const float delaytime,const int shape)974 void BShapr::delay (const float input1, const float input2, float* output1, float* output2, const float delaytime, const int shape)
975 {
976 const int audioBufferSize = rate;
977 const int delayBufferSize = rate * DELAYBUFFERTIME / 1000;
978 float param = LIM (delaytime, methods[DELAY].limit.min, methods[DELAY].limit.max) * rate / 1000;
979 const int delayframes = LIM (param, 0, audioBufferSize);
980
981 const uint32_t wPtr = uint32_t (audioBuffer1[shape].wPtr1) % audioBufferSize;
982 const uint32_t rPtr1 = uint32_t (audioBuffer1[shape].rPtr1) % audioBufferSize;
983 const uint32_t rPtr2 = uint32_t (audioBuffer1[shape].rPtr2) % audioBufferSize;
984 const int diff = (rPtr2 > rPtr1 ? rPtr2 - rPtr1 : rPtr2 + audioBufferSize - rPtr1);
985
986 // Write to buffers and output
987 audioBuffer1[shape].frames[wPtr] = input1;
988 audioBuffer2[shape].frames[wPtr] = input2;
989 *output1 = audioBuffer1[shape].frames[rPtr2];
990 *output2 = audioBuffer2[shape].frames[rPtr2];
991
992 // Update pointers
993 uint32_t newRPtr1 = rPtr1;
994 uint32_t newRPtr2 = rPtr2;
995
996 // End of block? Find best point to continue.
997 if (diff >= delayBufferSize)
998 {
999 double bestOverlayScore = 9999;
1000 int bestI = 0;
1001
1002 // Calulate slopes for the reference sample points
1003 double slope11[P_ORDER];
1004 double slope12[P_ORDER];
1005 for (int j = 0; j < P_ORDER; ++j)
1006 {
1007 double jpos = double (delayBufferSize * (1 << j)) / 1000;
1008 uint32_t jptr = rPtr2 + audioBufferSize - jpos;
1009 slope11[j] = audioBuffer1[shape].frames[(jptr + 1) % audioBufferSize] -
1010 audioBuffer1[shape].frames[jptr % audioBufferSize];
1011 slope12[j] = audioBuffer2[shape].frames[(jptr + 1) % audioBufferSize] -
1012 audioBuffer2[shape].frames[jptr % audioBufferSize];
1013 }
1014
1015 // Iterate through the buffer to find the best match
1016 for (int i = 0; (i < delayBufferSize) && (i < delayframes); ++i)
1017 {
1018 int32_t iPtr = (wPtr + 2 * audioBufferSize - delayframes - i) % audioBufferSize;
1019 double posDiff1 = audioBuffer1[shape].frames[rPtr2] - audioBuffer1[shape].frames[iPtr];
1020 double posDiff2 = audioBuffer2[shape].frames[rPtr2] - audioBuffer2[shape].frames[iPtr];
1021 double overlayScore = SQR (posDiff1) + SQR (posDiff2);
1022
1023 for (int j = 0; j < P_ORDER; ++j)
1024 {
1025 if (overlayScore > bestOverlayScore) break;
1026
1027 double jpos = double (delayBufferSize * (1 << j)) / 1000;
1028 uint32_t jptr = iPtr + audioBufferSize - jpos;
1029 double slope21 = audioBuffer1[shape].frames[(jptr + 1) % audioBufferSize] -
1030 audioBuffer1[shape].frames[jptr % audioBufferSize];
1031 double slope22 = audioBuffer2[shape].frames[(jptr + 1) % audioBufferSize] -
1032 audioBuffer2[shape].frames[jptr % audioBufferSize];
1033 double slopeDiff1 = slope11[j] - slope21;
1034 double slopeDiff2 = slope12[j] - slope22;
1035 overlayScore += SQR (slopeDiff1) + SQR (slopeDiff2);
1036 }
1037
1038 if (overlayScore < bestOverlayScore)
1039 {
1040 bestI = i;
1041 bestOverlayScore = overlayScore;
1042 }
1043 }
1044
1045 newRPtr1 = (wPtr + 2 * audioBufferSize - delayframes - bestI) % audioBufferSize;
1046 newRPtr2 = newRPtr1;
1047 }
1048
1049 // Write back pointers
1050 audioBuffer1[shape].wPtr1 = (wPtr + 1) % audioBufferSize;
1051 audioBuffer2[shape].wPtr1 = audioBuffer1[shape].wPtr1;
1052 audioBuffer1[shape].rPtr1 = newRPtr1;
1053 audioBuffer2[shape].rPtr1 = newRPtr1;
1054 audioBuffer1[shape].rPtr2 = (newRPtr2 + 1) % audioBufferSize;
1055 audioBuffer2[shape].rPtr2 = audioBuffer1[shape].rPtr2;
1056 }
1057
1058 // Delay with Doppler effect
doppler(const float input1,const float input2,float * output1,float * output2,const float delaytime,const int shape)1059 void BShapr::doppler (const float input1, const float input2, float* output1, float* output2, const float delaytime, const int shape)
1060 {
1061 const int audioBufferSize = rate;
1062 float param = LIM (delaytime, methods[DELAY].limit.min, methods[DELAY].limit.max) * rate / 1000;
1063 const float delayframes = LIM (param, 0, audioBufferSize);
1064
1065 const uint32_t wPtr = uint32_t (audioBuffer1[shape].wPtr1) % audioBufferSize;
1066 const uint32_t rPtrInt = uint32_t (audioBuffer1[shape].rPtr1) % audioBufferSize;
1067 const double rPtrFrac = fmod (audioBuffer1[shape].rPtr1, 1);
1068
1069 // Write to buffers and output
1070 audioBuffer1[shape].frames[wPtr] = input1;
1071 audioBuffer2[shape].frames[wPtr] = input2;
1072 *output1 = (1 - rPtrFrac) * audioBuffer1[shape].frames[rPtrInt] +
1073 rPtrFrac * audioBuffer1[shape].frames[(rPtrInt + 1) % audioBufferSize];
1074 *output2 = (1 - rPtrFrac) * audioBuffer2[shape].frames[rPtrInt] +
1075 rPtrFrac * audioBuffer2[shape].frames[(rPtrInt + 1) % audioBufferSize];
1076
1077 // Update pointers
1078 audioBuffer1[shape].wPtr1 = (wPtr + 1) % audioBufferSize;
1079 audioBuffer2[shape].wPtr1 = audioBuffer1[shape].wPtr1;
1080 audioBuffer1[shape].rPtr1 = fmod (audioBuffer1[shape].wPtr1 + audioBufferSize - delayframes, audioBufferSize);
1081 audioBuffer2[shape].rPtr1 = audioBuffer1[shape].rPtr1;
1082 }
1083
distortion(const float input1,const float input2,float * output1,float * output2,const int mode,const float drive,const float limit)1084 void BShapr::distortion (const float input1, const float input2, float* output1, float* output2, const int mode, const float drive, const float limit)
1085 {
1086 const float f = db2co (LIM (drive, methods[DISTORTION].limit.min, methods[DISTORTION].limit.max));
1087 const float l = db2co (LIM (limit, options[LIMIT_DB_OPT].limit.min, options[LIMIT_DB_OPT].limit.max));
1088 double i1 = input1 * f / l;
1089 double i2 = input2 * f / l;
1090
1091 switch (mode)
1092 {
1093 case HARDCLIP:
1094 *output1 = LIM (l * i1, -l, l);
1095 *output2 = LIM (l * i2, -l, l);
1096 break;
1097
1098 case SOFTCLIP:
1099 *output1 = SGN (i1) * l * sqrt (SQR (i1) / (1 + SQR (i1)));
1100 *output2 = SGN (i2) * l * sqrt (SQR (i2) / (1 + SQR (i2)));
1101 break;
1102
1103 case FOLDBACK:
1104 *output1 = (fabs (i1) <= 1 ? l * i1 : (SGN (i1) * l * double (2 * (int ((abs (i1) + 1) / 2) % 2) - 1) * (1.0 - fmod (fabs (i1) + 1, 2))));
1105 *output2 = (fabs (i2) <= 1 ? l * i2 : (SGN (i2) * l * double (2 * (int ((abs (i2) + 1) / 2) % 2) - 1) * (1.0 - fmod (fabs (i2) + 1, 2))));
1106 break;
1107
1108 case OVERDRIVE:
1109 *output1 = ((fabs (i1) < (1.0/3.0)) ? (2.0 * l * i1) : ((fabs (i1) < (2.0/3.0)) ? (SGN (i1) * l * (3.0 - SQR (2.0 - 3.0 * fabs (i1))) / 3.0) : l * SGN (i1)));
1110 *output2 = ((fabs (i2) < (1.0/3.0)) ? (2.0 * l * i2) : ((fabs (i2) < (2.0/3.0)) ? (SGN (i2) * l * (3.0 - SQR (2.0 - 3.0 * fabs (i2))) / 3.0) : l * SGN (i2)));
1111 break;
1112
1113 case FUZZ:
1114 *output1 = SGN (i1) * l * (1 - exp (- fabs (i1)));
1115 *output2 = SGN (i2) * l * (1 - exp (- fabs (i2)));
1116 break;
1117
1118 default:
1119 *output1 = input1;
1120 *output2 = input2;
1121 break;
1122 }
1123 }
1124
decimate(const float input1,const float input2,float * output1,float * output2,const float hz,const int shape)1125 void BShapr::decimate (const float input1, const float input2, float* output1, float* output2, const float hz, const int shape)
1126 {
1127 const double f = LIM (hz, methods[DECIMATE].limit.min, methods[DECIMATE].limit.max);
1128 if (decimateCounter[shape] + 1 >= double (rate) / f)
1129 {
1130 decimateBuffer1[shape] = input1;
1131 decimateBuffer2[shape] = input2;
1132 float c0 = double (rate) / f - decimateCounter[shape];
1133 decimateCounter[shape] = (c0 > 0 ? c0 : 0);
1134 }
1135
1136 else decimateCounter[shape]++;
1137
1138 *output1 = decimateBuffer1[shape];
1139 *output2 = decimateBuffer2[shape];
1140 }
1141
bitcrush(const float input1,const float input2,float * output1,float * output2,const float bitNr)1142 void BShapr::bitcrush (const float input1, const float input2, float* output1, float* output2, const float bitNr)
1143 {
1144 const double f = pow (2, LIM (bitNr, methods[BITCRUSH].limit.min, methods[BITCRUSH].limit.max) - 1);
1145 const int64_t bits1 = round (double (input1) * f);
1146 const int64_t bits2 = round (double (input2) * f);
1147 *output1 = double (bits1) / f;
1148 *output2 = double (bits2) / f;
1149 }
1150
1151
1152 #ifdef SUPPORTS_CV
sendCv(const float input1,const float input2,float * output1,float * output2,float * cv,const float amp)1153 void BShapr::sendCv (const float input1, const float input2, float* output1, float* output2, float* cv, const float amp)
1154 {
1155 *output1 = input1;
1156 *output2 = input2;
1157 if (cv) *cv = LIM (amp, 0.0f, 1.0f);
1158 }
1159
1160 #else
sendMidi(const float input1,const float input2,float * output1,float * output2,const uint8_t midiCh,const uint8_t midiCC,const float amp,uint32_t frames,const int shape)1161 void BShapr::sendMidi (const float input1, const float input2, float* output1, float* output2, const uint8_t midiCh, const uint8_t midiCC, const float amp, uint32_t frames, const int shape)
1162 {
1163 *output1 = input1;
1164 *output2 = input2;
1165
1166 uint8_t newValue = amp * 128;
1167 newValue = LIM (newValue, 0, 127);
1168
1169 if (newValue != sendValue[shape])
1170 {
1171 LV2_Atom midiatom;
1172 midiatom.type = urids.midi_Event;
1173 midiatom.size = 3;
1174
1175 uint8_t startCh = (midiCh == 0 ? 0 : midiCh - 1);
1176 uint8_t endCh = (midiCh == 0 ? 15 : midiCh - 1);
1177
1178 for (uint8_t ch = startCh; ch <= endCh; ++ ch)
1179 {
1180 uint8_t status = LV2_MIDI_MSG_CONTROLLER + ch;
1181 uint8_t msg[3] = {status, midiCC, newValue};
1182
1183 lv2_atom_forge_frame_time (&forge, frames);
1184 lv2_atom_forge_raw (&forge, &midiatom, sizeof (LV2_Atom));
1185 lv2_atom_forge_raw (&forge, &msg, 3);
1186 lv2_atom_forge_pad (&forge, sizeof (LV2_Atom) + 3);
1187 }
1188 sendValue[shape] = newValue;
1189 }
1190 }
1191 #endif
1192
play(uint32_t start,uint32_t end)1193 void BShapr::play (uint32_t start, uint32_t end)
1194 {
1195 if (end < start) return;
1196
1197 #ifdef SUPPORTS_CV
1198 // Clear CV out
1199 for (int i = 0; i < MAXSHAPES; ++i)
1200 {
1201 if (cvOutputs[i]) memset(&cvOutputs[i][start], 0, (end - start) * sizeof(float));
1202 }
1203 #endif
1204
1205 for (uint32_t i = start; i < end; ++i)
1206 {
1207 // Interpolate position within the loop
1208 double relpos = getPositionFromFrames (i - refFrame); // Position relative to reference frame
1209 double pos = floorfrac (position + relpos); // 0..1 position
1210
1211 float output1 = 0;
1212 float output2 = 0;
1213
1214 // Bypass
1215 if (controllers[BYPASS] != 0.0f)
1216 {
1217 output1 = audioInput1[i];
1218 output2 = audioInput2[i];
1219 }
1220
1221 // Audio calculations only if MIDI-independent or key pressed
1222 else if ((controllers[MIDI_CONTROL] == 0.0f) || (key != 0xFF))
1223 {
1224 float input1;
1225 float input2;
1226 float shapeOutput1[MAXSHAPES];
1227 memset (shapeOutput1, 0, MAXSHAPES * sizeof (float));
1228 float shapeOutput2[MAXSHAPES];
1229 memset (shapeOutput2, 0, MAXSHAPES * sizeof (float));
1230
1231 for (int sh = 0; sh < MAXSHAPES; ++sh)
1232 {
1233 if (controllers[SHAPERS + sh * SH_SIZE + SH_INPUT] != BShaprInputIndex::OFF)
1234 {
1235 // Connect to shaper input
1236 switch (int (controllers[SHAPERS + sh * SH_SIZE + SH_INPUT]))
1237 {
1238 case BShaprInputIndex::AUDIO_IN:
1239 input1 = audioInput1[i] * controllers[SHAPERS + sh * SH_SIZE + SH_INPUT_AMP];
1240 input2 = audioInput2[i] * controllers[SHAPERS + sh * SH_SIZE + SH_INPUT_AMP];
1241 break;
1242
1243 case BShaprInputIndex::CONSTANT:
1244 input1 = controllers[SHAPERS + sh * SH_SIZE + SH_INPUT_AMP];
1245 input2 = controllers[SHAPERS + sh * SH_SIZE + SH_INPUT_AMP];
1246 break;
1247
1248 default:
1249 if ((controllers[SHAPERS + sh * SH_SIZE + SH_INPUT] >= BShaprInputIndex::OUTPUT) &&
1250 (controllers[SHAPERS + sh * SH_SIZE + SH_INPUT] < BShaprInputIndex::OUTPUT + MAXSHAPES))
1251 {
1252 int inputSh = controllers[SHAPERS + sh * SH_SIZE + SH_INPUT] - BShaprInputIndex::OUTPUT;
1253 input1 = shapeOutput1[inputSh] * controllers[SHAPERS + sh * SH_SIZE + SH_INPUT_AMP];
1254 input2 = shapeOutput2[inputSh] * controllers[SHAPERS + sh * SH_SIZE + SH_INPUT_AMP];
1255 }
1256 else
1257 {
1258 input1 = 0;
1259 input2 = 0;
1260 }
1261 }
1262
1263 // Get shaper value for the actual position
1264 float iFactor = 0.0f;
1265 if (((speed == 0.0f) && (controllers[BASE] != SECONDS)) || (bpm < 1.0f)) iFactor = factors[sh].getValue();
1266 else
1267 {
1268 factors[sh].setTarget (shapes[sh].getMapValue (pos));
1269 iFactor = factors[sh].proceed();
1270 }
1271
1272 float drywet = controllers[SHAPERS + sh * SH_SIZE + SH_DRY_WET];
1273 float wet1 = 0;
1274 float wet2 = 0;
1275
1276 // Apply shaper on target
1277 switch (int (controllers[SHAPERS + sh * SH_SIZE + SH_TARGET]))
1278 {
1279 case BShaprTargetIndex::LEVEL:
1280 audioLevel (input1, input2, &wet1, &wet2, iFactor);
1281 break;
1282
1283 case BShaprTargetIndex::GAIN:
1284 audioLevel (input1, input2, &wet1, &wet2, db2co (LIM (iFactor, methods[GAIN].limit.min, methods[GAIN].limit.max)));
1285 break;
1286
1287 case BShaprTargetIndex::BALANCE:
1288 stereoBalance (input1, input2, &wet1, &wet2, iFactor);
1289 break;
1290
1291 case BShaprTargetIndex::WIDTH:
1292 stereoWidth (input1, input2, &wet1, &wet2, iFactor);
1293 break;
1294
1295 case BShaprTargetIndex::LOW_PASS:
1296 lowPassFilter (input1, input2, &wet1, &wet2, iFactor, sh);
1297 break;
1298
1299 case BShaprTargetIndex::LOW_PASS_LOG:
1300 lowPassFilter (input1, input2, &wet1, &wet2, pow (10, LIM (iFactor, methods[LOW_PASS_LOG].limit.min, methods[LOW_PASS_LOG].limit.max)), sh);
1301 break;
1302
1303 case BShaprTargetIndex::HIGH_PASS:
1304 highPassFilter (input1, input2, &wet1, &wet2, iFactor, sh);
1305 break;
1306
1307 case BShaprTargetIndex::HIGH_PASS_LOG:
1308 highPassFilter (input1, input2, &wet1, &wet2, pow (10, LIM (iFactor, methods[HIGH_PASS_LOG].limit.min, methods[HIGH_PASS_LOG].limit.max)), sh);
1309 break;
1310
1311 case BShaprTargetIndex::PITCH:
1312 pitch (input1, input2, &wet1, &wet2, iFactor, sh);
1313 break;
1314
1315 case BShaprTargetIndex::DELAY:
1316 delay (input1, input2, &wet1, &wet2, iFactor, sh);
1317 break;
1318
1319 case BShaprTargetIndex::DOPPLER:
1320 doppler (input1, input2, &wet1, &wet2, iFactor, sh);
1321 break;
1322
1323 case BShaprTargetIndex::DISTORTION:
1324 distortion
1325 (
1326 input1, input2, &wet1, &wet2,
1327 controllers[SHAPERS + sh * SH_SIZE + SH_OPTION + DISTORTION_OPT],
1328 iFactor,
1329 controllers[SHAPERS + sh * SH_SIZE + SH_OPTION + LIMIT_DB_OPT]
1330 );
1331 break;
1332
1333 case BShaprTargetIndex::DECIMATE:
1334 decimate (input1, input2, &wet1, &wet2, iFactor, sh);
1335 break;
1336
1337 case BShaprTargetIndex::BITCRUSH:
1338 bitcrush (input1, input2, &wet1, &wet2, iFactor);
1339 break;
1340
1341 #ifdef SUPPORTS_CV
1342 case BShaprTargetIndex::SEND_CV:
1343 sendCv (input1, input2, &wet1, &wet2, (cvOutputs[sh] ? &cvOutputs[sh][i] : nullptr), iFactor);
1344 break;
1345 #else
1346
1347 case BShaprTargetIndex::SEND_MIDI:
1348 sendMidi
1349 (
1350 input1, input2, &wet1, &wet2,
1351 controllers[SHAPERS + sh * SH_SIZE + SH_OPTION + SEND_MIDI_CH],
1352 controllers[SHAPERS + sh * SH_SIZE + SH_OPTION + SEND_MIDI_CC],
1353 iFactor, i, sh
1354 );
1355 break;
1356 #endif
1357 }
1358
1359 shapeOutput1[sh] = (1 - drywet) * input1 + drywet * wet1;
1360 shapeOutput2[sh] = (1 - drywet) * input2 + drywet * wet2;
1361
1362 if (controllers[SHAPERS + sh * SH_SIZE + SH_OUTPUT] == BShaprOutputIndex::AUDIO_OUT)
1363 {
1364 output1 += shapeOutput1[sh] * controllers[SHAPERS + sh * SH_SIZE + SH_OUTPUT_AMP];
1365 output2 += shapeOutput2[sh] * controllers[SHAPERS + sh * SH_SIZE + SH_OUTPUT_AMP];
1366 }
1367 }
1368 }
1369 }
1370
1371 // Analyze input and output data for GUI notification
1372 if (ui_on)
1373 {
1374 // Calculate position in monitor
1375 int newMonitorPos = pos * MONITORBUFFERSIZE;
1376 unsigned int nr = notificationsCount % NOTIFYBUFFERSIZE;
1377
1378 notifications[nr].position = newMonitorPos;
1379
1380 // Position changed? => Next nr
1381 if (newMonitorPos != monitorPos)
1382 {
1383 ++notificationsCount;
1384 stepCount = 0;
1385 nr = notificationsCount % NOTIFYBUFFERSIZE;
1386 memset(¬ifications[nr], 0, sizeof (BShaprNotifications));
1387 monitorPos = newMonitorPos;
1388 }
1389
1390 ++stepCount;
1391 float fstep = 1 / stepCount;
1392 float fprev = (stepCount - 1) * fstep;
1393
1394 if (audioInput1[i] < 0) notifications[nr].input1.min = fprev * notifications[nr].input1.min + fstep * audioInput1[i];
1395 else notifications[nr].input1.max = fprev * notifications[nr].input1.max + fstep * audioInput1[i];
1396 if (output1 < 0) notifications[nr].output1.min = fprev * notifications[nr].output1.min + fstep * output1;
1397 else notifications[nr].output1.max = fprev * notifications[nr].output1.max + fstep * output1;
1398 if (audioInput2[i] < 0) notifications[nr].input2.min = fprev * notifications[nr].input2.min + fstep * audioInput2[i];
1399 else notifications[nr].input2.max = fprev * notifications[nr].input2.max + fstep * audioInput2[i];
1400 if (output2 < 0) notifications[nr].output2.min = fprev * notifications[nr].output2.min + fstep * output2;
1401 else notifications[nr].output2.max = fprev * notifications[nr].output2.max + fstep * output2;
1402 }
1403
1404 // Store in audio out
1405 audioOutput1[i] = audioInput1[i] * (1 - controllers[DRY_WET]) + output1 * controllers[DRY_WET];
1406 audioOutput2[i] = audioInput2[i] * (1 - controllers[DRY_WET]) + output2 * controllers[DRY_WET];
1407 }
1408 }
1409
state_save(LV2_State_Store_Function store,LV2_State_Handle handle,uint32_t flags,const LV2_Feature * const * features)1410 LV2_State_Status BShapr::state_save (LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags,
1411 const LV2_Feature* const* features)
1412 {
1413 char shapesDataString[0x8010] = "Shape data:\n";
1414
1415 for (unsigned int sh = 0; sh < MAXSHAPES; ++sh)
1416 {
1417 for (unsigned int nd = 0; nd < shapes[sh].size (); ++nd)
1418 {
1419 char valueString[160];
1420 Node node = shapes[sh].getNode (nd);
1421 snprintf
1422 (
1423 valueString,
1424 126,
1425 "shp:%d; met:%d; typ:%d; ptx:%f; pty:%f; h1x:%f; h1y:%f; h2x:%f; h2y:%f",
1426 sh,
1427 int (controllers[SHAPERS + sh * SH_SIZE + SH_TARGET]),
1428 int (node.nodeType),
1429 node.point.x,
1430 node.point.y,
1431 node.handle1.x,
1432 node.handle1.y,
1433 node.handle2.x,
1434 node.handle2.y
1435 );
1436 if ((sh < MAXSHAPES - 1) || nd < shapes[sh].size ()) strcat (valueString, ";\n");
1437 else strcat(valueString, "\n");
1438 strcat (shapesDataString, valueString);
1439 }
1440 }
1441 store (handle, urids.state_shape, shapesDataString, strlen (shapesDataString) + 1, urids.atom_String, LV2_STATE_IS_POD);
1442
1443 return LV2_STATE_SUCCESS;
1444 }
1445
state_restore(LV2_State_Retrieve_Function retrieve,LV2_State_Handle handle,uint32_t flags,const LV2_Feature * const * features)1446 LV2_State_Status BShapr::state_restore (LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags,
1447 const LV2_Feature* const* features)
1448 {
1449 size_t size;
1450 uint32_t type;
1451 uint32_t valflags;
1452 const void* shapesData = retrieve(handle, urids.state_shape, &size, &type, &valflags);
1453
1454 if (shapesData && (type == urids.atom_String))
1455 {
1456 // Clear old data
1457 for (int i = 0; i < MAXSHAPES; ++i) shapes[i].clearShape ();
1458
1459 // Parse retrieved data
1460 std::string shapesDataString = (char*) shapesData;
1461 const std::string keywords[9] = {"shp:", "met:", "typ:", "ptx:", "pty:", "h1x:", "h1y:", "h2x:", "h2y:"};
1462 while (!shapesDataString.empty())
1463 {
1464 // Look for next "shp:"
1465 size_t strPos = shapesDataString.find ("shp:");
1466 size_t nextPos = 0;
1467 if (strPos == std::string::npos) break; // No "shp:" found => end
1468 if (strPos + 4 > shapesDataString.length()) break; // Nothing more after id => end
1469 shapesDataString.erase (0, strPos + 4);
1470
1471 int sh;
1472 try {sh = BUtilities::stof (shapesDataString, &nextPos);}
1473 catch (const std::exception& e)
1474 {
1475 fprintf (stderr, "BShapr.lv2: Restore shape state incomplete. Can't parse shape number from \"%s...\"", shapesDataString.substr (0, 63).c_str());
1476 break;
1477 }
1478
1479 if (nextPos > 0) shapesDataString.erase (0, nextPos);
1480 if ((sh < 0) || (sh >= MAXSHAPES))
1481 {
1482 fprintf (stderr, "BShapr.lv2: Restore shape state incomplete. Invalid matrix data block loaded for shape %i.\n", sh);
1483 break;
1484 }
1485
1486 // Look for shape data
1487 Node node = {NodeType::POINT_NODE, {0, 0}, {0, 0}, {0, 0}};
1488 bool isTypeDef = false;
1489 int methodNr = -1;
1490 for (int i = 1; i < 9; ++i)
1491 {
1492 strPos = shapesDataString.find (keywords[i]);
1493 if (strPos == std::string::npos) continue; // Keyword not found => next keyword
1494 if (strPos + 4 >= shapesDataString.length()) // Nothing more after keyword => end
1495 {
1496 shapesDataString ="";
1497 break;
1498 }
1499 if (strPos > 0) shapesDataString.erase (0, strPos + 4);
1500 float val;
1501 try {val = BUtilities::stof (shapesDataString, &nextPos);}
1502 catch (const std::exception& e)
1503 {
1504 fprintf (stderr, "BShapr.lv2: Restore shape state incomplete. Can't parse %s from \"%s...\"",
1505 keywords[i].substr(0,3).c_str(), shapesDataString.substr (0, 63).c_str());
1506 break;
1507 }
1508
1509 if (nextPos > 0) shapesDataString.erase (0, nextPos);
1510 switch (i)
1511 {
1512 case 1: methodNr = LIM (val, 0, MAXEFFECTS - 1);
1513 break;
1514 case 2: node.nodeType = (NodeType)((int)val);
1515 isTypeDef = true;
1516 break;
1517 case 3: node.point.x = val;
1518 break;
1519 case 4: node.point.y = val;
1520 break;
1521 case 5: node.handle1.x = val;
1522 break;
1523 case 6: node.handle1.y = val;
1524 break;
1525 case 7: node.handle2.x = val;
1526 break;
1527 case 8: node.handle2.y = val;
1528 break;
1529 default:break;
1530 }
1531 }
1532
1533 // Set data
1534 if (isTypeDef)
1535 {
1536 if (methodNr >=0)
1537 {
1538 shapes[sh].setTransformation (methods[methodNr].transformFactor, methods[methodNr].transformOffset);
1539 shapes[sh].appendNode (node);
1540 }
1541
1542 // Old versions (< 0.7): temp. store node until method is set
1543 else
1544 {
1545 tempNodes[sh].push_back (node);
1546 }
1547 }
1548 }
1549
1550 // Validate all shapes
1551 for (int i = 0; i < MAXSHAPES; ++i)
1552 {
1553 if (shapes[i].size () < 2) shapes[i].setDefaultShape ();
1554 else if (!shapes[i].validateShape ()) shapes[i].setDefaultShape ();
1555 }
1556
1557 // Force GUI notification
1558 for (int i = 0; i < MAXSHAPES; ++i) scheduleNotifyShapes[i] = true;
1559 }
1560
1561 return LV2_STATE_SUCCESS;
1562 }
1563
instantiate(const LV2_Descriptor * descriptor,double samplerate,const char * bundle_path,const LV2_Feature * const * features)1564 static LV2_Handle instantiate (const LV2_Descriptor* descriptor, double samplerate, const char* bundle_path, const LV2_Feature* const* features)
1565 {
1566 // New instance
1567 BShapr* instance;
1568 try {instance = new BShapr(samplerate, features);}
1569 catch (std::exception& exc)
1570 {
1571 fprintf (stderr, "BShapr.lv2: Plugin instantiation failed. %s\n", exc.what ());
1572 return NULL;
1573 }
1574
1575 if (!instance)
1576 {
1577 fprintf(stderr, "BShapr.lv2: Plugin instantiation failed.\n");
1578 return NULL;
1579 }
1580
1581 if (!instance->map)
1582 {
1583 fprintf(stderr, "BShapr.lv2: Host does not support urid:map.\n");
1584 delete (instance);
1585 return NULL;
1586 }
1587
1588 return (LV2_Handle)instance;
1589 }
1590
connect_port(LV2_Handle instance,uint32_t port,void * data)1591 static void connect_port (LV2_Handle instance, uint32_t port, void *data)
1592 {
1593 BShapr* inst = (BShapr*) instance;
1594 if (inst) inst->connect_port (port, data);
1595 }
1596
run(LV2_Handle instance,uint32_t n_samples)1597 static void run (LV2_Handle instance, uint32_t n_samples)
1598 {
1599 BShapr* inst = (BShapr*) instance;
1600 if (inst) inst->run (n_samples);
1601 }
1602
cleanup(LV2_Handle instance)1603 static void cleanup (LV2_Handle instance)
1604 {
1605 BShapr* inst = (BShapr*) instance;
1606 if (inst) delete inst;
1607 }
1608
state_save(LV2_Handle instance,LV2_State_Store_Function store,LV2_State_Handle handle,uint32_t flags,const LV2_Feature * const * features)1609 static LV2_State_Status state_save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags,
1610 const LV2_Feature* const* features)
1611 {
1612 BShapr* inst = (BShapr*)instance;
1613 if (!inst) return LV2_STATE_SUCCESS;
1614
1615 inst->state_save (store, handle, flags, features);
1616 return LV2_STATE_SUCCESS;
1617 }
1618
state_restore(LV2_Handle instance,LV2_State_Retrieve_Function retrieve,LV2_State_Handle handle,uint32_t flags,const LV2_Feature * const * features)1619 static LV2_State_Status state_restore(LV2_Handle instance, LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags,
1620 const LV2_Feature* const* features)
1621 {
1622 BShapr* inst = (BShapr*)instance;
1623 if (inst) inst->state_restore (retrieve, handle, flags, features);
1624 return LV2_STATE_SUCCESS;
1625 }
1626
extension_data(const char * uri)1627 static const void* extension_data(const char* uri)
1628 {
1629 static const LV2_State_Interface state = {state_save, state_restore};
1630 if (!strcmp(uri, LV2_STATE__interface)) {
1631 return &state;
1632 }
1633 return NULL;
1634 }
1635
1636 static const LV2_Descriptor descriptor =
1637 {
1638 BSHAPR_URI,
1639 instantiate,
1640 connect_port,
1641 NULL, //activate,
1642 run,
1643 NULL, //deactivate,
1644 cleanup,
1645 extension_data
1646 };
1647
1648 // LV2 Symbol Export
lv2_descriptor(uint32_t index)1649 LV2_SYMBOL_EXPORT const LV2_Descriptor* lv2_descriptor(uint32_t index)
1650 {
1651 switch (index)
1652 {
1653 case 0: return &descriptor;
1654 default: return NULL;
1655 }
1656 }
1657