aboutsummaryrefslogtreecommitdiffstats
path: root/plugins/eg-metro.lv2/metro.c
blob: cf6bccfcb04a6578a4c5a4f9b91df59a61309090 (plain)
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
/*
  LV2 Metronome Example Plugin
  Copyright 2012-2016 David Robillard <d@drobilla.net>

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

#include "lv2/atom/atom.h"
#include "lv2/atom/util.h"
#include "lv2/core/lv2.h"
#include "lv2/core/lv2_util.h"
#include "lv2/log/log.h"
#include "lv2/log/logger.h"
#include "lv2/time/time.h"
#include "lv2/urid/sid.h"
#include "lv2/urid/urid.h"

#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef M_PI
#    define M_PI 3.14159265
#endif

#define EG_METRO_URI "http://lv2plug.in/plugins/eg-metro"

static const double attack_s = 0.005;
static const double decay_s  = 0.075;

enum {
	METRO_CONTROL = 0,
	METRO_OUT     = 1
};

/** During execution this plugin can be in one of 3 states: */
typedef enum {
	STATE_ATTACK,  // Envelope rising
	STATE_DECAY,   // Envelope lowering
	STATE_OFF      // Silent
} State;

/**
   This plugin must keep track of more state than previous examples to be able
   to render audio.  The basic idea is to generate a single cycle of a sine
   wave which is conceptually played continuously.  The 'tick' is generated by
   enveloping the amplitude so there is a short attack/decay peak around a
   tick, and silence the rest of the time.

   This example uses a simple AD envelope with fixed parameters.  A more
   sophisticated implementation might use a more advanced envelope and allow
   the user to modify these parameters, the frequency of the wave, and so on.
*/
typedef struct {
	LV2_URID_Map*  map;     // URID map feature
	LV2_Log_Logger logger;  // Logger API

	struct {
		LV2_Atom_Sequence* control;
		float*             output;
	} ports;

	// Variables to keep track of the tempo information sent by the host
	double rate;   // Sample rate
	float  bpm;    // Beats per minute (tempo)
	float  speed;  // Transport speed (usually 0=stop, 1=play)

	uint32_t elapsed_len;  // Frames since the start of the last click
	uint32_t wave_offset;  // Current play offset in the wave
	State    state;        // Current play state

	// One cycle of a sine wave
	float*   wave;
	uint32_t wave_len;

	// Envelope parameters
	uint32_t attack_len;
	uint32_t decay_len;
} Metro;

static void
connect_port(LV2_Handle instance,
             uint32_t   port,
             void*      data)
{
	Metro* self = (Metro*)instance;

	switch (port) {
	case METRO_CONTROL:
		self->ports.control = (LV2_Atom_Sequence*)data;
		break;
	case METRO_OUT:
		self->ports.output = (float*)data;
		break;
	default:
		break;
	}
}

/**
   The activate() method resets the state completely, so the wave offset is
   zero and the envelope is off.
*/
static void
activate(LV2_Handle instance)
{
	Metro* self = (Metro*)instance;

	self->elapsed_len = 0;
	self->wave_offset = 0;
	self->state       = STATE_OFF;
}

/**
   This plugin does a bit more work in instantiate() than the previous
   examples.  The tempo updates from the host contain several URIs, so those
   are mapped, and the sine wave to be played needs to be generated based on
   the current sample rate.
*/
static LV2_Handle
instantiate(const LV2_Descriptor*     descriptor,
            double                    rate,
            const char*               path,
            const LV2_Feature* const* features)
{
	Metro* self = (Metro*)calloc(1, sizeof(Metro));
	if (!self) {
		return NULL;
	}

	// Scan host features for URID map
	const char* missing = lv2_features_query(
		features,
		LV2_LOG__log,  &self->logger.log, false,
		LV2_URID__map, &self->map, true,
		NULL);
	lv2_log_logger_set_map(&self->logger, self->map);
	if (missing) {
		lv2_log_error(&self->logger, "Missing feature <%s>\n", missing);
		free(self);
		return NULL;
	}

	// Initialise instance fields
	self->rate       = rate;
	self->bpm        = 120.0f;
	self->attack_len = (uint32_t)(attack_s * rate);
	self->decay_len  = (uint32_t)(decay_s * rate);
	self->state      = STATE_OFF;

	// Generate one cycle of a sine wave at the desired frequency
	const double freq = 440.0 * 2.0;
	const double amp  = 0.5;
	self->wave_len = (uint32_t)(rate / freq);
	self->wave     = (float*)malloc(self->wave_len * sizeof(float));
	for (uint32_t i = 0; i < self->wave_len; ++i) {
		self->wave[i] = (float)(sin(i * 2 * M_PI * freq / rate) * amp);
	}

	return (LV2_Handle)self;
}

static void
cleanup(LV2_Handle instance)
{
	free(instance);
}

