forked from RandyGaul/cute_headers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcute_sound.h
2719 lines (2257 loc) · 84.8 KB
/
cute_sound.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
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
cute_sound.h - v1.11
To create implementation (the function definitions)
#define CUTE_SOUND_IMPLEMENTATION
in *one* C/CPP file (translation unit) that includes this file
SUMMARY
cute_sound is a C API for loading, playing, looping, panning and fading mono
and stereo sounds, without any external dependencies other than things that ship
with standard OSs, or SDL2 for more uncommon OSs.
For Windows cute_sound uses DirectSound. Due to the use of SSE intrinsics, MinGW
builds must be made with the compiler option: -march=native, or optionally SSE
can be disabled with CUTE_SOUND_SCALAR_MODE. More on this mode written below.
For Apple machines cute_sound uses CoreAudio.
For Linux builds cute_sound uses ALSA (implementation is currently buggy, and
cute_sound's SDL2 implementation is recommended instead).
An SDL2 implementation of cute_sound is available on platforms SDL2 is available,
which is pretty much everywhere. To use the SDL2 implementation of cute_sound
define CUTE_SOUND_FORCE_SDL before placing the CUTE_SOUND_IMPLEMENTATION into a
translation unit in order to force the use of SDL. Here is an example:
#define CUTE_SOUND_FORCE_SDL
#define CUTE_SOUND_IMPLEMENTATION
#include <cute_sound.h>
If you want to use cute_sound with SDL_RWops, you must enable it by putting this
before you #include cute_sound.h:
#define CUTE_SOUND_SDL_RWOPS
REVISION HISTORY
1.0 (06/04/2016) initial release
1.01 (06/06/2016) load WAV from memory
separate portable and OS-specific code in cs_mix
fixed bug causing audio glitches when sounds ended
added stb_vorbis loaders + demo example
1.02 (06/08/2016) error checking + strings in vorbis loaders
SSE2 implementation of mixer
fix typos on docs/comments
corrected volume bug introduced in 1.01
1.03 (07/05/2016) size calculation helper (to know size of sound in
bytes on the heap) cs_sound_size
1.04 (12/06/2016) merged in Aaron Balint's contributions
SFFT and pitch functions from Stephan M. Bernsee
cs_mix can run on its own thread with cs_spawn_mix_thread
updated documentation, typo fixes
fixed typo in cs_malloc16 that caused heap corruption
1.05 (12/08/2016) cs_stop_all_sounds, suggested by Aaron Balint
1.06 (02/17/2017) port to CoreAudio for Apple machines
1.07 (06/18/2017) SIMD the pitch shift code; swapped out old Bernsee
code for a new re-write, updated docs as necessary,
support for compiling as .c and .cpp on Windows,
port for SDL (for Linux, or any other platform).
Special thanks to DeXP (Dmitry Hrabrov) for 90% of
the work on the SDL port!
1.08 (09/06/2017) SDL_RWops support by RobLoach
1.09 (05/20/2018) Load wav funcs can skip all irrelevant chunks
Ref counting for playing sounds
1.10 (08/24/2019) Introduced plugin interface, reimplemented pitch shifting
as a plugin, added optional `ctx` to alloc functions
1.11 (04/23/2020) scalar SIMD mode and various compiler warning/error fixes
CONTRIBUTORS
Aaron Balint 1.04 - real time pitch
1.04 - separate thread for cs_mix
1.04 - bugfix, removed extra cs_free16 call for second channel
DeXP 1.07 - initial work on SDL port
RobLoach 1.08 - SDL_RWops support
Matt Rosen 1.10 - Initial experiments with cute_dsp to figure out plugin
interface needs and use-cases
fluffrabbit 1.11 - scalar SIMD mode and various compiler warning/error fixes
DOCUMENTATION (very quick intro)
1. create context
2. load sounds from disk into memory
3. play sounds
4. free context
1. cs_context_t* ctx = cs_make_context(hwnd, frequency, buffered_samples, N, NULL);
2. cs_play_sound_def_t def = cs_make_def(&cs_load_wav("path_to_file/filename.wav"));
3. cs_play_sound(ctx, def);
4. cs_shutdown_context(ctx);
DOCUMENTATION (longer introduction)
cute_sound consists of cs_loaded_sound_t, cs_playing_sound_t and the cs_context_t.
The cs_context_t encapsulates an OS sound API, as well as buffers + settings.
cs_loaded_sound_t holds raw samples of a sound. cs_playing_sound_t is an instance
of a cs_loaded_sound_t that represents a sound that can be played through the
cs_context_t.
There are two main versions of the API, the low-level and the high-level
API. The low-level API does not manage any memory for cs_playing_sound_ts. The
high level api holds a memory pool of playing sounds.
To actually mix sounds together and send audio to the sound card, be sure
to call either cs_mix periodically or call cs_spawn_mix_thread once.
High-level API
First create a context and pass in non-zero to the final parameter. This
final parameter controls how large of a memory pool to use for cs_playing_sound_t's.
Here's an example where N is the size of the internal pool:
cs_context_t* ctx = cs_make_context(hwnd, frequency, buffered_samples, N, NULL);
We create cs_playing_sound_t's indirectly with cs_play_def_t structs. cs_play_def_t is a
POD struct so feel free to make them straight on the stack. The cs_play_def
sets up initialization parameters. Here's an example to load a wav and
play it:
cs_loaded_sound_t loaded = cs_load_wav("path_to_file/filename.wav");
cs_play_sound_def_t def = cs_make_def(&loaded);
cs_playing_sound_t* sound = cs_play_sound(ctx, def);
The same def can be used to play as many sounds as desired (even simultaneously)
as long as the context playing sound pool is large enough.
You can work with some low-level functionality by iterating through the linked list
ctx->playing, which can be accessed by calling cs_get_playing(ctx). If you spawned a
thread via cs_spawn_mix_thread, remember to call cs_lock before you work with
cs_get_playing and call cs_unlock afterwards so sound can play again.
Low-level API
First create a context and pass 0 in the final parameter (0 here means
the context will *not* allocate a cs_playing_sound_t memory pool):
cs_context_t* ctx = cs_make_context(hwnd, frequency, buffered_samples, 0, NULL);
parameters:
hwnd -- HWND, handle to window (on OSX just pass in 0)
frequency -- int, represents Hz frequency rate in which samples are played
buffered_samples -- int, number of samples the internal ring buffers can hold at once
0 -- int, number of elements in cs_playing_sound_t pool
NULL -- optional pointer for custom allocator, just set to NULL
We create a cs_playing_sound_t like so:
cs_loaded_sound_t loaded = cs_load_wav("path_to_file/filename.wav");
cs_playing_sound_t playing_sound = cs_make_playing_sound(&loaded);
Then to play the sound we do:
cs_insert_sound(ctx, &playing_sound);
The above cs_insert_sound function call will place playing_sound into
a singly-linked list inside the context. The context will remove
the sound from its internal list when it finishes playing.
WARNING: The high-level API cannot be mixed with the low-level API. If you
try then the internal code will assert and crash. Pick one and stick with it.
Usually he high-level API will be used, but if someone is *really* picky about
their memory usage, or wants more control, the low-level API can be used.
Here is the Low-Level API:
cs_playing_sound_t cs_make_playing_sound(cs_loaded_sound_t* loaded);
int cs_insert_sound(cs_context_t* ctx, cs_playing_sound_t* sound);
Here is the High-Level API:
cs_playing_sound_t* cs_play_sound(cs_context_t* ctx, cs_play_sound_def_t def);
cs_play_sound_def_t cs_make_def(cs_loaded_sound_t* sound);
void cs_stop_all_sounds(cs_context_t(ctx);
Be sure to link against dsound.dll (or dsound.lib) on Windows.
Read the rest of the header for specific details on all available functions
and struct types.
PLUGINS
Cute sound can add plugins at run-time to modify audio before it gets mixed. Please
refer to all the documentation near `cs_plugin_interface_t`.
DISABLE SSE SIMD ACCELERATION
If for whatever reason you don't want to use SSE intrinsics and instead would prefer
plain C (for example if your platform does not support SSE) then define
CUTE_SOUND_SCALAR_MODE before including cute_sound.h while also defining the
symbol definitions. Here's an example:
#define CUTE_SOUND_IMPLEMENTATION
#define CUTE_SOUND_SCALAR_MODE
#include <cute_sound.h>
KNOWN LIMITATIONS
* PCM mono/stereo format is the only formats the LoadWAV function supports. I don't
guarantee it will work for all kinds of wav files, but it certainly does for the common
kind (and can be changed fairly easily if someone wanted to extend it).
* Only supports 16 bits per sample.
* Mixer does not do any fancy clipping. The algorithm is to convert all 16 bit samples
to float, mix all samples, and write back to audio API as 16 bit integers. In
practice this works very well and clipping is not often a big problem.
FAQ
Q : Why DirectSound instead of (insert API here) on Windows?
A : Casey Muratori documented DS on Handmade Hero, other APIs do not have such good docs. DS has
shipped on Windows XP all the way through Windows 10 -- using this header effectively intro-
duces zero dependencies for the foreseeable future. The DS API itself is sane enough to quickly
implement needed features, and users won't hear the difference between various APIs. Latency is
not that great with DS but it is shippable. Additionally, many other APIs will in the end speak
to Windows through the DS API.
Q : I would like to use my own memory management, how can I achieve this?
A : This header makes a couple uses of malloc/free, and cs_malloc16/cs_free16. Simply find these bits
and replace them with your own memory allocation routines. They can be wrapped up into a macro,
or call your own functions directly -- it's up to you. Generally these functions allocate fairly
large chunks of memory, and not very often (if at all).
Q : Does this library support audio streaming? Something like System::createStream in FMOD.
A : No. Typically music files aren't that large (in the megabytes). Compare this to a typical
DXT texture of 1024x1024, at 0.5MB of memory. Now say an average music file for a game is three
minutes long. Loading this file into memory and storing it as raw 16bit samples with two channels,
would be:
num_samples = 3 * 60 * 44100 * 2
num_bits = num_samples * 16
num_bytes = num_bits / 8
num_megabytes = num_bytes / (1024 * 1024)
or 30.3mb
So say the user has 2gb of spare RAM. That means we could fit 67 different three minute length
music files in there simultaneously. That is a ridiculous amount of spare memory. 30mb is nothing
nowadays. Just load your music file into memory all at once and then play it.
Q : But I really need streaming of audio files from disk to save memory! Also loading my audio
files (like .OGG) takes a long time (multiple seconds).
A : It is recommended to either A) load up your music files before they are needed, perhaps during
a loading screen, or B) stream in the entire audio into memory on another thread. cs_read_mem_ogg is
a great candidate function to throw onto a job pool. Streaming is more a remnant of older machines
(like in the 90's or early 2000's) where decoding speed and RAM were real nasty bottlenecks. For
more modern machines, these aren't really concerns, even with mobile devices. If even after reading
this Q/A section you still want to stream your audio, you can try mini_al as an alternative:
https://github.com/dr-soft/mini_al
*/
/*
Some past discussion threads:
https://www.reddit.com/r/gamedev/comments/6i39j2/tinysound_the_cutest_library_to_get_audio_into/
https://www.reddit.com/r/gamedev/comments/4ml6l9/tinysound_singlefile_c_audio_library/
https://forums.tigsource.com/index.php?topic=58706.0
*/
#if !defined(CUTE_SOUND_H)
#if defined(_WIN32)
#if !defined _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#if !defined _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
#endif
#include <stdint.h>
// read this in the event of cs_load_wav/cs_load_ogg errors
// also read this in the event of certain errors from cs_make_context
extern const char* cs_error_reason;
// stores a loaded sound in memory
typedef struct cs_loaded_sound_t
{
int sample_rate;
int sample_count;
int channel_count;
// Number of instances currently referencing this audio. Must be zero
// in order to safely delete the audio. References are automatically
// updated whenever playing instances are inserted into the context.
int playing_count;
// The actual raw audio samples in memory.
void* channels[2];
} cs_loaded_sound_t;
// Don't change this unless necessary. 32 is a huge number to begin with.
#define CUTE_SOUND_PLUGINS_MAX (32)
// represents an instance of a cs_loaded_sound_t, can be played through the cs_context_t
typedef struct cs_playing_sound_t
{
int active;
int paused;
int looped;
float volume0;
float volume1;
float pan0;
float pan1;
int sample_index;
cs_loaded_sound_t* loaded_sound;
struct cs_playing_sound_t* next;
void* plugin_udata[CUTE_SOUND_PLUGINS_MAX];
} cs_playing_sound_t;
// holds audio API info and other info
struct cs_context_t;
typedef struct cs_context_t cs_context_t;
// The returned struct will contain a null pointer in cs_loaded_sound_t::channel[0]
// in the case of errors. Read cs_error_reason string for details on what happened.
// Calls cs_read_mem_wav internally.
cs_loaded_sound_t cs_load_wav(const char* path);
// Reads a WAV file from memory. Still allocates memory for the cs_loaded_sound_t since
// WAV format will interlace stereo, and we need separate data streams to do SIMD
// properly.
void cs_read_mem_wav(const void* memory, int size, cs_loaded_sound_t* sound);
// If stb_vorbis was included *before* cute_sound go ahead and create
// some functions for dealing with OGG files.
#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H
void cs_read_mem_ogg(const void* memory, int length, cs_loaded_sound_t* sound);
cs_loaded_sound_t cs_load_ogg(const char* path);
#endif
// Uses cs_free16 (aligned free, implemented later in this file) to free up both of
// the channels stored within sound
void cs_free_sound(cs_loaded_sound_t* sound);
// Returns the size, in bytes, of all heap-allocated memory for this particular
// loaded sound
int cs_sound_size(cs_loaded_sound_t* sound);
// playing_pool_count -- 0 to setup low-level API, non-zero to size the internal
// memory pool for cs_playing_sound_t instances
// `user_allocator_context` can be NULL - it is passed to `CUTE_SOUND_ALLOC` and
// `CUTE_SOUND_FREE`.
cs_context_t* cs_make_context(void* hwnd, unsigned play_frequency_in_Hz, int buffered_samples, int playing_pool_count, void* user_allocator_context);
void cs_shutdown_context(cs_context_t* ctx);
// Call cs_spawn_mix_thread once to setup a separate thread for the context to run
// upon. The separate thread will continually call cs_mix and perform mixing
// operations.
void cs_spawn_mix_thread(cs_context_t* ctx);
// Use cs_thread_sleep_delay to specify a custom sleep delay time.
// A sleep will occur after each call to cs_mix. By default YieldProcessor
// is used, and no sleep occurs. Use a sleep delay to conserve CPU bandwidth.
// A recommended sleep time is a little less than 1/2 your predicted 1/FPS.
// 60 fps is 16 ms, so about 1-5 should work well in most cases.
void cs_thread_sleep_delay(cs_context_t* ctx, int milliseconds);
// Lock the thread before working with some of the lower-level stuff.
void cs_lock(cs_context_t* ctx);
// Unlock the thread after you've done that stuff.
void cs_unlock(cs_context_t* ctx);
// Call this manually, once per game tick recommended, if you haven't ever
// called cs_spawn_mix_thread. Otherwise the thread will call cs_mix itself.
// num_samples_to_write is not used on Windows. On Mac it is used to push
// samples into a circular buffer while CoreAudio simultaneously pulls samples
// off of the buffer. num_samples_to_write should be computed each update tick
// as delta_time * play_frequency_in_Hz + 1.
void cs_mix(cs_context_t* ctx);
// All of the functions in this next section should only be called if cs_is_active
// returns true. Calling them otherwise probably won't do anything bad, but it
// won't do anything at all. If a sound is active it resides in the context's
// internal list of playing sounds.
int cs_is_active(cs_playing_sound_t* sound);
// Flags sound for removal. Upon next cs_mix call will remove sound from playing
// list. If high-level API used sound is placed onto the internal free list.
void cs_stop_sound(cs_playing_sound_t* sound);
void cs_loop_sound(cs_playing_sound_t* sound, int zero_for_no_loop);
void cs_pause_sound(cs_playing_sound_t* sound, int one_for_paused);
// lerp from 0 to 1, 0 full left, 1 full right
void cs_set_pan(cs_playing_sound_t* sound, float pan);
// explicitly set volume of each channel. Can be used as panning (but it's
// recommended to use the cs_set_pan function for panning).
void cs_set_volume(cs_playing_sound_t* sound, float volume_left, float volume_right);
// Delays sound before actually playing it. Requires context to be passed in
// since there's a conversion from seconds to samples per second.
// If one were so inclined another version could be implemented like:
// void cs_set_delay(cs_playing_sound_t* sound, float delay, int samples_per_second)
void cs_set_delay(cs_context_t* ctx, cs_playing_sound_t* sound, float delay_in_seconds);
// Return the linked list ctx->playing, be sure to use cs_lock or cs_unlock if mixing on
// another thread.
cs_playing_sound_t* cs_get_playing(cs_context_t* ctx);
// Portable sleep function. Do not call this with milliseconds > 999.
void cs_sleep(int milliseconds);
// LOW-LEVEL API
cs_playing_sound_t cs_make_playing_sound(cs_loaded_sound_t* loaded);
int cs_insert_sound(cs_context_t* ctx, cs_playing_sound_t* sound); // returns 1 if sound was successfully inserted, 0 otherwise
// HIGH-LEVEL API
// This def struct is just used to pass parameters to `cs_play_sound`.
// Be careful since `loaded` points to a `cs_loaded_sound_t` struct, so make
// sure the `cs_loaded_sound_t` struct persists in memory!
typedef struct cs_play_sound_def_t
{
int paused;
int looped;
float volume_left;
float volume_right;
float pan;
float delay;
cs_loaded_sound_t* loaded;
} cs_play_sound_def_t;
cs_playing_sound_t* cs_play_sound(cs_context_t* ctx, cs_play_sound_def_t def);
cs_play_sound_def_t cs_make_def(cs_loaded_sound_t* sound);
void cs_stop_all_sounds(cs_context_t* ctx);
// SDL_RWops specific functions
#if defined(SDL_rwops_h_) && defined(CUTE_SOUND_SDL_RWOPS)
// Provides the ability to use cs_load_wav with an SDL_RWops object.
cs_loaded_sound_t cs_load_wav_rw(SDL_RWops* context);
#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H
// Provides the ability to use cs_load_ogg with an SDL_RWops object.
cs_loaded_sound_t cs_load_ogg_rw(SDL_RWops* rw);
#endif
#endif // SDL_rwops_h_
/**
* Uniquely identifies a plugin once added to a `cs_context_t` via `cs_add_plugin`.
*/
typedef int cs_plugin_id_t;
/**
* Plugin interface.
*
* A plugin is anyone who implements one of these cs_plugin_interface_t structs
* and then calls `cs_add_plugin(ctx, plugin_ptr)`. Plugins can be implemented to
* perform custom operations on playing sounds before they mixed to the audio driver.
*/
typedef struct cs_plugin_interface_t
{
/**
* This pointer is used to represent your plugin instance, and is pased to all callbacks as the
* `plugin_instance` pointer. This pointer is not managed by cute sound in any way. You are
* responsible for allocating and releasing all resources associated with the plugin instance.
*/
void* plugin_instance;
/**
* Called whenever a new sound is starting to play. `playing_sound_udata` is optional, and should
* point to whatever data you would like to associate with playing sounds, on a per-playing-sound
* basis.
*
* This function is only called from user threads whenever `cs_play_sound` or `cs_insert_sound`
* is called.
*/
void (*on_make_playing_sound_fn)(cs_context_t* cs_ctx, void* plugin_instance, void** playing_sound_udata, const cs_playing_sound_t* sound);
/**
* Called once for each time `on_make_playing_sound_fn` is called. The pointer originally assigned
* in `on_make_playing_sound_fn` will be passed back here as `playing_sound_udata`. The intent is
* to let the user free up any resources associated with the playing sound instance before the sound
* is released completely internally.
*
* This function can be called from the user thread, or from the mixer thread.
*/
void (*on_free_playing_sound_fn)(cs_context_t* cs_ctx, void* plugin_instance, void* playing_sound_udata, const cs_playing_sound_t* sound);
/**
* Called when mixing each playing sound instance, once per channel on each playing sound instance.
* This function gives the plugin a chance to alter any audio before being mixed by cute_sound to
* the audio driver. The source audio is not alterable, however, the plugin can copy `samples_in`
* and then output modified samples in `samples_out`.
*
* `channel_index` This function is called once per source channel, so `channel_index` will be either
* 0 or 1, depending on the channel count.
* `samples_in` All audio from the playing sound's source.
* `sample_count` The number of samples in `samples_in` and expected in `samples_out`.
* `samples_out` Required to point to a valid samples buffer. The simplest case is to assign `samples_out`
* directly as `samples_in`, performing no modifications. In most cases though the plugin
* will make a copy of `(float*)samples_in`, alter the samples, and assign `samples_out` to
* point to the modified samples. `samples_out` is expected to point to a valid buffer until
* the next time `on_mix_fn` is called. Typically the plugin can hold a single buffer used
* for altered samples, and simply reuse the same buffer each time `on_mix_fn` is called.
* `playing_sound_udata` The user data `playing_sound_udata` assigned when `on_make_playing_sound_fn` was called.
*
* This function can be called from the user thread, or from the mixer thread.
*/
void (*on_mix_fn)(cs_context_t* cs_ctx, void* plugin_instance, int channel_index, const float* samples_in, int sample_count, float** samples_out, void* playing_sound_udata, const cs_playing_sound_t* sound);
} cs_plugin_interface_t;
cs_plugin_id_t cs_add_plugin(cs_context_t* ctx, const cs_plugin_interface_t* plugin);
#define CUTE_SOUND_H
#endif
#ifdef CUTE_SOUND_IMPLEMENTATION
#ifndef CUTE_SOUND_IMPLEMENTATION_ONCE
#define CUTE_SOUND_IMPLEMENTATION_ONCE
#ifndef CUTE_SOUND_MINIMUM_BUFFERED_SAMPLES
# define CUTE_SOUND_MINIMUM_BUFFERED_SAMPLES 1024
#endif
#if !defined(CUTE_SOUND_ALLOC)
#include <stdlib.h> // malloc, free
#define CUTE_SOUND_ALLOC(size, ctx) malloc(size)
#define CUTE_SOUND_FREE(mem, ctx) free(mem)
#endif
#include <stdio.h> // fopen, fclose
#include <string.h> // memcmp, memset, memcpy
// Platform detection.
#define CUTE_SOUND_WINDOWS 1
#define CUTE_SOUND_APPLE 2
#define CUTE_SOUND_LINUX 3
#define CUTE_SOUND_SDL 4
#if defined(_WIN32)
#if !defined _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#if !defined _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
#define CUTE_SOUND_PLATFORM CUTE_SOUND_WINDOWS
#elif defined(__APPLE__)
#define CUTE_SOUND_PLATFORM CUTE_SOUND_APPLE
#elif defined(__linux__)
#define CUTE_SOUND_PLATFORM CUTE_SOUND_LINUX
#else
// Just use SDL on other esoteric platforms.
#define CUTE_SOUND_PLATFORM CUTE_SOUND_SDL
#endif
// Use CUTE_SOUND_FORCE_SDL to override the above macros and use the SDL port.
#ifdef CUTE_SOUND_FORCE_SDL
#undef CUTE_SOUND_PLATFORM
#define CUTE_SOUND_PLATFORM CUTE_SOUND_SDL
#endif
// Platform specific file inclusions.
#if CUTE_SOUND_PLATFORM == CUTE_SOUND_WINDOWS
#ifndef _WINDOWS_
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#ifndef _WAVEFORMATEX_
#include <mmreg.h>
#include <mmsystem.h>
#endif
#include <dsound.h>
#undef PlaySound
#ifdef _MSC_VER
#pragma comment(lib, "dsound.lib")
#endif
#elif CUTE_SOUND_PLATFORM == CUTE_SOUND_APPLE
#include <CoreAudio/CoreAudio.h>
#include <AudioUnit/AudioUnit.h>
#include <pthread.h>
#include <mach/mach_time.h>
#elif CUTE_SOUND_PLATFORM == CUTE_SOUND_LINUX
#define ALSA_PCM_NEW_HW_PARAMS_API
#include <alsa/asoundlib.h>
#include <unistd.h> // nanosleep
#include <dlfcn.h> // dlopen, dclose, dlsym
#define timespec // Avoids duplicate definitions.
#undef timespec // You must compile with POSIX features enabled.
#include <pthread.h>
#include <alloca.h>
#include <assert.h>
#elif CUTE_SOUND_PLATFORM == CUTE_SOUND_SDL
#include <SDL2/SDL.h>
#ifndef _WIN32
#include <alloca.h>
#endif
#else
#error Unsupported platform - please choose one of CUTE_SOUND_WINDOWS, CUTE_SOUND_APPLE, CUTE_SOUND_LINUX or CUTE_SOUND_SDL.
#endif
#ifdef CUTE_SOUND_SCALAR_MODE
#include <limits.h>
#define CS_SATURATE16(X) (int16_t)((X) > SHRT_MAX ? SHRT_MAX : ((X) < SHRT_MIN ? SHRT_MIN : (X)))
typedef struct cs__m128
{
float a, b, c, d;
} cs__m128;
typedef struct cs__m128i
{
int32_t a, b, c, d;
} cs__m128i;
cs__m128 cs_mm_set_ps(float e3, float e2, float e1, float e0)
{
cs__m128 a;
a.a = e0;
a.b = e1;
a.c = e2;
a.d = e3;
return a;
}
cs__m128 cs_mm_set1_ps(float e)
{
cs__m128 a;
a.a = e;
a.b = e;
a.c = e;
a.d = e;
return a;
}
cs__m128 cs_mm_load_ps(float const* mem_addr)
{
cs__m128 a;
a.a = mem_addr[0];
a.b = mem_addr[1];
a.c = mem_addr[2];
a.d = mem_addr[3];
return a;
}
cs__m128 cs_mm_add_ps(cs__m128 a, cs__m128 b)
{
cs__m128 c;
c.a = a.a + b.a;
c.b = a.b + b.b;
c.c = a.c + b.c;
c.d = a.d + b.d;
return c;
}
cs__m128 cs_mm_mul_ps(cs__m128 a, cs__m128 b)
{
cs__m128 c;
c.a = a.a * b.a;
c.b = a.b * b.b;
c.c = a.c * b.c;
c.d = a.d * b.d;
return c;
}
cs__m128i cs_mm_cvtps_epi32(cs__m128 a)
{
cs__m128i b;
b.a = a.a;
b.b = a.b;
b.c = a.c;
b.d = a.d;
return b;
}
cs__m128i cs_mm_unpacklo_epi32(cs__m128i a, cs__m128i b)
{
cs__m128i c;
c.a = a.a;
c.b = b.a;
c.c = a.b;
c.d = b.b;
return c;
}
cs__m128i cs_mm_unpackhi_epi32(cs__m128i a, cs__m128i b)
{
cs__m128i c;
c.a = a.c;
c.b = b.c;
c.c = a.d;
c.d = b.d;
return c;
}
cs__m128i cs_mm_packs_epi32(cs__m128i a, cs__m128i b)
{
union {
int16_t c[8];
cs__m128i m;
} dst;
dst.c[0] = CS_SATURATE16(a.a);
dst.c[1] = CS_SATURATE16(a.b);
dst.c[2] = CS_SATURATE16(a.c);
dst.c[3] = CS_SATURATE16(a.d);
dst.c[4] = CS_SATURATE16(b.a);
dst.c[5] = CS_SATURATE16(b.b);
dst.c[6] = CS_SATURATE16(b.c);
dst.c[7] = CS_SATURATE16(b.d);
return dst.m;
}
#else
#include <xmmintrin.h>
#include <emmintrin.h>
#define cs__m128 __m128
#define cs__m128i __m128i
#define cs_mm_set_ps _mm_set_ps
#define cs_mm_set1_ps _mm_set1_ps
#define cs_mm_load_ps _mm_load_ps
#define cs_mm_add_ps _mm_add_ps
#define cs_mm_mul_ps _mm_mul_ps
#define cs_mm_cvtps_epi32 _mm_cvtps_epi32
#define cs_mm_unpacklo_epi32 _mm_unpacklo_epi32
#define cs_mm_unpackhi_epi32 _mm_unpackhi_epi32
#define cs_mm_packs_epi32 _mm_packs_epi32
#endif // CUTE_SOUND_SCALAR_MODE
#define CUTE_SOUND_CHECK(X, Y) do { if (!(X)) { cs_error_reason = Y; goto ts_err; } } while (0)
#ifdef __clang__
#define CUTE_SOUND_ASSERT_INTERNAL __builtin_trap()
#else
#define CUTE_SOUND_ASSERT_INTERNAL *(int*)0 = 0
#endif
#define CUTE_SOUND_ASSERT(X) do { if (!(X)) CUTE_SOUND_ASSERT_INTERNAL; } while (0)
#define CUTE_SOUND_ALIGN(X, Y) ((((size_t)X) + ((Y) - 1)) & ~((Y) - 1))
#define CUTE_SOUND_TRUNC(X, Y) ((size_t)(X) & ~((Y) - 1))
const char* cs_error_reason;
static void* cs_read_file_to_memory(const char* path, int* size, void* mem_ctx)
{
(void)mem_ctx;
void* data = 0;
FILE* fp = fopen(path, "rb");
int sizeNum = 0;
if (fp)
{
fseek(fp, 0, SEEK_END);
sizeNum = (int)ftell(fp);
fseek(fp, 0, SEEK_SET);
data = CUTE_SOUND_ALLOC(sizeNum, mem_ctx);
(void)(fread(data, sizeNum, 1, fp) + 1);
fclose(fp);
}
if (size) *size = sizeNum;
return data;
}
static int cs_four_cc(const char* CC, void* memory)
{
if (!memcmp(CC, memory, 4)) return 1;
return 0;
}
static char* cs_next(char* data)
{
uint32_t size = *(uint32_t*)(data + 4);
size = (size + 1) & ~1;
return data + 8 + size;
}
static void* cs_malloc16(size_t size, void* mem_ctx)
{
(void)mem_ctx;
void* p = CUTE_SOUND_ALLOC(size + 16, mem_ctx);
if (!p) return 0;
unsigned char offset = (size_t)p & 15;
p = (void*)CUTE_SOUND_ALIGN(p + 1, 16);
*((char*)p - 1) = 16 - offset;
CUTE_SOUND_ASSERT(!((size_t)p & 15));
return p;
}
static void cs_free16(void* p, void* mem_ctx)
{
(void)mem_ctx;
if (!p) return;
CUTE_SOUND_FREE((char*)p - (((size_t)*((char*)p - 1)) & 0xFF), NULL);
}
static void cs_last_element(cs__m128* a, int i, int j, int16_t* samples, int offset)
{
switch (offset)
{
case 1:
a[i] = cs_mm_set_ps(samples[j], 0.0f, 0.0f, 0.0f);
break;
case 2:
a[i] = cs_mm_set_ps(samples[j], samples[j + 1], 0.0f, 0.0f);
break;
case 3:
a[i] = cs_mm_set_ps(samples[j], samples[j + 1], samples[j + 2], 0.0f);
break;
case 0:
a[i] = cs_mm_set_ps(samples[j], samples[j + 1], samples[j + 2], samples[j + 3]);
break;
}
}
void cs_read_mem_wav(const void* memory, int size, cs_loaded_sound_t* sound)
{
#pragma pack(push, 1)
typedef struct
{
uint16_t wFormatTag;
uint16_t nChannels;
uint32_t nSamplesPerSec;
uint32_t nAvgBytesPerSec;
uint16_t nBlockAlign;
uint16_t wBitsPerSample;
uint16_t cbSize;
uint16_t wValidBitsPerSample;
uint32_t dwChannelMask;
uint8_t SubFormat[18];
} Fmt;
#pragma pack(pop)
sound->playing_count = 0;
char* data = (char*)memory;
char* end = data + size;
CUTE_SOUND_CHECK(data, "Unable to read input file (file doesn't exist, or could not allocate heap memory.");
CUTE_SOUND_CHECK(cs_four_cc("RIFF", data), "Incorrect file header; is this a WAV file?");
CUTE_SOUND_CHECK(cs_four_cc("WAVE", data + 8), "Incorrect file header; is this a WAV file?");
data += 12;
while (1)
{
CUTE_SOUND_CHECK(end > data, "Error searching for fmt chunk.");
if (cs_four_cc("fmt ", data)) break;
data = cs_next(data);
}
Fmt fmt;
fmt = *(Fmt*)(data + 8);
CUTE_SOUND_CHECK(fmt.wFormatTag == 1, "Only PCM WAV files are supported.");
CUTE_SOUND_CHECK(fmt.nChannels == 1 || fmt.nChannels == 2, "Only mono or stereo supported (too many channels detected).");
CUTE_SOUND_CHECK(fmt.wBitsPerSample == 16, "Only 16 bits per sample supported.");
CUTE_SOUND_CHECK(fmt.nBlockAlign == fmt.nChannels * 2, "implementation error");
sound->sample_rate = (int)fmt.nSamplesPerSec;
while (1)
{
CUTE_SOUND_CHECK(end > data, "Error searching for data chunk.");
if (cs_four_cc("data", data)) break;
data = cs_next(data);
}
{
int sample_size = *((uint32_t*)(data + 4));
int sample_count = sample_size / (fmt.nChannels * sizeof(uint16_t));
sound->sample_count = sample_count;
sound->channel_count = fmt.nChannels;
int wide_count = (int)CUTE_SOUND_ALIGN(sample_count, 4);
wide_count /= 4;
int wide_offset = sample_count & 3;
int16_t* samples = (int16_t*)(data + 8);
float* sample = (float*)alloca(sizeof(float) * 4 + 16);
sample = (float*)CUTE_SOUND_ALIGN(sample, 16);
switch (sound->channel_count)
{
case 1:
{
sound->channels[0] = cs_malloc16(wide_count * sizeof(cs__m128), NULL);
sound->channels[1] = 0;
cs__m128* a = (cs__m128*)sound->channels[0];
for (int i = 0, j = 0; i < wide_count - 1; ++i, j += 4)
{
sample[0] = (float)samples[j];
sample[1] = (float)samples[j + 1];
sample[2] = (float)samples[j + 2];
sample[3] = (float)samples[j + 3];
a[i] = cs_mm_load_ps(sample);
}
cs_last_element(a, wide_count - 1, (wide_count - 1) * 4, samples, wide_offset);
} break;
case 2:
{
cs__m128* a = (cs__m128*)cs_malloc16(wide_count * sizeof(cs__m128) * 2, NULL);
cs__m128* b = a + wide_count;
for (int i = 0, j = 0; i < wide_count - 1; ++i, j += 8)
{
sample[0] = (float)samples[j];
sample[1] = (float)samples[j + 2];
sample[2] = (float)samples[j + 4];
sample[3] = (float)samples[j + 6];
a[i] = cs_mm_load_ps(sample);
sample[0] = (float)samples[j + 1];
sample[1] = (float)samples[j + 3];
sample[2] = (float)samples[j + 5];
sample[3] = (float)samples[j + 7];
b[i] = cs_mm_load_ps(sample);
}
cs_last_element(a, wide_count - 1, (wide_count - 1) * 4, samples, wide_offset);
cs_last_element(b, wide_count - 1, (wide_count - 1) * 4 + 4, samples, wide_offset);
sound->channels[0] = a;
sound->channels[1] = b;
} break;
default:
CUTE_SOUND_CHECK(0, "unsupported channel count (only support mono and stereo).");
}
}
return;
ts_err:
memset(&sound, 0, sizeof(sound));
}
cs_loaded_sound_t cs_load_wav(const char* path)
{
cs_loaded_sound_t sound = { 0, 0, 0, 0, { NULL, NULL } };
int size;
char* wav = (char*)cs_read_file_to_memory(path, &size, NULL);
cs_read_mem_wav(wav, size, &sound);
CUTE_SOUND_FREE(wav, NULL);
return sound;
}
#if CUTE_SOUND_PLATFORM == CUTE_SOUND_SDL && defined(SDL_rwops_h_) && defined(CUTE_SOUND_SDL_RWOPS)
// Load an SDL_RWops object's data into memory.
// Ripped straight from: https://wiki.libsdl.org/SDL_RWread
static void* cs_read_rw_to_memory(SDL_RWops* rw, int* size, void* mem_ctx)
{
Sint64 res_size = SDL_RWsize(rw);
char* data = (char*)CUTE_SOUND_ALLOC((size_t)(res_size + 1), mem_ctx);
Sint64 nb_read_total = 0, nb_read = 1;
char* buf = data;