-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbarelymusician.h
1576 lines (1413 loc) · 51.3 KB
/
barelymusician.h
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
/// ==================
/// barelymusician API
/// ==================
///
/// barelymusician is a real-time music engine for interactive systems.
/// It is used to generate and perform musical sounds from scratch in a sample accurate way.
///
/// -----------------
/// Example C++ Usage
/// -----------------
///
/// - Musician:
///
/// @code{.cpp}
/// #include "barelymusician.h"
///
/// // Create.
/// barely::Musician musician(/*sample_rate=*/48000);
///
/// // Set the tempo.
/// musician.SetTempo(/*tempo=*/124.0);
///
/// // Update the timestamp.
/// //
/// // Timestamp updates must occur before processing instruments with their respective
/// // timestamps. Otherwise, `Process` calls may be *late* in receiving the relevant changes to
/// // the instruments. To address this, `Update` should typically be called from the main thread
/// // update callback using a lookahead to prevent potential thread synchronization issues in
/// // real-time audio applications.
/// double timestamp = 1.0;
/// musician.Update(timestamp);
/// @endcode
///
/// - Instrument:
///
/// @code{.cpp}
/// // Create.
/// auto instrument = musician.CreateInstrument();
///
/// // Set a note on.
/// //
/// // The note pitch is centered around the reference frequency and measured in octaves.
/// // Fractional note values adjust the frequency logarithmically to ensure equally perceived
/// // pitch intervals within each octave.
/// const float c3_pitch = -1.0f;
/// instrument.SetNoteOn(c3_pitch, /*intensity=*/0.25f);
///
/// // Check if the note is on.
/// const bool is_note_on = instrument.IsNoteOn(c3_pitch);
///
/// // Set a control value.
/// instrument.SetControl(barely::ControlType::kGain, /*value=*/-6.0f);
///
/// // Process.
/// //
/// // Instruments process raw PCM audio samples in a synchronous call. Therefore, `Process`
/// // should typically be called from an audio thread process callback in real-time audio
/// // applications.
/// float output_samples[1024];
/// double timestamp = 0.0;
/// instrument.Process(output_samples, timestamp);
/// @endcode
///
/// - Performer:
///
/// @code{.cpp}
/// // Create.
/// auto performer = musician.CreatePerformer();
///
/// // Create a task.
/// auto task = performer.CreateTask(/*position=*/0.0, /*duration=*/1.0,
/// [](barely::TaskState state) { /*populate this*/ });
///
/// // Set to looping.
/// performer.SetLooping(/*is_looping=*/true);
///
/// // Start.
/// performer.Start();
///
/// // Check if started playing.
/// const bool is_playing = performer.IsPlaying();
/// @endcode
///
/// ---------------
/// Example C Usage
/// ---------------
///
/// - Musician:
///
/// @code{.cpp}
/// #include "barelymusician.h"
///
/// // Create.
/// BarelyMusicianHandle musician = nullptr;
/// BarelyMusician_Create(/*sample_rate=*/48000, &musician);
///
/// // Set the tempo.
/// BarelyMusician_SetTempo(musician, /*tempo=*/124.0);
///
/// // Update the timestamp.
/// //
/// // Timestamp updates must occur before processing instruments with their respective
/// // timestamps. Otherwise, `Process` calls may be *late* in receiving the relevant changes to
/// // the instruments. To address this, `Update` should typically be called from the main thread
/// // update callback using a lookahead to prevent potential thread synchronization issues in
/// // real-time audio applications.
/// double timestamp = 1.0;
/// BarelyMusician_Update(musician, timestamp);
///
/// // Destroy.
/// BarelyMusician_Destroy(musician);
/// @endcode
///
/// - Instrument:
///
/// @code{.cpp}
/// // Create.
/// BarelyInstrumentHandle instrument = nullptr;
/// BarelyInstrument_Create(musician, &instrument);
///
/// // Set a note on.
/// //
/// // The note pitch is centered around the reference frequency and measured in octaves.
/// // Fractional note values adjust the frequency logarithmically to ensure equally perceived
/// // pitch intervals within each octave.
/// float c3_pitch = -1.0f;
/// BarelyInstrument_SetNoteOn(instrument, c3_pitch, /*intensity=*/0.25f);
///
/// // Check if the note is on.
/// bool is_note_on = false;
/// BarelyInstrument_IsNoteOn(instrument, c3_pitch, &is_note_on);
///
/// // Set a control value.
/// BarelyInstrument_SetControl(instrument, BarelyControlType_kGain, /*value=*/-6.0f);
///
/// // Process.
/// //
/// // Instruments process raw PCM audio samples in a synchronous call. Therefore, `Process`
/// // should typically be called from an audio thread process callback in real-time audio
/// // applications.
/// float output_samples[1024];
/// double timestamp = 0.0;
/// BarelyInstrument_Process(instrument, output_samples, /*output_sample_count=*/1024, timestamp);
///
/// // Destroy.
/// BarelyInstrument_Destroy(instrument);
/// @endcode
///
/// - Performer:
///
/// @code{.cpp}
/// // Create.
/// BarelyPerformerHandle performer = nullptr;
/// BarelyPerformer_Create(musician, &performer);
///
/// // Create a task.
/// BarelyTaskHandle task = nullptr;
/// BarelyTask_ProcessCallback process_callback{ /*populate this*/ };
/// BarelyTask_Create(performer, /*position=*/0.0, /*duration=*/1.0, process_callback, &task);
///
/// // Set to looping.
/// BarelyPerformer_SetLooping(performer, /*is_looping=*/true);
///
/// // Start.
/// BarelyPerformer_Start(performer);
///
/// // Check if started playing.
/// bool is_playing = false;
/// BarelyPerformer_IsPlaying(performer, &is_playing);
///
/// // Destroy the task.
/// BarelyTask_Destroy(task);
///
/// // Destroy.
/// BarelyPerformer_Destroy(performer);
/// @endcode
#ifndef BARELYMUSICIAN_BARELYMUSICIAN_H_
#define BARELYMUSICIAN_BARELYMUSICIAN_H_
// NOLINTBEGIN
#include <stdbool.h>
#include <stdint.h>
#if defined(_WIN32) || defined(__CYGWIN__)
#ifdef BARELYMUSICIAN_EXPORTS
#ifdef __GNUC__
#define BARELY_EXPORT __attribute__((dllexport))
#else // __GNUC__
#define BARELY_EXPORT __declspec(dllexport)
#endif // __GNUC__
#else // BARELYMUSICIAN_EXPORTS
#ifdef __GNUC__
#define BARELY_EXPORT __attribute__((dllimport))
#else // __GNUC__
#define BARELY_EXPORT __declspec(dllimport)
#endif // __GNUC__
#endif // BARELYMUSICIAN_EXPORTS
#else // defined(_WIN32) || defined(__CYGWIN__)
#if __GNUC__ >= 4
#define BARELY_EXPORT __attribute__((visibility("default")))
#else // __GNUC__ >= 4
#define BARELY_EXPORT
#endif // __GNUC__ >= 4
#endif // defined(_WIN32) || defined(__CYGWIN__)
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/// Control type enum.
typedef enum BarelyControlType {
/// Gain in decibels.
BarelyControlType_kGain = 0,
/// Pitch shift.
BarelyControlType_kPitchShift,
/// Retrigger.
BarelyControlType_kRetrigger,
/// Number of voices.
BarelyControlType_kVoiceCount,
/// Envelope attack in seconds.
BarelyControlType_kAttack,
/// Envelope decay in seconds.
BarelyControlType_kDecay,
/// Envelope sustain.
BarelyControlType_kSustain,
/// Envelope release in seconds.
BarelyControlType_kRelease,
/// Oscillator mix.
BarelyControlType_kOscillatorMix,
/// Oscillator mode.
BarelyControlType_kOscillatorMode,
/// Oscillator pitch shift.
BarelyControlType_kOscillatorPitchShift,
/// Oscillator shape.
BarelyControlType_kOscillatorShape,
/// Pulse width.
BarelyControlType_kPulseWidth,
/// Sample playback mode.
BarelyControlType_kSamplePlaybackMode,
/// Filter type.
BarelyControlType_kFilterType,
/// Filter frequency in hertz.
BarelyControlType_kFilterFrequency,
/// Number of control types.
BarelyControlType_kCount,
} BarelyControlType;
/// Filter type enum.
typedef enum BarelyFilterType {
/// None.
BarelyFilterType_kNone = 0,
/// Low pass.
BarelyFilterType_kLowPass,
/// High pass.
BarelyFilterType_kHighPass,
/// Number of filters.
BarelyFilterType_kCount,
} BarelyFilterType;
/// Note control type enum.
typedef enum BarelyNoteControlType {
/// Pitch shift.
BarelyNoteControlType_kPitchShift = 0,
/// Number of note control types.
BarelyNoteControlType_kCount,
} BarelyNoteControlType;
/// Oscillator mode enum.
typedef enum BarelyOscillatorMode {
/// Mix.
BarelyOscillatorMode_kMix = 0,
/// Amplitude modulation.
BarelyOscillatorMode_kAm,
/// Envelope follower.
BarelyOscillatorMode_kEnvelopeFollower,
// TODO(#146): Add FM support once voice pitch calculation is cleaned up.
// /// Frequency modulation.
// BarelyOscillatorMode_kFm,
/// Ring modulation.
BarelyOscillatorMode_kRing,
/// Number of oscillator modes.
BarelyOscillatorMode_kCount,
} BarelyOscillatorMode;
/// Oscillator shape enum.
typedef enum BarelyOscillatorShape {
/// None.
BarelyOscillatorShape_kNone = 0,
/// Sine wave.
BarelyOscillatorShape_kSine,
/// Sawtooth wave.
BarelyOscillatorShape_kSaw,
/// Square wave.
BarelyOscillatorShape_kSquare,
/// White noise.
BarelyOscillatorShape_kNoise,
/// Number of oscillator shapes.
BarelyOscillatorShape_kCount,
} BarelyOscillatorShape;
/// Sample playback mode enum.
typedef enum BarelySamplePlaybackMode {
/// None.
BarelySamplePlaybackMode_kNone = 0,
/// Once.
BarelySamplePlaybackMode_kOnce,
/// Sustain.
BarelySamplePlaybackMode_kSustain,
/// Loop.
BarelySamplePlaybackMode_kLoop,
/// Number of playback modes.
BarelySamplePlaybackMode_kCount,
} BarelySamplePlaybackMode;
/// Task state enum.
typedef enum BarelyTaskState {
/// Begin.
BarelyTaskState_kBegin = 0,
/// End.
BarelyTaskState_kEnd,
/// Update.
BarelyTaskState_kUpdate,
/// Number of task states.
BarelyTaskState_kCount,
} BarelyTaskState;
/// Slice of sample data.
typedef struct BarelySampleDataSlice {
/// Root note pitch.
float root_pitch;
/// Sampling rate in hertz.
int32_t sample_rate;
/// Array of mono samples.
const float* samples;
/// Number of mono samples.
int32_t sample_count;
} BarelySampleDataSlice;
/// Instrument handle.
typedef struct BarelyInstrument* BarelyInstrumentHandle;
/// Musician handle.
typedef struct BarelyMusician* BarelyMusicianHandle;
/// Performer handle.
typedef struct BarelyPerformer* BarelyPerformerHandle;
/// Task handle.
typedef struct BarelyTask* BarelyTaskHandle;
/// Instrument note off callback.
///
/// @param pitch Note pitch.
/// @param user_data Pointer to user data.
typedef void (*BarelyInstrument_NoteOffCallback)(float pitch, void* user_data);
/// Instrument note on callback.
///
/// @param pitch Note pitch.
/// @param intensity Note intensity.
/// @param user_data Pointer to user data.
typedef void (*BarelyInstrument_NoteOnCallback)(float pitch, float intensity, void* user_data);
/// Performer beat callback.
///
/// @param user_data Pointer to user data.
typedef void (*BarelyPerformer_BeatCallback)(void* user_data);
/// Task process callback.
///
/// @param state Task state.
/// @param user_data Pointer to user data.
typedef void (*BarelyTask_ProcessCallback)(BarelyTaskState state, void* user_data);
/// Creates a new instrument.
///
/// @param musician Musician handle.
/// @param out_instrument Output instrument handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_Create(BarelyMusicianHandle musician,
BarelyInstrumentHandle* out_instrument);
/// Destroys an instrument.
///
/// @param instrument Instrument handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_Destroy(BarelyInstrumentHandle instrument);
/// Gets an instrument control value.
///
/// @param instrument Instrument handle.
/// @param type Control type.
/// @param out_value Output control value.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_GetControl(BarelyInstrumentHandle instrument,
BarelyControlType type, float* out_value);
/// Gets an instrument note control value.
///
/// @param instrument Instrument handle.
/// @param pitch Note pitch.
/// @param type Note control type.
/// @param out_value Output note control value.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_GetNoteControl(BarelyInstrumentHandle instrument, float pitch,
BarelyNoteControlType type, float* out_value);
/// Gets whether an instrument note is on or not.
///
/// @param instrument Instrument handle.
/// @param pitch Note pitch.
/// @param out_is_note_on Output true if on, false otherwise.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_IsNoteOn(BarelyInstrumentHandle instrument, float pitch,
bool* out_is_note_on);
/// Processes instrument output samples at timestamp.
/// @note This is *not* thread-safe during a corresponding `BarelyInstrument_Destroy` call.
///
/// @param instrument Instrument handle.
/// @param output_samples Array of mono output samples.
/// @param output_sample_count Number of output samples.
/// @param timestamp Timestamp in seconds.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_Process(BarelyInstrumentHandle instrument,
float* output_samples, int32_t output_sample_count,
double timestamp);
/// Sets all instrument notes off.
///
/// @param instrument Instrument handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetAllNotesOff(BarelyInstrumentHandle instrument);
/// Sets an instrument control value.
///
/// @param instrument Instrument handle.
/// @param type Control type.
/// @param value Control value.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetControl(BarelyInstrumentHandle instrument,
BarelyControlType type, float value);
/// Sets an instrument note control value.
///
/// @param instrument Instrument handle.
/// @param pitch Note pitch.
/// @param type Note control type.
/// @param value Note control value.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetNoteControl(BarelyInstrumentHandle instrument, float pitch,
BarelyNoteControlType type, float value);
/// Sets an instrument note off.
///
/// @param instrument Instrument handle.
/// @param pitch Note pitch.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetNoteOff(BarelyInstrumentHandle instrument, float pitch);
/// Sets the note off callback of an instrument.
///
/// @param instrument Instrument handle.
/// @param callback Note off callback.
/// @param user_data Pointer to user data.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetNoteOffCallback(BarelyInstrumentHandle instrument,
BarelyInstrument_NoteOffCallback callback,
void* user_data);
/// Sets an instrument note on.
///
/// @param instrument Instrument handle.
/// @param pitch Note pitch.
/// @param intensity Note intensity.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetNoteOn(BarelyInstrumentHandle instrument, float pitch,
float intensity);
/// Sets the note on callback of an instrument.
///
/// @param instrument Instrument handle.
/// @param callback Note on callback.
/// @param user_data Pointer to user data.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetNoteOnCallback(BarelyInstrumentHandle instrument,
BarelyInstrument_NoteOnCallback callback,
void* user_data);
/// Sets instrument sample data.
///
/// @param instrument Instrument handle.
/// @param slices Array of sample data slices.
/// @param sample_data_count Number of sample data slices.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyInstrument_SetSampleData(BarelyInstrumentHandle instrument,
const BarelySampleDataSlice* slices,
int32_t slice_count);
/// Creates a new musician.
///
/// @param sample_rate Sampling rate in hertz.
/// @param out_musician Output musician handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_Create(int32_t sample_rate, BarelyMusicianHandle* out_musician);
/// Destroys a musician.
///
/// @param musician Musician handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_Destroy(BarelyMusicianHandle musician);
/// Gets the reference frequency of a musician.
///
/// @param musician Musician handle.
/// @param out_reference_frequency Output reference frequency in hertz.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_GetReferenceFrequency(BarelyMusicianHandle musician,
float* out_reference_frequency);
/// Gets the tempo of a musician.
///
/// @param musician Musician handle.
/// @param out_tempo Output tempo in beats per minute.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_GetTempo(BarelyMusicianHandle musician, double* out_tempo);
/// Gets the timestamp of a musician.
///
/// @param musician Musician handle.
/// @param out_timestamp Output timestamp in seconds.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_GetTimestamp(BarelyMusicianHandle musician,
double* out_timestamp);
/// Sets the reference frequency of a musician.
///
/// @param musician Musician handle.
/// @param reference_frequency Reference frequency in hertz.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_SetReferenceFrequency(BarelyMusicianHandle musician,
float reference_frequency);
/// Sets the tempo of a musician.
///
/// @param musician Musician handle.
/// @param tempo Tempo in beats per minute.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_SetTempo(BarelyMusicianHandle musician, double tempo);
/// Updates a musician at timestamp.
///
/// @param musician Musician handle.
/// @param timestamp Timestamp in seconds.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyMusician_Update(BarelyMusicianHandle musician, double timestamp);
/// Creates a performer.
///
/// @param musician Musician handle.
/// @param out_performer Output performer handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_Create(BarelyMusicianHandle musician,
BarelyPerformerHandle* out_performer);
/// Destroys a performer.
///
/// @param performer Performer handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_Destroy(BarelyPerformerHandle performer);
/// Gets the loop begin position of a performer.
///
/// @param performer Performer handle.
/// @param out_loop_begin_position Output loop begin position in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_GetLoopBeginPosition(BarelyPerformerHandle performer,
double* out_loop_begin_position);
/// Gets the loop length of a performer.
///
/// @param performer Performer handle.
/// @param out_loop_length Output loop length.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_GetLoopLength(BarelyPerformerHandle performer,
double* out_loop_length);
/// Gets the position of a performer.
///
/// @param performer Performer handle.
/// @param out_position Output position in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_GetPosition(BarelyPerformerHandle performer,
double* out_position);
/// Gets whether a performer is looping or not.
///
/// @param performer Performer handle.
/// @param out_is_looping Output true if looping, false otherwise.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_IsLooping(BarelyPerformerHandle performer, bool* out_is_looping);
/// Gets whether a performer is playing or not.
///
/// @param performer Performer handle.
/// @param out_is_playing Output true if playing, false otherwise.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_IsPlaying(BarelyPerformerHandle performer, bool* out_is_playing);
/// Sets the beat callback of a performer.
///
/// @param performer Performer handle.
/// @param callback Beat callback.
/// @param user_data Pointer to user data.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_SetBeatCallback(BarelyPerformerHandle performer,
BarelyPerformer_BeatCallback callback,
void* user_data);
/// Sets the loop begin position of a performer.
///
/// @param performer Performer handle.
/// @param loop_begin_position Loop begin position in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_SetLoopBeginPosition(BarelyPerformerHandle performer,
double loop_begin_position);
/// Sets the loop length of a performer.
///
/// @param performer Performer handle.
/// @param loop_length Loop length in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_SetLoopLength(BarelyPerformerHandle performer,
double loop_length);
/// Sets whether a performer is looping or not.
///
/// @param performer Performer handle.
/// @param is_looping True if looping, false otherwise.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_SetLooping(BarelyPerformerHandle performer, bool is_looping);
/// Sets the position of a performer.
///
/// @param performer Performer handle.
/// @param position Position in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_SetPosition(BarelyPerformerHandle performer, double position);
/// Starts a performer.
///
/// @param performer Performer handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_Start(BarelyPerformerHandle performer);
/// Stops a performer.
///
/// @param performer Performer handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyPerformer_Stop(BarelyPerformerHandle performer);
/// Creates a new task.
///
/// @param performer Performer handle.
/// @param position Task position in beats.
/// @param duration Task duration in beats.
/// @param callback Task process callback.
/// @param user_data Pointer to user data.
/// @param out_task Output task handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_Create(BarelyPerformerHandle performer, double position,
double duration, BarelyTask_ProcessCallback callback,
void* user_data, BarelyTaskHandle* out_task);
/// Destroys a task.
///
/// @param task Task handle.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_Destroy(BarelyTaskHandle task);
/// Gets the duration of a task.
///
/// @param task Task handle.
/// @param out_duration Output duration in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_GetDuration(BarelyTaskHandle task, double* out_duration);
/// Gets the position of a task.
///
/// @param task Task handle.
/// @param out_position Output position in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_GetPosition(BarelyTaskHandle task, double* out_position);
/// Gets whether the task is active or not.
///
/// @param task Task handle.
/// @param out_is_active Output true if active, false otherwise.
BARELY_EXPORT bool BarelyTask_IsActive(BarelyTaskHandle task, bool* out_is_active);
/// Sets the duration of a task.
///
/// @param task Task handle.
/// @param position Duration in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_SetDuration(BarelyTaskHandle task, double duration);
/// Sets the position of a task.
///
/// @param task Task handle.
/// @param position Position in beats.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_SetPosition(BarelyTaskHandle task, double position);
/// Sets the process callback of a task.
///
/// @param task Task handle.
/// @param callback Process callback.
/// @param user_data Pointer to user data.
/// @return True if successful, false otherwise.
BARELY_EXPORT bool BarelyTask_SetProcessCallback(BarelyTaskHandle task,
BarelyTask_ProcessCallback callback,
void* user_data);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
// NOLINTEND
#ifdef __cplusplus
#include <cassert>
#include <cstdint>
#include <functional>
#include <span>
#include <type_traits>
#include <utility>
namespace barely {
/// Control type enum.
enum class ControlType {
/// Gain in decibels.
kGain = BarelyControlType_kGain,
/// Pitch shift.
kPitchShift = BarelyControlType_kPitchShift,
/// Retrigger.
kRetrigger = BarelyControlType_kRetrigger,
/// Number of voices.
kVoiceCount = BarelyControlType_kVoiceCount,
/// Envelope attack in seconds.
kAttack = BarelyControlType_kAttack,
/// Envelope decay in seconds.
kDecay = BarelyControlType_kDecay,
/// Envelope sustain.
kSustain = BarelyControlType_kSustain,
/// Envelope release in seconds.
kRelease = BarelyControlType_kRelease,
/// Oscillator mix.
kOscillatorMix = BarelyControlType_kOscillatorMix,
/// Oscillator mode.
kOscillatorMode = BarelyControlType_kOscillatorMode,
/// Oscillator pitch shift.
kOscillatorPitchShift = BarelyControlType_kOscillatorPitchShift,
/// Oscillator shape.
kOscillatorShape = BarelyControlType_kOscillatorShape,
/// Pulse width.
kPulseWidth = BarelyControlType_kPulseWidth,
/// Sample playback mode.
kSamplePlaybackMode = BarelyControlType_kSamplePlaybackMode,
/// Filter type.
kFilterType = BarelyControlType_kFilterType,
/// Filter frequency in hertz.
kFilterFrequency = BarelyControlType_kFilterFrequency,
};
/// Filter type enum.
enum class FilterType {
/// None.
kNone = BarelyFilterType_kNone,
/// Low pass.
kLowPass = BarelyFilterType_kLowPass,
/// High pass.
kHighPass = BarelyFilterType_kHighPass,
};
/// Note control type enum.
enum class NoteControlType {
/// Pitch shift.
kPitchShift = BarelyNoteControlType_kPitchShift,
};
/// Oscillator mode enum.
enum class OscillatorMode {
/// Mix.
kMix = BarelyOscillatorMode_kMix,
/// Amplitude modulation.
kAm = BarelyOscillatorMode_kAm,
/// Envelope follower.
kEnvelopeFollower = BarelyOscillatorMode_kEnvelopeFollower,
// TODO(#146): Add FM support once voice pitch calculation is cleaned up.
// /// Frequency modulation.
// kFm = BarelyOscillatorMode_kFm,
/// Ring modulation.
kRing = BarelyOscillatorMode_kRing,
};
/// Oscillator shape enum.
enum class OscillatorShape {
/// None.
kNone = BarelyOscillatorShape_kNone,
/// Sine wave.
kSine = BarelyOscillatorShape_kSine,
/// Sawtooth wave.
kSaw = BarelyOscillatorShape_kSaw,
/// Square wave.
kSquare = BarelyOscillatorShape_kSquare,
/// White noise.
kNoise = BarelyOscillatorShape_kNoise,
};
/// Sample playback mode enum.
enum class SamplePlaybackMode {
/// None.
kNone = BarelySamplePlaybackMode_kNone,
/// Once.
kOnce = BarelySamplePlaybackMode_kOnce,
/// Sustain.
kSustain = BarelySamplePlaybackMode_kSustain,
/// Loop.
kLoop = BarelySamplePlaybackMode_kLoop,
};
/// Task state enum.
enum class TaskState {
/// Begin.
kBegin = BarelyTaskState_kBegin,
/// End.
kEnd = BarelyTaskState_kEnd,
/// Update.
kUpdate = BarelyTaskState_kUpdate,
};
/// Slice of sample data.
struct SampleDataSlice : public BarelySampleDataSlice {
/// Constructs a new `SampleDataSlice`.
///
/// @param root_pitch Root pich.
/// @param sample_rate Sampling rate in hertz.
/// @param samples Span of mono samples.
explicit constexpr SampleDataSlice(float root_pitch, int sample_rate,
std::span<const float> samples) noexcept
: SampleDataSlice(
{root_pitch, sample_rate, samples.data(), static_cast<int>(samples.size())}) {
assert(sample_rate >= 0);
}
/// Constructs a new `SampleDataSlice` from a raw type.
///
/// @param sample_data_slice Raw sample data slice.
// NOLINTNEXTLINE(google-explicit-constructor)
constexpr SampleDataSlice(BarelySampleDataSlice sample_data_slice) noexcept
: BarelySampleDataSlice{sample_data_slice} {}
};
/// Handle wrapper template.
template <typename HandleType>
class HandleWrapper {
public:
/// Default constructor.
constexpr HandleWrapper() noexcept = default;
/// Constructs a new `HandleWrapper`.
///
/// @param handle Raw handle.
explicit constexpr HandleWrapper(HandleType handle) noexcept : handle_(handle) {
assert(handle != nullptr);
}
/// Default destructor.
constexpr ~HandleWrapper() noexcept = default;
/// Non-copyable.
constexpr HandleWrapper(const HandleWrapper& other) noexcept = delete;
constexpr HandleWrapper& operator=(const HandleWrapper& other) noexcept = delete;
/// Constructs a new `HandleWrapper` via move.
///
/// @param other Other handle wrapper.
constexpr HandleWrapper(HandleWrapper&& other) noexcept
: handle_(std::exchange(other.handle_, nullptr)) {}
/// Assigns `HandleWrapper` via move.
///
/// @param other Other.
/// @return Handle wrapper.
constexpr HandleWrapper& operator=(HandleWrapper&& other) noexcept {
if (this != &other) {
handle_ = std::exchange(other.handle_, nullptr);
}
return *this;
}
/// Returns the raw handle.
///
/// @return Raw handle.
[[nodiscard]] constexpr operator HandleType() const noexcept { return handle_; }
protected:
// Helper functions to set a callback.
template <typename SetCallbackFn, typename... CallbackArgs>
void SetCallback(SetCallbackFn set_callback_fn, std::function<void(CallbackArgs...)>& callback) {
SetCallback(set_callback_fn, callback, [](CallbackArgs... args, void* user_data) noexcept {
assert(user_data != nullptr && "Invalid callback user data");
(*static_cast<std::function<void(CallbackArgs...)>*>(user_data))(args...);
});
}
template <typename ProcessCallbackFn, typename SetCallbackFn, typename... CallbackArgs>
void SetCallback(SetCallbackFn set_callback_fn, std::function<void(CallbackArgs...)>& callback,
ProcessCallbackFn process_callback_fn) {
[[maybe_unused]] bool success = false;
if (callback) {
success = set_callback_fn(handle_, process_callback_fn, &callback);
} else {
success = set_callback_fn(handle_, nullptr, nullptr);
}
assert(success && "HandleWrapper::SetCallback failed");
}
private:
// Raw handle.
HandleType handle_ = nullptr;
};
/// Class that wraps an instrument handle.
class Instrument : public HandleWrapper<BarelyInstrumentHandle> {
public:
/// Note off callback function.
///
/// @param pitch Note pitch.
/// @param intensity Note intensity.
using NoteOffCallback = std::function<void(float pitch)>;
/// Note on callback function.
///
/// @param pitch Note pitch.
/// @param intensity Note intensity.
using NoteOnCallback = std::function<void(float pitch, float intensity)>;
/// Constructs a new `Instrument`.
///
/// @param musician Raw musician handle.
explicit Instrument(BarelyMusicianHandle musician) noexcept
: HandleWrapper([&]() {
BarelyInstrumentHandle instrument = nullptr;
[[maybe_unused]] const bool success = BarelyInstrument_Create(musician, &instrument);
assert(success);
return instrument;
}()) {}
/// Constructs a new `Instrument` from a raw handle.
///
/// @param instrument Raw handle to instrument.
explicit Instrument(BarelyInstrumentHandle instrument) noexcept : HandleWrapper(instrument) {}
/// Destroys `Instrument`.
~Instrument() noexcept { BarelyInstrument_Destroy(*this); }
/// Non-copyable.
Instrument(const Instrument& other) noexcept = delete;
Instrument& operator=(const Instrument& other) noexcept = delete;
/// Constructs a new `Instrument` via move.
///
/// @param other Other instrument.
/// @return Instrument.
Instrument(Instrument&& other) noexcept
: HandleWrapper(std::move(other)),
note_off_callback_(std::exchange(other.note_off_callback_, {})),
note_on_callback_(std::exchange(other.note_on_callback_, {})) {
if (note_off_callback_) {
SetCallback(BarelyInstrument_SetNoteOffCallback, note_off_callback_);
}
if (note_on_callback_) {
SetCallback(BarelyInstrument_SetNoteOnCallback, note_on_callback_);
}
}
/// Assigns `Instrument` via move.
///
/// @param other Other instrument.
/// @return Instrument.
Instrument& operator=(Instrument&& other) noexcept {
if (this != &other) {
BarelyInstrument_Destroy(*this);
HandleWrapper::operator=(std::move(other));
note_off_callback_ = std::exchange(other.note_off_callback_, {});