-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixer.d
1156 lines (954 loc) · 34.7 KB
/
mixer.d
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
/**
* `IMixer` API and definition. This is the API entrypoint.
*
* Copyright: Copyright Guillaume Piolat 2021.
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
*/
module gamemixer.mixer;
import core.thread;
import core.atomic;
import std.math: SQRT2, PI_4;
import dplug.core;
import dplug.audio;
import gamemixer.effects;
import gamemixer.source;
/// Restrict the library to ONLY use loopback
/// Use "loopback" DUB configuration to enable this.
//version = onlyLoopback;
version(onlyLoopback)
{
}
else
version = hasSoundIO;
version(hasSoundIO)
{
import soundio;
}
nothrow:
@nogc:
/// Create a `Mixer` and start playback.
IMixer mixerCreate(MixerOptions options = MixerOptions.init)
{
return mallocNew!Mixer(options);
}
/// Stops `playback`.
void mixerDestroy(IMixer mixer)
{
destroyFree(mixer);
}
/// Options to create the mixer with.
/// You can customize sample-rate or the number of internal tracks.
/// Always stereo.
struct MixerOptions
{
/// If loopback, the mixer is intended not to produce audio. Instead you should call `generateToLoopback`.
/// If `false` (default), the mixer will directly output audio to the OS.
bool isLoopback = false;
/// Desired output sample rate.
float sampleRate = 48000.0f;
/// Number of possible sounds to play simultaneously.
int numChannels = 16;
/// The fade time it takes for one playing channel to change its volume with `setChannelVolume`.
float channelVolumeSecs = 0.040f;
}
/// Chooses any mixer channel.
enum anyMixerChannel = -1;
/// Loop the source forever.
enum uint loopForever = uint.max;
/// Options when playing a source.
struct PlayOptions
{
/// The channel where to play the source.
/// `anyMixerChannel` for the first free unreserved channel.
int channel = anyMixerChannel;
/// The volume to play the source with. This one volume cannot change during playback.
/// This is multiplied by the channel-specific volume and the master volume, which can change.
float volume = 1.0f;
/// The angle pan to play the source with.
/// -1 = full left
/// 1 = full right
float pan = 0.0f;
/// The delay in seconds before which to play.
/// The time reference is the time given by `playbackTimeInSeconds()`.
/// The source starts playing when `playbackTimeInSeconds` has increased by `delayBeforePlay`.
/// Note that it still occupies the channel.
/// Warning: can't use both `delayBeforePlay` and `startTimeSecs` at the same time.
float delayBeforePlay = 0.0f;
/// Play the sound immediately, starting at a given time in the sample (in mixer time).
/// Warning: can't use both `delayBeforePlay` and `startTimeSecs` at the same time.
float startTimeSecs = 0.0f;
/// Number of times the source is looped.
uint loopCount = 1;
/// The time it takes to start the sound if the channel is already busy.
/// If the channel isn't busy, `faceInSecs` is used.
/// Default: 14ms transition.
float crossFadeInSecs = 0.000f; // Default was tuned on drum machine example
/// The time it takes to halt the existing sound if the channel is already busy.
/// If the channel isn't busy, there is nothing to halt.
/// Default: 40ms transition out.
float crossFadeOutSecs = 0.040f; // Default was tuned on drum machine example.
/// Fade in time when the channel is free. This can be used to "dull" percussive samples and
/// give them an attack time.
/// Default: no fade in for maximum punch.
float fadeInSecs = 0.0f;
}
/// Public API for the `Mixer` object.
interface IMixer
{
nothrow:
@nogc:
/// Create a source from file or memory.
/// (All sources get destroyed automatically when the IMixer is destroyed).
/// Returns: `null` if loading failed
IAudioSource createSourceFromMemory(const(ubyte[]) inputData);
///ditto
IAudioSource createSourceFromFile(const(char[]) path);
/// Play a source.
/// This locks the audio thread for a short while.
void play(IAudioSource source, PlayOptions options);
void play(IAudioSource source, float volume = 1.0f);
/// Play several source simulatenously, these will be synchronized down to sample accuracy.
/// This locks the audio thread for a short while.
void playSimultaneously(IAudioSource[] sources, PlayOptions[] options);
/// Stop sound playing on a given channel.
void stopChannel(int channel, float fadeOutSecs = 0.040f);
void stopAllChannels(float fadeOutSecs = 0.040f);
/// Sets the volume of a particular channel (default is 1.0f).
void setChannelVolume(int channel, float volume);
/// Sets the volume of the master bus (volume should typically be between 0 and 1).
void setMasterVolume(float volume);
/// Adds an effect on the master channel (all sounds mixed together).
void addMasterEffect(IAudioEffect effect);
/// Creates an effect with a custom callback processing function.
/// (All effects get destroyed automatically when the IMixer is destroyed).
IAudioEffect createEffectCustom(EffectCallbackFunction callback, void* userData = null);
/// Creates an effect with a custom callback processing function.
/// (All effects get destroyed automatically when the IMixer is destroyed).
IAudioEffect createEffectGain();
/// Returns: Time in seconds since the beginning of playback.
/// This is equal to `getTimeInFrames() / getSampleRate() - latency`.
/// Warning: Because this subtract known latency, this can return a negative value.
/// BUG: latency reported of libsoundio is too high for WASAPI, so we have an incorrect value here.
double playbackTimeInSeconds();
/// Returns: Playback sample rate.
/// Once created, this is guaranteed to never change.
float getSampleRate();
/// Returns: `true` if a playback error has been detected.
/// Your best bet is to recreate a `Mixer`.
bool isErrored();
/// Returns: An error message for the last error.
/// Warning: only call this if `isErrored()` returns `true`.
const(char)[] lastErrorString();
/// Manual output instead of a libsoundio-d stream.
/// You can only call this if the mixer is created with the `isLoopback` option.
void loopbackGenerate(float*[2] outBuffers, int frames);
void loopbackMix(float*[2] inoutBuffers, int frames); ///ditto
}
package:
/// Package API for the `Mixer` object.
interface IMixerInternal
{
nothrow:
@nogc:
float getSampleRate();
}
/// Implementation of `IMixer`.
private final class Mixer : IMixer, IMixerInternal
{
nothrow:
@nogc:
public:
this(MixerOptions options)
{
_isLoopback = options.isLoopback;
version(onlyLoopback)
{
// If you fail here, you've used a "only loopback" configuration, and then tried to obtain a IMixer with sound I/O.
assert(_isLoopback);
}
_channelVolumeSecs = options.channelVolumeSecs;
_channels.resize(options.numChannels);
for (int n = 0; n < options.numChannels; ++n)
_channels[n] = mallocNew!ChannelStatus(n);
int err = 0;
version(hasSoundIO)
{
if (!isLoopback)
{
_soundio = soundio_create();
assert(_soundio !is null);
err = soundio_connect(_soundio);
if (err != 0)
{
setErrored("Out of memory");
_lastError = "Out of memory";
return;
}
soundio_flush_events(_soundio);
int default_out_device_index = soundio_default_output_device_index(_soundio);
if (default_out_device_index < 0)
{
setErrored("No output device found");
return;
}
_device = soundio_get_output_device(_soundio, default_out_device_index);
if (!_device)
{
setErrored("Out of memory");
return;
}
if (!soundio_device_supports_format(_device, SoundIoFormatFloat32NE))
{
setErrored("Must support 32-bit float output");
return;
}
}
}
_masterEffectsMutex = makeMutex();
_channelsMutex = makeMutex();
version(hasSoundIO)
{
if (!isLoopback)
{
_outstream = soundio_outstream_create(_device);
_outstream.format = SoundIoFormatFloat32NE; // little endian floats
_outstream.write_callback = &mixerWriteCallback;
_outstream.userdata = cast(void*)this;
_outstream.sample_rate = cast(int) options.sampleRate;
_outstream.software_latency = 0.010; // 10ms
err = soundio_outstream_open(_outstream);
if (err != 0)
{
setErrored("Unable to open device");
return;
}
if (_outstream.layout_error)
{
setErrored("Unable to set channel layout");
return;
}
}
}
_framesElapsed = 0;
_timeSincePlaybackBegan = 0;
version(hasSoundIO)
{
if (isLoopback)
_sampleRate = options.sampleRate;
else
_sampleRate = _outstream.sample_rate;
}
else
{
_sampleRate = options.sampleRate;
}
// TODO: do something better in WASAPI
// do something better when latency reporting works
if (isLoopback)
_softwareLatency = 0;
else
_softwareLatency = (maxInternalBuffering / _sampleRate);
// The very last effect of the master chain is a global gain.
_masterGainPostFx = createEffectGain();
_masterGainPostFxContext.initialized = false;
version(hasSoundIO)
{
if (!isLoopback)
{
err = soundio_outstream_start(_outstream);
if (err != 0)
{
setErrored("Unable to start device");
return;
}
// start event thread
_eventThread = makeThread(&waitEvents);
_eventThread.start();
}
}
}
~this()
{
setMasterVolume(0);
if (!isLoopback)
{
core.thread.Thread.sleep( dur!("msecs")( 200 ) );
}
cleanUp();
}
/// Returns: Time in seconds since the beginning of playback.
/// This is equal to `getTimeInFrames() / getSampleRate() - softwareLatency()`.
/// Warning: This is returned with some amount of latency.
override double playbackTimeInSeconds()
{
double sr = getSampleRate();
long t = playbackTimeInFrames();
return t / sr - _softwareLatency;
}
/// Returns: Playback sample rate.
override float getSampleRate()
{
return _sampleRate;
}
override bool isErrored()
{
return _errored;
}
override const(char)[] lastErrorString()
{
assert(isErrored);
return _lastError;
}
override void addMasterEffect(IAudioEffect effect)
{
_masterEffectsMutex.lock();
_masterEffects.pushBack(effect);
_masterEffectsContexts.pushBack(EffectContext(false));
_masterEffectsMutex.unlock();
}
override IAudioEffect createEffectCustom(EffectCallbackFunction callback, void* userData)
{
IAudioEffect fx = mallocNew!EffectCallback(callback, userData);
_allCreatedEffects.pushBack(fx);
return fx;
}
override IAudioEffect createEffectGain()
{
IAudioEffect fx = mallocNew!EffectGain();
_allCreatedEffects.pushBack(fx);
return fx;
}
override IAudioSource createSourceFromMemory(const(ubyte[]) inputData)
{
try
{
IAudioSource s = mallocNew!AudioSource(this, inputData);
_allCreatedSource.pushBack(s);
return s;
}
catch(Exception e)
{
destroyFree(e); // TODO maybe leaks
return null;
}
}
override IAudioSource createSourceFromFile(const(char[]) path)
{
try
{
IAudioSource s = mallocNew!AudioSource(this, path);
_allCreatedSource.pushBack(s);
return s;
}
catch(Exception e)
{
destroyFree(e); // TODO maybe leaks
return null;
}
}
override void setMasterVolume(float volume)
{
_masterGainPostFx.parameter(0).setValue(volume);
}
override void setChannelVolume(int channel, float volume)
{
_channels[channel].setVolume(volume);
}
override void play(IAudioSource source, float volume)
{
PlayOptions opt;
opt.volume = volume;
play(source, opt);
}
override void play(IAudioSource source, PlayOptions options)
{
_channelsMutex.lock();
_channelsMutex.unlock();
playInternal(source, options);
}
override void playSimultaneously(IAudioSource[] sources, PlayOptions[] options)
{
_channelsMutex.lock();
_channelsMutex.unlock();
assert(sources.length == options.length);
for (int n = 0; n < sources.length; ++n)
playInternal(sources[n], options[n]);
}
override void stopChannel(int channel, float fadeOutSecs)
{
_channels[channel].stop(fadeOutSecs);
}
override void stopAllChannels(float fadeOutSecs)
{
for (int chan = 0; chan < _channels.length; ++chan)
_channels[chan].stop(fadeOutSecs);
}
long playbackTimeInFrames()
{
return atomicLoad(_timeSincePlaybackBegan);
}
override void loopbackGenerate(float*[2] outBuffers, int frames)
{
// Can't use loopbackGenerate if the IMixer is not created solely for loopback output.
assert(isLoopback);
const(float*[2]) mixedBuffers = loopbackCallback(frames);
outBuffers[0][0..frames] = mixedBuffers[0][0..frames];
outBuffers[1][0..frames] = mixedBuffers[1][0..frames];
}
override void loopbackMix(float*[2] inoutBuffers, int frames)
{
// Can't use loopbackMix if the IMixer is not created solely for loopback output.
assert(isLoopback);
const(float*[2]) mixedBuffers = loopbackCallback(frames);
inoutBuffers[0][0..frames] += mixedBuffers[0][0..frames];
inoutBuffers[1][0..frames] += mixedBuffers[1][0..frames];
}
bool isLoopback()
{
return _isLoopback;
}
private:
bool _isLoopback;
version(hasSoundIO)
{
SoundIo* _soundio; // null if loopback
SoundIoDevice* _device; // null if loopback
SoundIoOutStream* _outstream; // null if loopback
dplug.core.thread.Thread _eventThread;
}
long _framesElapsed;
shared(long) _timeSincePlaybackBegan;
float _sampleRate;
double _softwareLatency;
float _channelVolumeSecs;
static struct EffectContext
{
bool initialized;
}
Vec!EffectContext _masterEffectsContexts; // sync by _masterEffectsMutex
Vec!IAudioEffect _masterEffects;
UncheckedMutex _masterEffectsMutex;
Vec!IAudioEffect _allCreatedEffects;
Vec!IAudioSource _allCreatedSource;
IAudioEffect _masterGainPostFx;
EffectContext _masterGainPostFxContext;
bool _errored;
const(char)[] _lastError;
AudioBuffer!float _sumBuf;
shared(bool) _shouldReadEvents = true;
Vec!ChannelStatus _channels;
UncheckedMutex _channelsMutex;
int findFreeChannel()
{
for (int c = 0; c < _channels.length; ++c)
if (_channels[c].isAvailable())
return c;
return -1;
}
version(hasSoundIO)
{
void waitEvents()
{
assert(!_isLoopback); // no event thread in loopback mode
// This function calls ::soundio_flush_events then blocks until another event is ready
// or you call ::soundio_wakeup. Be ready for spurious wakeups.
while (true)
{
bool shouldReadEvents = atomicLoad(_shouldReadEvents);
if (!shouldReadEvents)
break;
soundio_wait_events(_soundio);
}
}
}
void setErrored(const(char)[] msg)
{
_errored = true;
_lastError = msg;
}
void playInternal(IAudioSource source, PlayOptions options)
{
int chan = options.channel;
if (chan == -1)
chan = findFreeChannel();
if (chan == -1)
return; // no free channel
if (chan >= _channels.length)
{
assert(false); // specified non-existing channel index
}
float pan = options.pan;
if (pan < -1) pan = -1;
if (pan > 1) pan = 1;
float volumeL = options.volume * fast_cos((pan + 1) * PI_4) * SQRT2;
float volumeR = options.volume * fast_sin((pan + 1) * PI_4) * SQRT2;
int delayBeforePlayFrames = cast(int)(0.5 + options.delayBeforePlay * _sampleRate);
int frameOffset = -delayBeforePlayFrames;
int startTimeFrames = cast(int)(0.5 + options.startTimeSecs * _sampleRate);
if (startTimeFrames != 0)
frameOffset = startTimeFrames;
// API wrong usage, can't use both delayBeforePlayFrames and startTimeSecs.
assert ((startTimeFrames == 0) || (delayBeforePlayFrames == 0));
double crossFadeInSecs = options.crossFadeInSecs;
double crossFadeOutSecs = options.crossFadeOutSecs;
double fadeInSecs = options.fadeInSecs;
_channels[chan].startPlaying(source, volumeL, volumeR, frameOffset, options.loopCount,
crossFadeInSecs, crossFadeOutSecs, fadeInSecs);
IAudioSourceInternal isource = cast(IAudioSourceInternal) source;
assert(isource);
isource.prepareToPlay();
}
void cleanUp()
{
// remove effects
_masterEffectsMutex.lock();
_masterEffects.clearContents();
_masterEffectsMutex.unlock();
version(hasSoundIO)
{
if (_outstream !is null)
{
assert(!_isLoopback);
soundio_outstream_destroy(_outstream);
_outstream = null;
}
if (_eventThread.getThreadID() !is null)
{
atomicStore(_shouldReadEvents, false);
soundio_wakeup(_soundio);
_eventThread.join();
destroyNoGC(_eventThread);
}
if (_device !is null)
{
soundio_device_unref(_device);
_device = null;
}
if (_soundio !is null)
{
soundio_destroy(_soundio);
_soundio = null;
}
}
// Destroy all effects
foreach(fx; _allCreatedEffects)
{
destroyFree(fx);
}
_allCreatedEffects.clearContents();
for (int c = 0; c < _channels.length; ++c)
_channels[c].destroyFree();
}
const(float*[2]) loopbackCallback(int frames)
{
// Extend storage if need be.
if (frames > _sumBuf.frames())
{
_sumBuf.resize(2, frames);
}
// Take the fisrt `frames` frames as current buf.
AudioBuffer!float masterBuf = _sumBuf.sliceFrames(0, frames);
// 1. Mix sources in stereo.
masterBuf.fillWithZeroes();
float*[2] inoutBuffers;
inoutBuffers[0] = masterBuf.getChannelPointer(0);
inoutBuffers[1] = masterBuf.getChannelPointer(1);
_channelsMutex.lock(); // to protect from "play"
for (int n = 0; n < _channels.length; ++n)
{
ChannelStatus* cs = &_channels[n];
cs.produceSound(inoutBuffers, masterBuf.frames(), _sampleRate, this);
}
_channelsMutex.unlock();
// 2. Apply master effects
_masterEffectsMutex.lock();
int numMasterEffects = cast(int) _masterEffects.length;
for (int numFx = 0; numFx < numMasterEffects; ++numFx)
{
applyEffect(masterBuf, _masterEffectsContexts[numFx], _masterEffects[numFx], frames);
}
_masterEffectsMutex.unlock();
// Apply post gain effect
applyEffect(masterBuf, _masterGainPostFxContext, _masterGainPostFx, frames);
_framesElapsed += frames;
atomicStore(_timeSincePlaybackBegan, _framesElapsed);
return inoutBuffers;
}
version(hasSoundIO)
{
void writeCallback(SoundIoOutStream* stream, int frames)
{
assert(stream.sample_rate == _sampleRate);
SoundIoChannelArea* areas;
// 1. Generate next `frames` stereo frames.
const(float*[2]) mixedBuffers = loopbackCallback(frames);
// 2. Pass the audio to libsoundio
int frames_left = frames;
for (;;)
{
int frame_count = frames_left;
if (auto err = soundio_outstream_begin_write(_outstream, &areas, &frame_count))
{
assert(false, "unrecoverable stream error");
}
if (!frame_count)
break;
const(SoundIoChannelLayout)* layout = &stream.layout;
for (int frame = 0; frame < frame_count; frame += 1)
{
for (int channel = 0; channel < layout.channel_count; channel += 1)
{
float sample = _sumBuf[channel][frame];
write_sample_float32ne(areas[channel].ptr, sample);
areas[channel].ptr += areas[channel].step;
}
}
if (auto err = soundio_outstream_end_write(stream))
{
if (err == SoundIoError.Underflow)
return;
setErrored("Unrecoverable stream error");
return;
}
frames_left -= frame_count;
if (frames_left <= 0)
break;
}
}
}
void applyEffect(ref AudioBuffer!float inoutBuf, ref EffectContext ec, IAudioEffect effect, int frames)
{
enum int MAX_FRAMES_FOR_EFFECTS = 512; // TODO: should disappear in favor of maxInternalBuffering
if (!ec.initialized)
{
effect.prepareToPlay(_sampleRate, MAX_FRAMES_FOR_EFFECTS, 2);
ec.initialized = true;
}
EffectCallbackInfo info;
info.sampleRate = _sampleRate;
info.userData = null;
// Buffer-splitting! It is used so that effects can be given a maximum buffer size at init point.
int framesDone = 0;
foreach( block; inoutBuf.chunkBy(MAX_FRAMES_FOR_EFFECTS))
{
info.timeInFramesSincePlaybackStarted = _framesElapsed + framesDone;
effect.processAudio(block, info); // apply effect
framesDone += block.frames();
assert(framesDone <= inoutBuf.frames());
}
}
}
private:
enum int maxInternalBuffering = 1024; // Allows to lower latency with WASAPI
version(hasSoundIO)
{
extern(C) void mixerWriteCallback(SoundIoOutStream* stream, int frame_count_min, int frame_count_max)
{
Mixer mixer = cast(Mixer)(stream.userdata);
// Note: WASAPI can have 4 seconds buffers, so we return as frames as following:
// - the highest nearest valid frame count in [frame_count_min .. frame_count_max] that is below 1024.
int frames = maxInternalBuffering;
if (frames < frame_count_min) frames = frame_count_min;
if (frames > frame_count_max) frames = frame_count_max;
mixer.writeCallback(stream, frames);
}
static void write_sample_s16ne(char* ptr, double sample) {
short* buf = cast(short*)ptr;
double range = cast(double)short.max - cast(double)short.min;
double val = sample * range / 2.0;
*buf = cast(short) val;
}
static void write_sample_s32ne(char* ptr, double sample) {
int* buf = cast(int*)ptr;
double range = cast(double)int.max - cast(double)int.min;
double val = sample * range / 2.0;
*buf = cast(int) val;
}
static void write_sample_float32ne(char* ptr, double sample) {
float* buf = cast(float*)ptr;
*buf = sample;
}
static void write_sample_float64ne(char* ptr, double sample) {
double* buf = cast(double*)ptr;
*buf = sample;
}
}
// A channel can be in one of four states:
enum ChannelState
{
idle,
fadingIn,
normalPlay,
fadingOut
}
/// Internal status of single channel.
/// In reality, a channel support multiple sounds playing at once, in order to support cross-fades.
final class ChannelStatus
{
nothrow:
@nogc:
public:
this(int channelIndex)
{
}
/// Returns: true if no sound is playing or scheduled to play on this channel
bool isAvailable()
{
for (int nsound = 0; nsound < MAX_SOUND_PER_CHANNEL; ++nsound)
{
if (_sounds[nsound].isPlayingOrPending())
return false;
}
return true;
}
~this()
{
_volumeRamp.reallocBuffer(0);
}
// Change the currently playing source in this channel.
void startPlaying(IAudioSource source,
float volumeL,
float volumeR,
int frameOffset,
uint loopCount,
float crossFadeInSecs,
float crossFadeOutSecs,
float fadeInSecs)
{
// shift sound to keep most recently played
for (int n = MAX_SOUND_PER_CHANNEL - 1; n > 0; --n)
{
_sounds[n] = _sounds[n-1];
}
VolumeState _state;
float _currentFadeVolume = 1.0f;
float _fadeInDuration = 0.0f;
float _fadeOutDuration = 0.0f;
// Note: _sounds[0] is here to replace _sounds[1]. _sounds[2] and later, if playing, were already fadeouting.
with (_sounds[0])
{
_sourcePlaying = source;
_volume[0] = volumeL;
_volume[1] = volumeR;
_frameOffset = frameOffset;
_loopCount = loopCount;
if (_sounds[1].isPlaying())
{
// There is another sound already playing, AND it has started
_sounds[1].stopPlayingFadeOut(crossFadeOutSecs);
startFadeIn(crossFadeInSecs);
}
else if (_sounds[1].isPlayingOrPending())
{
startFadeIn(fadeInSecs);
_sounds[1].stopPlayingImmediately();
}
else
{
startFadeIn(fadeInSecs);
}
}
}
void stop(float fadeOutSecs)
{
for (int n = 0; n < MAX_SOUND_PER_CHANNEL; ++n)
{
_sounds[n].stopPlayingFadeOut(fadeOutSecs);
}
}
void produceSound(float*[2] inoutBuffers, int frames, float sampleRate, Mixer mixer)
{
// Compute channel volume ramp (if any)
bool hasChannelVolumeRamp = (_channelVolume != 1.0f) || (_currentChannelVolume != 1.0f);
bool hasConstantChannelVolume = false;
if (hasChannelVolumeRamp)
{
if (_chanVolumeRamp.length < frames)
_chanVolumeRamp.reallocBuffer(frames);
float v = _currentChannelVolume; // RACE: technically, should be a raw atomic
float target = _channelVolume;
float diff = target - v;
// do we need to recompute the ramp? Or stable.
if (v != target)
{
float channelFaderSecs = mixer._channelVolumeSecs; // time for volume change for the channel
float chanIncrement = 1.0 / (sampleRate * channelFaderSecs);
for (int n = 0; n < frames; ++n)
{
if (diff > 0)
{
v += chanIncrement;
if (v > target)
v = target;
}
else
{
v -= chanIncrement;
if (v < target)
v = target;
}
_chanVolumeRamp[n] = v;
}
_currentChannelVolume = v;
}
else
{
hasConstantChannelVolume = true; // instead, just multiply by constant volume
}
}
for (int nsound = 0; nsound < MAX_SOUND_PER_CHANNEL; ++nsound)
{
SoundPlaying* sp = &_sounds[nsound];
if (sp._loopCount != 0)
{
// deals with negative frameOffset
if (sp._frameOffset + frames <= 0)
{
sp._frameOffset += frames;
}
else
{
if (sp._frameOffset < 0)
{
// Adjust to only a smaller subpart of the beginning of the source.
int skip = -sp._frameOffset;
frames -= skip;
sp._frameOffset = 0;
for (int chan = 0; chan < 2; ++chan)
inoutBuffers[chan] += skip;
}
if (_volumeRamp.length < frames)