1 /*
2  * Copyright (C) 2019-2020 Alexandros Theodotou <alex at zrythm dot org>
3  *
4  * This file is part of ZPlugins
5  *
6  * ZPlugins is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as
8  * published by the Free Software Foundation, either version 3 of the
9  * License, or (at your option) any later version.
10  *
11  * ZPlugins 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 Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Affero Public License
17  * along with ZPlugins.  If not, see <https://www.gnu.org/licenses/>.
18  */
19 
20 #include PLUGIN_CONFIG
21 
22 #include <math.h>
23 #include <stdlib.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 
27 #include "../math.h"
28 #include PLUGIN_COMMON
29 #include "lfo_math.h"
30 
31 #define math_floats_almost_equal(a,b) \
32   (a > b ? \
33    (a - b) < 0.0001f : \
34    (b - a) < 0.0001f)
35 
36 #define IS_FREERUN(x) (*x->freerun > 0.001f)
37 #define IS_STEP_MODE(x) (*x->step_mode > 0.001f)
38 #define IS_TRIGGERED(x) (*x->trigger > 0.001f)
39 #define IS_GATED_MODE(x) (*x->gated_mode > 0.001f)
40 #define IS_GATED(x) (*x->gate > 0.001f)
41 #define SINE_ON(x) (*x->sine_on > 0.001f)
42 #define SQUARE_ON(x) (*x->square_on > 0.001f)
43 #define TRIANGLE_ON(x) (*x->triangle_on > 0.001f)
44 #define SAW_ON(x) (*x->saw_on > 0.001f)
45 #define CUSTOM_ON(x) (*x->custom_on > 0.001f)
46 
47 typedef struct LFO
48 {
49   /** Plugin ports. */
50   const LV2_Atom_Sequence* control;
51   LV2_Atom_Sequence* notify;
52   const float * gate;
53   const float * trigger;
54   const float * cv_gate;
55   const float * cv_trigger;
56   const float * gated_mode;
57   const float * freq;
58   const float * shift;
59   const float * range_min;
60   const float * range_max;
61   const float * step_mode;
62   const float * freerun;
63   const float * grid_step;
64   const float * sync_rate;
65   const float * sync_rate_type;
66   const float * hinvert;
67   const float * vinvert;
68   const float * sine_on;
69   const float * saw_on;
70   const float * square_on;
71   const float * triangle_on;
72   const float * custom_on;
73   const float * nodes[16][3];
74   const float * num_nodes;
75 
76   /* outputs */
77   float *       cv_out;
78   float *       sine_out;
79   float *       saw_out;
80   float *       triangle_out;
81   float *       square_out;
82   float *       custom_out;
83   float *       sample_to_ui;
84 
85   /** This is how far we are inside a beat, from 0.0
86    * to 1.0. */
87   /*float         beat_offset;*/
88 
89   LfoCommon    common;
90 
91   /* FIXME this can be a local variable */
92   LV2_Atom_Forge_Frame notify_frame;
93 
94   /** Whether the UI is active or not. */
95   int           ui_active;
96 
97   /** Temporary variables. */
98 
99   /* whether the plugin was freerunning in the
100    * last cycle. this is used to detect changes
101    * in freerunning/sync. */
102   int           was_freerunning;
103 
104   /** Frequency during the last run. */
105   float         last_freq;
106   float         last_sync_rate;
107   float         last_sync_rate_type;
108 
109   /* These are used to detect changes so we
110    * can notify the UI. */
111   long          last_period_size;
112   double        last_samplerate;
113 
114   /** Flag to be used to send messages to the
115    * UI. */
116   int           first_run_with_ui;
117 
118 } LFO;
119 
120 static LV2_Handle
instantiate(const LV2_Descriptor * descriptor,double rate,const char * bundle_path,const LV2_Feature * const * features)121 instantiate (
122   const LV2_Descriptor*     descriptor,
123   double                    rate,
124   const char*               bundle_path,
125   const LV2_Feature* const* features)
126 {
127   LFO * self = calloc (1, sizeof (LFO));
128 
129   SET_SAMPLERATE (self, rate);
130 
131   PluginCommon * pl_common = &self->common.pl_common;
132   int ret =
133     plugin_common_instantiate (
134       pl_common, features, 0);
135   if (ret)
136     goto fail;
137 
138   /* map uris */
139   map_uris (pl_common->map, &self->common);
140 
141   /* init atom forge */
142   lv2_atom_forge_init (
143     &pl_common->forge, pl_common->map);
144 
145   /* init logger */
146   lv2_log_logger_init (
147     &pl_common->logger, pl_common->map, pl_common->log);
148 
149   return (LV2_Handle) self;
150 
151 fail:
152   free (self);
153   return NULL;
154 }
155 
156 static void
recalc_multipliers(LFO * self)157 recalc_multipliers (
158   LFO * self)
159 {
160   /* no ports connected yet */
161   if (!self->freerun)
162     return;
163 
164   float sync_rate_float =
165     sync_rate_to_float (
166       *self->sync_rate,
167       *self->sync_rate_type);
168 
169   /**
170    * Effective frequency.
171    *
172    * This is either the free-running frequency,
173    * or the frequency corresponding to the current
174    * sync rate.
175    */
176   float effective_freq =
177     get_effective_freq (
178       IS_FREERUN (self), *self->freq,
179       &self->common.host_pos, sync_rate_float);
180 
181   recalc_vars (
182     IS_FREERUN (self),
183     &self->common.sine_multiplier,
184     &self->common.saw_multiplier,
185     &self->common.period_size,
186     &self->common.current_sample,
187     &self->common.host_pos, effective_freq,
188     sync_rate_float,
189     (float) GET_SAMPLERATE (self));
190 }
191 
192 static void
connect_port(LV2_Handle instance,uint32_t port,void * data)193 connect_port (
194   LV2_Handle instance,
195   uint32_t   port,
196   void *     data)
197 {
198   LFO * self = (LFO*) instance;
199 
200   switch ((PortIndex) port)
201     {
202     case LFO_CONTROL:
203       self->control =
204         (const LV2_Atom_Sequence *) data;
205       break;
206     case LFO_NOTIFY:
207       self->notify =
208         (LV2_Atom_Sequence *) data;
209       break;
210     case LFO_CV_GATE:
211       self->cv_gate = (const float *) data;
212       break;
213     case LFO_CV_TRIGGER:
214       self->cv_trigger = (const float *) data;
215       break;
216     case LFO_GATE:
217       self->gate = (const float *) data;
218       break;
219     case LFO_TRIGGER:
220       self->trigger = (const float *) data;
221       break;
222     case LFO_GATED_MODE:
223       self->gated_mode = (const float *) data;
224       break;
225     case LFO_FREQ:
226       self->freq = (const float *) data;
227       break;
228     case LFO_SHIFT:
229       self->shift = (const float *) data;
230       break;
231     case LFO_RANGE_MIN:
232       self->range_min = (const float *) data;
233       break;
234     case LFO_RANGE_MAX:
235       self->range_max = (const float *) data;
236       break;
237     case LFO_STEP_MODE:
238       self->step_mode = (const float *) data;
239       break;
240     case LFO_FREE_RUNNING:
241       self->freerun = (const float *) data;
242       break;
243     case LFO_GRID_STEP:
244       self->grid_step = (const float *) data;
245       break;
246     case LFO_SYNC_RATE:
247       self->sync_rate = (const float *) data;
248       break;
249     case LFO_SYNC_RATE_TYPE:
250       self->sync_rate_type = (const float *) data;
251       break;
252     case LFO_HINVERT:
253       self->hinvert = (const float *) data;
254       break;
255     case LFO_VINVERT:
256       self->vinvert = (const float *) data;
257       break;
258     case LFO_SINE_TOGGLE:
259       self->sine_on = (const float *) data;
260       break;
261     case LFO_SAW_TOGGLE:
262       self->saw_on = (const float *) data;
263       break;
264     case LFO_SQUARE_TOGGLE:
265       self->square_on = (const float *) data;
266       break;
267     case LFO_TRIANGLE_TOGGLE:
268       self->triangle_on = (const float *) data;
269       break;
270     case LFO_CUSTOM_TOGGLE:
271       self->custom_on = (const float *) data;
272       break;
273     case LFO_SINE_OUT:
274       self->sine_out = (float *) data;
275       break;
276     case LFO_SAW_OUT:
277       self->saw_out = (float *) data;
278       break;
279     case LFO_TRIANGLE_OUT:
280       self->triangle_out = (float *) data;
281       break;
282     case LFO_SQUARE_OUT:
283       self->square_out = (float *) data;
284       break;
285     case LFO_CUSTOM_OUT:
286       self->custom_out = (float *) data;
287       break;
288     case LFO_SAMPLE_TO_UI:
289       self->sample_to_ui = (float *) data;
290       break;
291     case LFO_NUM_NODES:
292       self->num_nodes = (float *) data;
293       break;
294     default:
295       break;
296     }
297 
298   if (port >= LFO_NODE_1_POS &&
299       port <= LFO_NODE_16_CURVE)
300     {
301       unsigned int prop =
302         (port - LFO_NODE_1_POS) % 3;
303       unsigned int node_id =
304         (port - LFO_NODE_1_POS) / 3;
305       self->nodes[node_id][prop] =
306         (const float *) data;
307     }
308 }
309 
310 static void
send_position_to_ui(LFO * self)311 send_position_to_ui (
312   LFO *  self)
313 {
314   PluginCommon * pl_common = &self->common.pl_common;
315 
316   /* forge container object of type time_Position */
317   lv2_atom_forge_frame_time (&pl_common->forge, 0);
318   LV2_Atom_Forge_Frame frame;
319   lv2_atom_forge_object (
320     &pl_common->forge, &frame, 0,
321     pl_common->uris.time_Position);
322 
323   /* append property for bpm */
324   lv2_atom_forge_key (
325     &pl_common->forge,
326     pl_common->uris.time_beatsPerMinute);
327   lv2_atom_forge_float (
328     &pl_common->forge, self->common.host_pos.bpm);
329 
330   /* append property for current sample */
331   lv2_atom_forge_key (
332     &pl_common->forge,
333     pl_common->uris.time_frame);
334   lv2_atom_forge_long (
335     &pl_common->forge,
336     self->common.host_pos.frame);
337 
338   /* append speed */
339   lv2_atom_forge_key (
340     &pl_common->forge,
341     pl_common->uris.time_speed);
342   lv2_atom_forge_float (
343     &pl_common->forge,
344     self->common.host_pos.speed);
345 
346   /* append beat unit */
347   lv2_atom_forge_key (
348     &pl_common->forge,
349     pl_common->uris.time_beatUnit);
350   lv2_atom_forge_int (
351     &pl_common->forge,
352     self->common.host_pos.beat_unit);
353 
354   /* finish object */
355   lv2_atom_forge_pop (&pl_common->forge, &frame);
356 }
357 
358 static void
send_messages_to_ui(LFO * self,int send_position)359 send_messages_to_ui (
360   LFO * self,
361   int    send_position)
362 {
363   PluginCommon * pl_common = &self->common.pl_common;
364 
365   /* set up forge to write directly to notify
366    * output port */
367   const uint32_t notify_capacity =
368     self->notify->atom.size;
369   lv2_atom_forge_set_buffer (
370     &pl_common->forge, (uint8_t*) self->notify,
371     notify_capacity);
372 
373   /* start a sequence in the notify output port */
374   lv2_atom_forge_sequence_head (
375     &pl_common->forge, &self->notify_frame, 0);
376 
377   /* forge container object of type "ui_state" */
378   lv2_atom_forge_frame_time (&pl_common->forge, 0);
379   LV2_Atom_Forge_Frame frame;
380   lv2_atom_forge_object (
381     &pl_common->forge, &frame, 0,
382     self->common.uris.ui_state);
383 
384   /* append property for current sample */
385   lv2_atom_forge_key (
386     &pl_common->forge,
387     self->common.uris.ui_state_current_sample);
388   lv2_atom_forge_long (
389     &pl_common->forge,
390     self->common.current_sample);
391 
392   /* append property for period size */
393   lv2_atom_forge_key (
394     &pl_common->forge,
395     self->common.uris.ui_state_period_size);
396   lv2_atom_forge_long (
397     &pl_common->forge, self->common.period_size);
398 
399   /* append samplerate */
400   lv2_atom_forge_key (
401     &pl_common->forge,
402     self->common.uris.ui_state_samplerate);
403   lv2_atom_forge_double (
404     &pl_common->forge, GET_SAMPLERATE (self));
405 
406   /* append sine multiplier */
407   lv2_atom_forge_key (
408     &pl_common->forge,
409     self->common.uris.ui_state_sine_multiplier);
410   lv2_atom_forge_float (
411     &pl_common->forge,
412     self->common.sine_multiplier);
413 
414   /* append saw multiplier */
415   lv2_atom_forge_key (
416     &pl_common->forge,
417     self->common.uris.ui_state_saw_multiplier);
418   lv2_atom_forge_float (
419     &pl_common->forge,
420     self->common.saw_multiplier);
421 
422   /* finish object */
423   lv2_atom_forge_pop (&pl_common->forge, &frame);
424 
425   if (send_position)
426     {
427       send_position_to_ui (self);
428     }
429 }
430 
431 static void
activate(LV2_Handle instance)432 activate (
433   LV2_Handle instance)
434 {
435   LFO * self = (LFO*) instance;
436 
437   self->first_run_with_ui = 1;
438 
439   recalc_multipliers (self);
440 }
441 
442 static void
run(LV2_Handle instance,uint32_t n_samples)443 run (
444   LV2_Handle instance,
445   uint32_t n_samples)
446 {
447   LFO * self = (LFO *) instance;
448   PluginCommon * pl_common = &self->common.pl_common;
449 
450 #ifdef TRIAL_VER
451   if (get_time_since_instantiation (
452         &self->common.pl_common) > SECONDS_TO_SILENCE)
453     return;
454 #endif
455 
456   int xport_changed = 0;
457 
458   /* read incoming events from host and UI */
459   LV2_ATOM_SEQUENCE_FOREACH (
460     self->control, ev)
461     {
462       if (lv2_atom_forge_is_object_type (
463             &pl_common->forge, ev->body.type))
464         {
465           const LV2_Atom_Object * obj =
466             (const LV2_Atom_Object*)&ev->body;
467           if (obj->body.otype ==
468                 pl_common->uris.time_Position)
469             {
470               update_position_from_atom_obj (
471                 &self->common, obj);
472               xport_changed = 1;
473             }
474           else if (obj->body.otype ==
475                      self->common.uris.ui_on)
476             {
477               self->ui_active = 1;
478               self->first_run_with_ui = 1;
479             }
480           else if (obj->body.otype ==
481                      self->common.uris.ui_off)
482             {
483               self->ui_active = 0;
484             }
485         }
486     }
487 
488   int freq_changed =
489     !math_floats_almost_equal(
490       self->last_freq, *self->freq);
491   int is_freerunning = *self->freerun > 0.0001f;
492   int sync_or_freerun_mode_changed =
493     self->was_freerunning != is_freerunning;
494   int sync_rate_changed =
495     !(math_floats_almost_equal (
496       self->last_sync_rate, *self->sync_rate) &&
497     math_floats_almost_equal (
498       self->last_sync_rate_type,
499       *self->sync_rate_type));
500 
501   /* if freq or transport changed, reset the
502    * multipliers */
503   if (xport_changed || freq_changed ||
504       sync_rate_changed ||
505       sync_or_freerun_mode_changed)
506     {
507 #if 0
508       fprintf (
509         stderr, "xport %d freq %d sync %d\n",
510         xport_changed, freq_changed,
511         sync_or_freerun_mode_changed);
512 #endif
513       recalc_multipliers (self);
514     }
515 
516   float max_range =
517     MAX (*self->range_max, *self->range_min);
518   float min_range =
519     MIN (*self->range_max, *self->range_min);
520   float range = max_range - min_range;
521 
522   float grid_step_divisor =
523     (float)
524     grid_step_to_divisor (
525       (GridStep) *self->grid_step);
526   long step_frames =
527     (long)
528     ((float) self->common.period_size /
529      grid_step_divisor);
530 
531   /* sort node curves by position */
532   NodeIndexElement node_indices[
533     (int) *self->num_nodes];
534   float nodes[16][3];
535   for (int i = 0; i < 16; i++)
536     {
537       for (int j = 0; j < 3; j++)
538         {
539           nodes[i][j] = *(self->nodes[i][j]);
540         }
541     }
542   sort_node_indices_by_pos (
543     nodes, node_indices,
544     (int) *self->num_nodes);
545 
546   /* handle control trigger */
547   if (IS_TRIGGERED (self))
548     {
549       self->common.current_sample = 0;
550     }
551 
552   for (uint32_t i = 0; i < n_samples; i++)
553     {
554       /* handle cv trigger */
555       if (self->cv_trigger[i] > 0.00001f)
556         self->common.current_sample = 0;
557 
558       /* invert horizontally */
559       long shifted_current_sample =
560         invert_and_shift_xval (
561           self->common.current_sample,
562           self->common.period_size,
563           *self->hinvert >= 0.01f,
564           *self->shift);
565 
566       if (IS_STEP_MODE (self))
567         {
568           /* find closest step and set the current
569            * sample to the middle of it */
570           shifted_current_sample =
571             (shifted_current_sample / step_frames) *
572               step_frames +
573             step_frames / 2;
574         }
575 
576       float ratio =
577          (float) shifted_current_sample /
578          (float) self->common.period_size;
579 
580       if (SINE_ON (self))
581         {
582           /* calculate sine */
583           self->sine_out[i] =
584             sinf (
585               ((float) shifted_current_sample *
586                   self->common.sine_multiplier));
587         }
588       if (SAW_ON (self))
589         {
590           /* calculate saw */
591           self->saw_out[i] =
592             (1.f - ratio) * 2.f - 1.f;
593         }
594       if (TRIANGLE_ON (self))
595         {
596           if (ratio > 0.4999f)
597             {
598               self->triangle_out[i] =
599                 (1.f - ratio) * 4.f - 1.f;
600             }
601           else
602             {
603               self->triangle_out[i] =
604                 ratio * 4.f - 1.f;
605             }
606         }
607       if (SQUARE_ON (self))
608         {
609           if (ratio > 0.4999f)
610             {
611               self->square_out[i] = - 1.f;
612             }
613           else
614             {
615               self->square_out[i] = 1.f;
616             }
617         }
618       if (CUSTOM_ON (self))
619         {
620           int prev_idx =
621             get_prev_idx (
622               node_indices, (int) * self->num_nodes,
623               (float) ratio);
624           int next_idx =
625             get_next_idx (
626               node_indices, (int) * self->num_nodes,
627               (float) ratio);
628 
629           /* calculate custom */
630           self->custom_out[i] =
631             get_custom_val_at_x (
632               *self->nodes[prev_idx][0],
633               *self->nodes[prev_idx][1],
634               *self->nodes[prev_idx][2],
635               next_idx < 0 ? 1.f :
636                 *self->nodes[next_idx][0],
637               next_idx < 0 ?
638                 *self->nodes[0][1] :
639                 *self->nodes[next_idx][1],
640               next_idx < 0 ?
641                 *self->nodes[0][2] :
642                 *self->nodes[next_idx][2],
643               shifted_current_sample,
644               self->common.period_size);
645 
646           /* adjust for -1 to 1 */
647           self->custom_out[i] =
648             self->custom_out[i] * 2 - 1;
649         }
650 
651       /* invert vertically */
652       if (*self->vinvert >= 0.01f)
653         {
654 #define INVERT(x) \
655   self->x##_out[i] = - self->x##_out[i]
656 
657           INVERT (sine);
658           INVERT (saw);
659           INVERT (triangle);
660           INVERT (square);
661           INVERT (custom);
662 
663 #undef INVERT
664         }
665 
666       /* if in gating mode and gate is not active,
667        * set all output to zero */
668       if (IS_GATED_MODE (self) &&
669           !(IS_GATED (self) || self->cv_gate[i] > 0.001f))
670         {
671           self->sine_out[i] = 0.f;
672           self->saw_out[i] = 0.f;
673           self->triangle_out[i] = 0.f;
674           self->square_out[i] = 0.f;
675           self->custom_out[i] = 0.f;
676         }
677 
678       /* adjust range */
679 #define ADJUST_RANGE(x) \
680   self->x##_out[i] = \
681     min_range + \
682     ((self->x##_out[i] + 1.f) / 2.f) * range
683 
684       ADJUST_RANGE (sine);
685       ADJUST_RANGE (saw);
686       ADJUST_RANGE (triangle);
687       ADJUST_RANGE (square);
688       ADJUST_RANGE (custom);
689 
690 #undef ADJUST_RANGE
691 
692       if (is_freerunning ||
693           (!is_freerunning &&
694            self->common.host_pos.speed >
695              0.00001f))
696         {
697           self->common.current_sample++;
698         }
699       if (self->common.current_sample ==
700             self->common.period_size)
701         self->common.current_sample = 0;
702     }
703 #if 0
704   fprintf (
705     stderr, "current sample %ld, "
706     "period size%ld\n",
707     self->current_sample, self->period_size);
708 #endif
709 
710   if (self->ui_active &&
711       (self->common.period_size !=
712          self->last_period_size ||
713        !math_doubles_equal (
714          GET_SAMPLERATE (self),
715          self->last_samplerate) ||
716        xport_changed ||
717        self->first_run_with_ui))
718     {
719       /*fprintf (stderr, "sending messages\n");*/
720       send_messages_to_ui (self, xport_changed);
721       self->first_run_with_ui = 0;
722     }
723 
724   /* set current sample for UI to pick up */
725   *self->sample_to_ui =
726     (float) self->common.current_sample;
727 
728   /* remember values */
729   self->last_freq = *self->freq;
730   self->last_sync_rate = *self->sync_rate;
731   self->last_sync_rate_type = *self->sync_rate_type;
732   self->was_freerunning = is_freerunning;
733   self->last_period_size =
734     self->common.period_size;
735   self->last_samplerate = GET_SAMPLERATE (self);
736 }
737 
738 static void
deactivate(LV2_Handle instance)739 deactivate (
740   LV2_Handle instance)
741 {
742 }
743 
744 static void
cleanup(LV2_Handle instance)745 cleanup (
746   LV2_Handle instance)
747 {
748   free (instance);
749 }
750 
751 static const void*
extension_data(const char * uri)752 extension_data (
753   const char* uri)
754 {
755   return NULL;
756 }
757 
758 static const LV2_Descriptor descriptor = {
759   PLUGIN_URI,
760   instantiate,
761   connect_port,
762   activate,
763   run,
764   deactivate,
765   cleanup,
766   extension_data
767 };
768 
769 LV2_SYMBOL_EXPORT
770 const LV2_Descriptor*
lv2_descriptor(uint32_t index)771 lv2_descriptor (
772   uint32_t index)
773 {
774   switch (index)
775     {
776     case 0:
777       return &descriptor;
778     default:
779       return NULL;
780     }
781 }
782