-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlight_sampler.c
More file actions
1040 lines (890 loc) · 34.7 KB
/
light_sampler.c
File metadata and controls
1040 lines (890 loc) · 34.7 KB
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Light Sampler LV2 Plugin - Sampler plugin
* Copyright (C) 2026 Simon Delaruotte
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*/
#include "light_sampler_uris.h"
#include "light_sampler_peaks.h"
#include "atom_sink.h"
/* LV2 includes - use the paths that match your system */
#include <lv2/core/lv2.h>
#include <lv2/atom/atom.h>
#include <lv2/atom/forge.h>
#include <lv2/atom/util.h>
#include <lv2/midi/midi.h>
#include <lv2/urid/urid.h>
#include <lv2/state/state.h>
#include <lv2/worker/worker.h>
#include <lv2/log/log.h>
#include <lv2/log/logger.h>
#include <lv2/patch/patch.h>
#include <sndfile.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#define LIGHT_SAMPLER_URI "urn:simdott:light_sampler"
/* Missing LV2 utility functions */
#ifndef HAVE_LV2_FEATURES_QUERY
static inline const char*
lv2_features_query(const LV2_Feature* const* features,
const char* uri, void** data, bool required, ...)
{
va_list args;
va_start(args, required);
for (int i = 0; features[i]; ++i) {
if (!strcmp(features[i]->URI, uri)) {
if (data) *data = features[i]->data;
va_end(args);
return NULL;
}
}
while (1) {
const char* next_uri = va_arg(args, const char*);
if (!next_uri) break;
void** next_data = va_arg(args, void**);
bool next_required = (bool)va_arg(args, int);
for (int i = 0; features[i]; ++i) {
if (!strcmp(features[i]->URI, next_uri)) {
if (next_data) *next_data = features[i]->data;
va_end(args);
return NULL;
}
}
if (next_required) {
va_end(args);
return next_uri;
}
}
va_end(args);
if (data) *data = NULL;
return NULL;
}
#endif
#ifndef HAVE_LV2_FEATURES_DATA
static inline void*
lv2_features_data(const LV2_Feature* const* features, const char* uri)
{
for (int i = 0; features[i]; ++i) {
if (!strcmp(features[i]->URI, uri)) {
return features[i]->data;
}
}
return NULL;
}
#endif
typedef enum {
CONTROL_IN = 0,
NOTIFY_OUT = 1,
AUDIO_OUT_L = 2,
AUDIO_OUT_R = 3,
PLAY_BACKWARD= 4,
HUMANIZE = 5,
STEREO = 6,
MIDI_CHANNEL = 7,
MIDI_NOTE = 8,
PITCH_SHIFT = 9,
VOICE_MODE = 10,
ATTACK = 11,
HOLD = 12,
DECAY = 13,
SUSTAIN = 14,
RELEASE = 15,
VOLUME = 16
} PortIndex;
typedef struct {
SF_INFO info;
float* data;
char* path;
uint32_t path_len;
} Sample;
typedef struct {
float position;
float gain;
bool play;
float envelope;
float attack_rate;
float hold_frames;
float decay_rate;
float sustain_level;
float release_rate;
float current_attack_rate;
uint32_t current_hold_frames;
float current_decay_rate;
float current_sustain_level;
float current_release_rate;
uint8_t current_note;
float velocity_gain;
float pitch_shift_value;
float humanize_offset;
float humanize_volume;
uint32_t hold_counter;
int envelope_state;
} Voice;
typedef struct {
// Features
LV2_URID_Map* map;
LV2_Worker_Schedule* schedule;
LV2_Log_Logger logger;
// Ports
const LV2_Atom_Sequence* control_port;
LV2_Atom_Sequence* notify_port;
float* output_port_l;
float* output_port_r;
const float* midi_channel;
const float* midi_note;
const float* play_backward;
const float* humanize;
const float* pitch_shift;
const float* voice_mode;
const float* attack;
const float* hold;
const float* decay;
const float* sustain;
const float* release;
const float* volume;
const float* stereo;
LV2_Atom_Forge forge;
LightSamplerURIs uris;
PeaksSender peaks_sender;
Sample* sample;
uint64_t frame_offset;
float global_gain;
bool gain_changed;
bool sample_changed;
bool activated;
Voice voice0;
Voice voice1;
bool active_voice_count;
uint8_t last_note;
uint64_t last_note_frame;
uint32_t random_state;
uint32_t host_rate;
float sample_rate_ratio;
} LightSampler;
typedef struct {
LV2_Atom atom;
Sample* sample;
} SampleMessage;
/* Helper functions */
static Sample* load_sample(LV2_Log_Logger* logger, const char* path) {
lv2_log_trace(logger, "Loading %s\n", path);
const size_t path_len = strlen(path);
Sample* sample = (Sample*)calloc(1, sizeof(Sample));
SF_INFO* info = &sample->info;
SNDFILE* sndfile = sf_open(path, SFM_READ, info);
float* data = NULL;
bool error = true;
if (!sndfile || !info->frames) {
lv2_log_error(logger, "Failed to open %s\n", path);
} else if (info->channels != 1 && info->channels != 2) {
lv2_log_error(logger, "%s has %d channels, need 1 or 2\n", path, info->channels);
} else if (!(data = (float*)malloc(sizeof(float) * info->frames * info->channels))) {
lv2_log_error(logger, "Failed to allocate memory for sample\n");
} else {
error = false;
}
if (error) {
free(sample);
free(data);
if (sndfile) sf_close(sndfile);
return NULL;
}
sf_seek(sndfile, 0ul, SEEK_SET);
sf_readf_float(sndfile, data, info->frames);
sf_close(sndfile);
sample->data = data;
sample->path = (char*)malloc(path_len + 1);
sample->path_len = (uint32_t)path_len;
memcpy(sample->path, path, path_len + 1);
return sample;
}
static void free_sample(LightSampler* self, Sample* sample) {
if (sample) {
lv2_log_trace(&self->logger, "Freeing %s\n", sample->path);
free(sample->path);
free(sample->data);
free(sample);
}
}
static void init_voice(Voice* v) {
v->position = 0.0f;
v->gain = 1.0f;
v->play = false;
v->envelope = 0.0f;
v->envelope_state = 0;
v->attack_rate = 0.0f;
v->hold_frames = 0.0f;
v->decay_rate = 0.0f;
v->sustain_level = 0.75f;
v->release_rate = 0.0f;
v->current_attack_rate = 0.0f;
v->current_hold_frames = 0;
v->current_decay_rate = 0.0f;
v->current_sustain_level = 0.75f;
v->current_release_rate = 0.0f;
v->current_note = 60;
v->velocity_gain = 1.0f;
v->pitch_shift_value = 0.0f;
v->humanize_offset = 0.0f;
v->humanize_volume = 1.0f;
v->hold_counter = 0;
}
static uint8_t get_midi_channel(uint8_t status_byte) {
return status_byte & 0x0F;
}
static int should_process_message(LightSampler* self, uint8_t status_byte) {
if (!self->midi_channel) return 1;
int target_channel_param = (int)*(self->midi_channel);
if (target_channel_param <= 0 || target_channel_param >= 17) return 1;
int target_channel = target_channel_param - 1;
uint8_t msg_channel = get_midi_channel(status_byte);
return (msg_channel == target_channel);
}
/* Update envelope rates once per block */
static void update_envelope_rates(LightSampler* self) {
const float MIN_TIME_SEC = 0.000001f;
float attack_time = self->attack ? *(self->attack) * 0.001f : 0.0f;
if (attack_time > 0.0f && attack_time < MIN_TIME_SEC) attack_time = MIN_TIME_SEC;
float attack_rate = (attack_time > 0.0f) ? (1.0f / (attack_time * self->host_rate)) : 1.0f;
if (attack_rate > 1.0f) attack_rate = 1.0f;
float hold_time = self->hold ? *(self->hold) * 0.001f : 0.0f;
uint32_t hold_frames = (uint32_t)(hold_time * self->host_rate);
float decay_time = 0.0f;
if (self->decay) {
decay_time = *(self->decay) * 0.001f;
if (decay_time > 0.0f && decay_time < MIN_TIME_SEC) decay_time = MIN_TIME_SEC;
}
float decay_rate = (decay_time > 0.0f) ? (1.0f / (decay_time * self->host_rate)) : 1.0f;
if (decay_rate > 1.0f) decay_rate = 1.0f;
float sustain_level = 0.75f;
if (self->sustain) {
float sustain_percent = *(self->sustain);
if (sustain_percent < 0.0f) sustain_percent = 0.0f;
if (sustain_percent > 100.0f) sustain_percent = 100.0f;
sustain_level = sustain_percent / 100.0f;
}
float release_time = self->release ? *(self->release) * 0.001f : 0.0f;
if (release_time > 0.0f && release_time < MIN_TIME_SEC) release_time = MIN_TIME_SEC;
float release_rate = (release_time > 0.0f) ? (1.0f / (release_time * self->host_rate)) : 1.0f;
if (release_rate > 1.0f) release_rate = 1.0f;
self->voice0.attack_rate = attack_rate;
self->voice0.hold_frames = hold_frames;
self->voice0.decay_rate = decay_rate;
self->voice0.sustain_level = sustain_level;
self->voice0.release_rate = release_rate;
self->voice1.attack_rate = attack_rate;
self->voice1.hold_frames = hold_frames;
self->voice1.decay_rate = decay_rate;
self->voice1.sustain_level = sustain_level;
self->voice1.release_rate = release_rate;
}
static inline uint32_t xorshift32(uint32_t* state) {
uint32_t x = *state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
*state = x;
return x;
}
static inline float xorshift_float_range(uint32_t* state, float min, float max) {
uint32_t r = xorshift32(state);
float t = (float)r / 4294967295.0f;
return min + t * (max - min);
}
static float linear_interpolate(float y1, float y2, float frac) {
return y1 + frac * (y2 - y1);
}
/* Worker functions */
static LV2_Worker_Status work(LV2_Handle instance,
LV2_Worker_Respond_Function respond,
LV2_Worker_Respond_Handle handle,
uint32_t size, const void* data) {
LightSampler* self = (LightSampler*)instance;
const LV2_Atom* atom = (const LV2_Atom*)data;
if (atom->type == self->uris.ls_freeSample) {
const SampleMessage* msg = (const SampleMessage*)data;
free_sample(self, msg->sample);
} else if (atom->type == self->forge.Object) {
const LV2_Atom_Object* obj = (const LV2_Atom_Object*)data;
const char* path = read_set_file(&self->uris, obj);
if (!path) {
lv2_log_error(&self->logger, "Malformed set file request\n");
return LV2_WORKER_ERR_UNKNOWN;
}
Sample* sample = load_sample(&self->logger, path);
if (sample) {
respond(handle, sizeof(Sample*), &sample);
}
}
return LV2_WORKER_SUCCESS;
}
static LV2_Worker_Status work_response(LV2_Handle instance, uint32_t size, const void* data) {
LightSampler* self = (LightSampler*)instance;
Sample* old_sample = self->sample;
Sample* new_sample = *(Sample* const*)data;
if (!new_sample) return LV2_WORKER_SUCCESS;
if (new_sample == old_sample) {
return LV2_WORKER_SUCCESS;
}
self->sample = new_sample;
init_voice(&self->voice0);
init_voice(&self->voice1);
self->sample_changed = true;
if (new_sample->info.samplerate > 0) {
self->sample_rate_ratio = (float)self->host_rate / (float)new_sample->info.samplerate;
}
if (self->notify_port && self->notify_port->atom.size >= 256) {
lv2_atom_forge_set_buffer(&self->forge, (uint8_t*)self->notify_port, self->notify_port->atom.size);
LV2_Atom_Forge_Frame frame;
lv2_atom_forge_sequence_head(&self->forge, &frame, 0);
lv2_atom_forge_frame_time(&self->forge, 0);
write_set_file(&self->forge, &self->uris, new_sample->path, new_sample->path_len);
}
self->voice0.play = false;
self->voice0.envelope_state = 0;
self->voice1.play = false;
self->voice1.envelope_state = 0;
if (old_sample) {
SampleMessage msg = {{sizeof(Sample*), self->uris.ls_freeSample}, old_sample};
if (self->schedule) {
self->schedule->schedule_work(self->schedule->handle, sizeof(msg), &msg);
} else {
free_sample(self, old_sample);
}
}
return LV2_WORKER_SUCCESS;
}
static void start_voice(LightSampler* self, Voice* v, uint8_t note, uint8_t vel) {
if (!self->sample || !self->sample->data) return;
if (v->play) {
v->envelope_state = 4;
}
v->position = 0.0f;
v->play = true;
v->current_note = note;
v->envelope = 0.0f;
v->envelope_state = 1;
v->hold_counter = 0;
if (v->attack_rate >= 1.0f) {
v->envelope = 1.0f;
if (v->hold_frames > 0) {
v->envelope_state = 2;
v->hold_counter = v->hold_frames;
} else {
v->envelope_state = 3;
}
}
if (*(self->play_backward) > 0.5f) {
v->position = (float)(self->sample->info.frames - 1);
}
v->pitch_shift_value = *(self->pitch_shift);
if (*(self->humanize) > 0.5f) {
v->humanize_offset = xorshift_float_range(&self->random_state, -0.2f, 0.2f);
v->humanize_volume = xorshift_float_range(&self->random_state, 0.94f, 1.06f);
} else {
v->humanize_offset = 0.0f;
v->humanize_volume = 1.0f;
}
float total_pitch = v->pitch_shift_value + v->humanize_offset;
v->gain = exp2f(total_pitch / 12.0f) * self->sample_rate_ratio;
if (*(self->play_backward) > 0.5f) {
v->gain = -fabsf(v->gain);
}
v->velocity_gain = (float)vel / 127.0f;
v->current_attack_rate = v->attack_rate;
v->current_hold_frames = v->hold_frames;
v->current_decay_rate = v->decay_rate;
v->current_sustain_level = v->sustain_level;
v->current_release_rate = v->release_rate;
}
static void stop_voice(Voice* v, uint8_t note) {
if (note == v->current_note && (v->envelope_state == 1 || v->envelope_state == 2 || v->envelope_state == 3)) {
v->envelope_state = 4;
}
}
static void handle_event(LightSampler* self, LV2_Atom_Event* ev) {
if (!self) return;
if (ev->body.type == self->uris.midi_Event) {
const uint8_t* const msg = (const uint8_t*)(ev + 1);
const uint8_t status = msg[0] & 0xF0;
const uint8_t note = msg[1];
const uint8_t vel = msg[2];
if (!should_process_message(self, msg[0])) {
return;
}
if (status == LV2_MIDI_MSG_NOTE_ON && vel > 0) {
int target_note = (int)*(self->midi_note);
if (target_note < 0) target_note = 0;
if (target_note > 127) target_note = 127;
if (note != target_note) {
return;
}
if (ev->time.frames == self->last_note_frame && note == self->last_note) {
return;
}
self->last_note = note;
self->last_note_frame = ev->time.frames;
bool dual_mode = self->voice_mode && (*(self->voice_mode) > 0.5f);
if (dual_mode) {
int voice_to_use = 0;
if (!self->voice0.play && self->voice1.play) {
voice_to_use = 0;
} else if (self->voice0.play && !self->voice1.play) {
voice_to_use = 1;
} else if (!self->voice0.play && !self->voice1.play) {
voice_to_use = 0;
} else {
if (self->voice0.envelope_state == 3 && self->voice1.envelope_state != 3) {
voice_to_use = 0;
} else if (self->voice1.envelope_state == 3 && self->voice0.envelope_state != 3) {
voice_to_use = 1;
} else {
voice_to_use = (self->voice0.envelope <= self->voice1.envelope) ? 0 : 1;
}
}
if (voice_to_use == 0) {
start_voice(self, &self->voice0, note, vel);
} else {
start_voice(self, &self->voice1, note, vel);
}
} else {
start_voice(self, &self->voice0, note, vel);
if (self->voice1.play) {
self->voice1.envelope_state = 3;
}
}
} else if (status == LV2_MIDI_MSG_NOTE_OFF || (status == LV2_MIDI_MSG_NOTE_ON && vel == 0)) {
int target_note = (int)*(self->midi_note);
if (target_note < 0) target_note = 0;
if (target_note > 127) target_note = 127;
if (note == target_note) {
stop_voice(&self->voice0, note);
stop_voice(&self->voice1, note);
}
}
} else if (lv2_atom_forge_is_object_type(&self->forge, ev->body.type)) {
const LV2_Atom_Object* obj = (const LV2_Atom_Object*)&ev->body;
if (obj->body.otype == self->uris.patch_Set) {
const LV2_Atom* property = NULL;
const LV2_Atom* value = NULL;
lv2_atom_object_get(obj, self->uris.patch_property, &property,
self->uris.patch_value, &value, 0);
if (!property || property->type != self->uris.atom_URID) {
return;
}
const uint32_t key = ((const LV2_Atom_URID*)property)->body;
if (key == self->uris.ls_sample) {
if (self->schedule) {
self->schedule->schedule_work(self->schedule->handle,
lv2_atom_total_size(&ev->body), &ev->body);
}
}
}
}
}
static void render_voice(LightSampler* self, Voice* v, uint32_t start, uint32_t end,
float* out_l, float* out_r, bool stereo_mode, float volume) {
/* Fast path for inactive voices */
if (!v->play && v->envelope_state == 0) {
v->envelope = 0.0f;
return;
}
/* These checks now only happen for active voices */
if (!self->sample || !self->sample->data || self->sample->info.frames == 0) return;
uint32_t total_frames = self->sample->info.frames;
uint32_t channels = self->sample->info.channels;
uint32_t block_frames = end - start;
float final_volume = volume * v->humanize_volume * v->velocity_gain;
float envelope = v->envelope;
/* Calculate envelope once per block */
if (v->envelope_state != 0) {
if (v->envelope_state == 1) { /* Attack */
float attack_factor = powf(1.0f - v->current_attack_rate, (float)block_frames);
float target = 1.0f;
envelope = target - (target - envelope) * attack_factor;
if (envelope >= 0.999f) {
envelope = 1.0f;
if (v->current_hold_frames > 0) {
v->envelope_state = 2; /* Hold */
v->hold_counter = v->current_hold_frames;
} else {
v->envelope_state = 3; /* Decay */
}
}
}
else if (v->envelope_state == 2) { /* Hold */
if (v->hold_counter > block_frames) {
v->hold_counter -= block_frames;
} else {
v->envelope_state = 3; /* Decay */
v->hold_counter = 0;
}
}
else if (v->envelope_state == 3) { /* Decay */
float decay_factor = powf(1.0f - v->current_decay_rate, (float)block_frames);
envelope = v->current_sustain_level + (envelope - v->current_sustain_level) * decay_factor;
if (envelope <= v->current_sustain_level + 0.001f) {
envelope = v->current_sustain_level;
}
}
else if (v->envelope_state == 4) { /* Release */
float release_factor = powf(1.0f - v->current_release_rate, (float)block_frames);
envelope = envelope * release_factor;
if (envelope < 0.001f) {
envelope = 0.0f;
v->play = false;
v->envelope_state = 0;
v->envelope = 0.0f;
return;
}
}
v->envelope = envelope;
}
float final_gain = envelope * final_volume;
/* Sample processing loop */
for (uint32_t i = start; i < end; i++) {
if (v->gain > 0 && v->position >= total_frames) {
v->position = (float)(total_frames - 1);
if (v->envelope_state != 4) {
v->envelope_state = 4;
v->play = false;
}
}
if (v->gain < 0 && v->position < 0.0f) {
v->position = 0.0f;
if (v->envelope_state != 4) {
v->envelope_state = 4;
v->play = false;
}
}
float sample_l = 0.0f;
float sample_r = 0.0f;
if (channels == 1) {
uint32_t pos0 = (uint32_t)v->position;
uint32_t pos1 = pos0 + 1;
if (pos1 >= total_frames) pos1 = pos0;
float frac = v->position - (float)pos0;
float s0 = self->sample->data[pos0];
float s1 = self->sample->data[pos1];
sample_l = linear_interpolate(s0, s1, frac);
sample_r = sample_l;
} else if (channels == 2) {
uint32_t pos0 = (uint32_t)v->position;
uint32_t pos1 = pos0 + 1;
if (pos1 >= total_frames) pos1 = pos0;
float frac = v->position - (float)pos0;
uint32_t idx0 = pos0 * 2;
uint32_t idx1 = pos1 * 2;
float left = linear_interpolate(self->sample->data[idx0], self->sample->data[idx1], frac);
float right = linear_interpolate(self->sample->data[idx0 + 1], self->sample->data[idx1 + 1], frac);
if (stereo_mode) {
sample_l = left;
sample_r = right;
} else {
float mono = (left + right) * 0.5f;
sample_l = mono;
sample_r = mono;
}
}
out_l[i] += sample_l * final_gain;
out_r[i] += sample_r * final_gain;
v->position += v->gain;
}
if (v->gain > 0 && v->position >= total_frames && v->envelope_state != 4) {
v->envelope_state = 4;
} else if (v->gain < 0 && v->position < 0 && v->envelope_state != 4) {
v->envelope_state = 4;
}
}
static void render(LightSampler* self, uint32_t start, uint32_t end) {
if (!self || !self->output_port_l || !self->output_port_r || start >= end) return;
bool stereo_mode = self->stereo && (*(self->stereo) > 0.5f);
bool dual_mode = self->voice_mode && (*(self->voice_mode) > 0.5f);
float volume = 1.0f;
if (self->volume) {
volume = *self->volume / 100.0f;
volume = volume * volume;
}
memset(&self->output_port_l[start], 0, (end - start) * sizeof(float));
memset(&self->output_port_r[start], 0, (end - start) * sizeof(float));
render_voice(self, &self->voice0, start, end,
self->output_port_l, self->output_port_r, stereo_mode, volume);
if (dual_mode) {
render_voice(self, &self->voice1, start, end,
self->output_port_l, self->output_port_r, stereo_mode, volume);
}
}
static LV2_Handle instantiate(const LV2_Descriptor* descriptor,
double rate, const char* bundle_path,
const LV2_Feature* const* features) {
LightSampler* self = (LightSampler*)calloc(1, sizeof(LightSampler));
if (!self) return NULL;
self->map = NULL;
self->schedule = NULL;
self->logger.log = NULL;
self->sample = NULL;
for (int i = 0; features[i]; ++i) {
const char* uri = features[i]->URI;
if (!strcmp(uri, LV2_URID__map)) {
self->map = (LV2_URID_Map*)features[i]->data;
}
else if (!strcmp(uri, LV2_WORKER__schedule)) {
self->schedule = (LV2_Worker_Schedule*)features[i]->data;
}
else if (!strcmp(uri, LV2_LOG__log)) {
self->logger.log = (LV2_Log_Log*)features[i]->data;
}
}
if (!self->map) {
free(self);
return NULL;
}
if (self->logger.log) {
lv2_log_logger_set_map(&self->logger, self->map);
lv2_log_note(&self->logger, "Light Sampler instantiated\n");
}
map_light_sampler_uris(self->map, &self->uris);
lv2_atom_forge_init(&self->forge, self->map);
peaks_sender_init(&self->peaks_sender, self->map);
self->host_rate = (uint32_t)rate;
self->global_gain = 1.0f;
self->random_state = (uint32_t)((uintptr_t)self ^ (uint32_t)rate);
if (self->random_state == 0) self->random_state = 123456789;
self->sample = NULL;
self->sample_rate_ratio = 1.0f;
init_voice(&self->voice0);
init_voice(&self->voice1);
self->last_note = 0;
self->last_note_frame = 0;
self->control_port = NULL;
self->notify_port = NULL;
self->output_port_l = NULL;
self->output_port_r = NULL;
self->midi_channel = NULL;
self->midi_note = NULL;
self->play_backward = NULL;
self->humanize = NULL;
self->pitch_shift = NULL;
self->voice_mode = NULL;
self->attack = NULL;
self->hold = NULL;
self->decay = NULL;
self->sustain = NULL;
self->release = NULL;
self->volume = NULL;
self->stereo = NULL;
self->activated = false;
self->gain_changed = false;
self->sample_changed = false;
self->frame_offset = 0;
self->active_voice_count = 0;
return (LV2_Handle)self;
}
static void connect_port(LV2_Handle instance, uint32_t port, void* data) {
LightSampler* self = (LightSampler*)instance;
switch ((PortIndex)port) {
case CONTROL_IN: self->control_port = (const LV2_Atom_Sequence*)data; break;
case NOTIFY_OUT: self->notify_port = (LV2_Atom_Sequence*)data; break;
case AUDIO_OUT_L: self->output_port_l = (float*)data; break;
case AUDIO_OUT_R: self->output_port_r = (float*)data; break;
case PLAY_BACKWARD:self->play_backward = (const float*)data; break;
case HUMANIZE: self->humanize = (const float*)data; break;
case STEREO: self->stereo = (const float*)data; break;
case MIDI_CHANNEL: self->midi_channel = (const float*)data; break;
case MIDI_NOTE: self->midi_note = (const float*)data; break;
case PITCH_SHIFT: self->pitch_shift = (const float*)data; break;
case VOICE_MODE: self->voice_mode = (const float*)data; break;
case ATTACK: self->attack = (const float*)data; break;
case HOLD: self->hold = (const float*)data; break;
case DECAY: self->decay = (const float*)data; break;
case SUSTAIN: self->sustain = (const float*)data; break;
case RELEASE: self->release = (const float*)data; break;
case VOLUME: self->volume = (const float*)data; break;
}
}
static void activate(LV2_Handle instance) {
LightSampler* self = (LightSampler*)instance;
self->activated = true;
update_envelope_rates(self);
// Force clean voice state on activation
init_voice(&self->voice0);
init_voice(&self->voice1);
self->voice0.play = false;
self->voice0.envelope_state = 0;
self->voice1.play = false;
self->voice1.envelope_state = 0;
}
static void run(LV2_Handle instance, uint32_t sample_count) {
LightSampler* self = (LightSampler*)instance;
if (!self || !self->output_port_l || !self->output_port_r) {
return;
}
update_envelope_rates(self);
if (self->control_port) {
if (self->control_port->atom.size <= sizeof(LV2_Atom_Sequence_Body)) {
render(self, 0, sample_count);
return;
}
if (self->notify_port && self->notify_port->atom.size >= 256) {
lv2_atom_forge_set_buffer(&self->forge,
(uint8_t*)self->notify_port,
self->notify_port->atom.size);
LV2_Atom_Forge_Frame notify_frame;
lv2_atom_forge_sequence_head(&self->forge, ¬ify_frame, 0);
if (self->gain_changed || self->sample_changed) {
lv2_atom_forge_frame_time(&self->forge, 0);
if (self->gain_changed) {
write_set_gain(&self->forge, &self->uris, 0.0f);
self->gain_changed = false;
}
if (self->sample_changed && self->sample) {
write_set_file(&self->forge, &self->uris,
self->sample->path, self->sample->path_len);
self->sample_changed = false;
}
}
}
if (self->sample_changed) {
// Sample just loaded, ensure voices are clean
self->voice0.play = false;
self->voice0.envelope_state = 0;
self->voice1.play = false;
self->voice1.envelope_state = 0;
self->sample_changed = false;
}
self->frame_offset = 0;
uint32_t event_count = 0;
self->last_note_frame = UINT64_MAX;
LV2_ATOM_SEQUENCE_FOREACH(self->control_port, ev) {
event_count++;
self->frame_offset = ev->time.frames;
handle_event(self, ev);
}
if (event_count == 0) {
if (self->frame_offset == 0) {
render(self, 0, sample_count);
} else {
if (self->frame_offset > 0) {
uint32_t zero_frames = (uint32_t)self->frame_offset;
if (zero_frames > sample_count) zero_frames = sample_count;
memset(self->output_port_l, 0, zero_frames * sizeof(float));
memset(self->output_port_r, 0, zero_frames * sizeof(float));
}
if ((uint32_t)self->frame_offset < sample_count) {
render(self, (uint32_t)self->frame_offset, sample_count);
}
}
} else {
render(self, 0, sample_count);
}
} else {
memset(self->output_port_l, 0, sample_count * sizeof(float));
memset(self->output_port_r, 0, sample_count * sizeof(float));
}
if (self->notify_port && self->notify_port->atom.size >= 256 &&
self->sample && self->sample->data &&
(self->voice0.play || self->voice1.play)) {
peaks_sender_send(&self->peaks_sender, &self->forge,
sample_count, self->frame_offset);
}
}
static void deactivate(LV2_Handle instance) {
LightSampler* self = (LightSampler*)instance;
self->activated = false;
init_voice(&self->voice0);
init_voice(&self->voice1);
}
static void cleanup(LV2_Handle instance) {
LightSampler* self = (LightSampler*)instance;
free_sample(self, self->sample);
free(self);
}
/* State functions */
static LV2_State_Status save(LV2_Handle instance,
LV2_State_Store_Function store,
LV2_State_Handle handle,
uint32_t flags,
const LV2_Feature* const* features) {
LightSampler* self = (LightSampler*)instance;
if (!self->sample) return LV2_STATE_SUCCESS;
LV2_State_Map_Path* map_path = (LV2_State_Map_Path*)
lv2_features_data(features, LV2_STATE__mapPath);
if (!map_path) return LV2_STATE_ERR_NO_FEATURE;
char* apath = map_path->abstract_path(map_path->handle, self->sample->path);
store(handle, self->uris.ls_sample, apath, strlen(apath) + 1,
self->uris.atom_Path, LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE);
free(apath);
return LV2_STATE_SUCCESS;
}
static LV2_State_Status restore(LV2_Handle instance,
LV2_State_Retrieve_Function retrieve,
LV2_State_Handle handle,
uint32_t flags,
const LV2_Feature* const* features) {
LightSampler* self = (LightSampler*)instance;
LV2_Worker_Schedule* schedule = NULL;
LV2_State_Map_Path* paths = NULL;
const char* missing = lv2_features_query(
features,
LV2_STATE__mapPath, (void**)&paths, true,
LV2_WORKER__schedule, (void**)&schedule, false,
NULL);
if (missing) return LV2_STATE_ERR_NO_FEATURE;
size_t size; uint32_t type, valflags;
const void* value = retrieve(handle, self->uris.ls_sample, &size, &type, &valflags);
if (!value || type != self->uris.atom_Path) return LV2_STATE_ERR_BAD_TYPE;
const char* apath = (const char*)value;
char* path = paths->absolute_path(paths->handle, apath);
// Always use worker if available, never load directly
if (schedule) {
LV2_Atom_Forge forge;
LV2_Atom* buf = (LV2_Atom*)calloc(1, strlen(path) + 128);
lv2_atom_forge_init(&forge, self->map);
lv2_atom_forge_set_sink(&forge, atom_sink, atom_sink_deref, buf);
write_set_file(&forge, &self->uris, path, strlen(path));
const uint32_t msg_size = lv2_atom_pad_size(buf->size);