/**
   Play back audio for the range [begin..end) relative to this cycle.  This is
   called by run() in-between events to output audio up until the current time.
*/
static void
play(Metro* self, uint32_t begin, uint32_t end)
{
	float* const   output          = self->ports.output;
	const uint32_t frames_per_beat = 60.0f / self->bpm * self->rate;

	if (self->speed == 0.0f) {
		memset(output, 0, (end - begin) * sizeof(float));
		return;
	}

	for (uint32_t i = begin; i < end; ++i) {
		switch (self->state) {
		case STATE_ATTACK:
			// Amplitude increases from 0..1 until attack_len
			output[i] = self->wave[self->wave_offset] *
				self->elapsed_len / (float)self->attack_len;
			if (self->elapsed_len >= self->attack_len) {
				self->state = STATE_DECAY;
			}
			break;
		case STATE_DECAY:
			// Amplitude decreases from 1..0 until attack_len + decay_len
			output[i] = 0.0f;
			output[i] = self->wave[self->wave_offset] *
				(1 - ((self->elapsed_len - self->attack_len) /
				      (float)self->decay_len));
			if (self->elapsed_len >= self->attack_len + self->decay_len) {
				self->state = STATE_OFF;
			}
			break;
		case STATE_OFF:
			output[i] = 0.0f;
		}

		// We continuously play the sine wave regardless of envelope
		self->wave_offset = (self->wave_offset + 1) % self->wave_len;

		// Update elapsed time and start attack if necessary
		if (++self->elapsed_len == frames_per_beat) {
			self->state       = STATE_ATTACK;
			self->elapsed_len = 0;
		}
	}
}

/**
   Update the current position based on a host message.  This is called by
   run() when a time:Position is received.
*/
static void
update_position(Metro* self, const LV2_Atom_Object* obj)
{
	// Received new transport position/speed
	LV2_Atom *beat = NULL, *bpm = NULL, *speed = NULL;
	lv2_atom_object_get(obj,
	                    LV2_URID_TIME_barBeat,        &beat,
	                    LV2_URID_TIME_beatsPerMinute, &bpm,
	                    LV2_URID_TIME_speed,          &speed,
	                    NULL);
	if (bpm && bpm->type == LV2_URID_ATOM_Float) {
		// Tempo changed, update BPM
		self->bpm = ((LV2_Atom_Float*)bpm)->body;
	}
	if (speed && speed->type == LV2_URID_ATOM_Float) {
		// Speed changed, e.g. 0 (stop) to 1 (play)
		self->speed = ((LV2_Atom_Float*)speed)->body;
	}
	if (beat && beat->type == LV2_URID_ATOM_Float) {
		// Received a beat position, synchronise
		// This hard sync may cause clicks, a real plugin would be more graceful
		const float frames_per_beat = 60.0f / self->bpm * self->rate;
		const float bar_beats       = ((LV2_Atom_Float*)beat)->body;
		const float beat_beats      = bar_beats - floorf(bar_beats);
		self->elapsed_len           = beat_beats * frames_per_beat;
		if (self->elapsed_len < self->attack_len) {
			self->state = STATE_ATTACK;
		} else if (self->elapsed_len < self->attack_len + self->decay_len) {
			self->state = STATE_DECAY;
		} else {
			self->state = STATE_OFF;
		}
	}
}

static void
run(LV2_Handle instance, uint32_t sample_count)
{
	Metro* self = (Metro*)instance;

	// Work forwards in time frame by frame, handling events as we go
	const LV2_Atom_Sequence* in     = self->ports.control;
	uint32_t                 last_t = 0;
	for (const LV2_Atom_Event* ev = lv2_atom_sequence_begin(&in->body);
	     !lv2_atom_sequence_is_end(&in->body, in->atom.size, ev);
	     ev = lv2_atom_sequence_next(ev)) {

		// Play the click for the time slice from last_t until now
		play(self, last_t, ev->time.frames);

		// Check if this event is an Object
		// (or deprecated Blank to tolerate old hosts)
		if (ev->body.type == LV2_URID_ATOM_Object ||
		    ev->body.type == LV2_URID_ATOM_Blank) {
			const LV2_Atom_Object* obj = (const LV2_Atom_Object*)&ev->body;
			if (obj->body.otype == LV2_URID_TIME_Position) {
				// Received position information, update
				update_position(self, obj);
			}
		}

		// Update time for next iteration and move to next event
		last_t = ev->time.frames;
	}

	// Play for remainder of cycle
	play(self, last_t, sample_count);
}

static const LV2_Descriptor descriptor = {
	EG_METRO_URI,
	instantiate,
	connect_port,
	activate,
	run,
	NULL,  // deactivate,
	cleanup,
	NULL,  // extension_data
};

LV2_SYMBOL_EXPORT const LV2_Descriptor*
lv2_descriptor(uint32_t index)
{
	switch (index) {
	case 0:
		return &descriptor;
	default:
		return NULL;
	}
}