Repository navigation
Expand file tree
/
Copy pathApus.Engine.Sound.pas
More file actions
1818 lines (1679 loc) · 54.6 KB
/
Copy pathApus.Engine.Sound.pas
File metadata and controls
1818 lines (1679 loc) · 54.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) Ivan Polyacov, Apus Software (ivan@apus-software.com)
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
// Events syntax:
// Sound\Play\EventName[,param1=value1,...,paramN=valueN]
// Start playing sample defined by EventName
// Parameters can override default playback settings
//
// Sound\PlayMusic\MusicName
//
// Sound\PlayFile\Path[,vol=N][,group=Name]
// Load a file (VFS path, not inside the audio folder) and play it once as a sample;
// it is unloaded when finished. Group "file" is used by default
// Sound\StopFile\Path, Sound\StopGroup\Name, Sound\StopAllFiles (= StopGroup\file)
// Stop file playback (short fade-out), no notification is sent
// Sound\SetGroup\Name[,duck=N][,exclusive=0|1]
// Group playback policy: duck = music volume (in %) while any file of the group plays,
// exclusive = a new file stops other files of the group. Default: no ducking, not exclusive
// Sound\ClearCache[\EventName]
// Unload the sample of this event (or all samples): it is loaded again when played
//
// Outgoing: Sound\FilePlayed\Path - a file played to the end (not sent if it was stopped)
//
{$I defines.inc}
unit Apus.Engine.Sound;
interface
uses Apus.Core, Apus.Types, Apus.AnimatedValues;
var
soundFolderPath:string8 = 'Audio\';
soundConfigFile:string8 = 'sounds.ctl';
type
TSoundLib = (
slDefault, // platform default selection
slNative, // AndroidSoundPool / AVAudioPlayer
slIMixer, // IMixerPro (ImxEx.dll, Win32-only)
slBass, // BASS (bass.dll)
slSDL); // SDL Mixer
TMediaLoadingMode = (
mlmJustOpen, // open file but don't load its content
mlmLoad, // load file content, don't unpack it
mlmLoadUnpack); // load and unpack data
TVolumeType = (
vtSounds, // sounds volume
vtMusic); // music volume (streams and modules)
TChannelAttribute = (
caVolume, // relative volume (0..1)
caPanning, // -1=left, 1=right
caSpeed); // 1.0 - normal speed
TChannelAttributes = set of TChannelAttribute;
// Playback handle: an opaque value, 0 = no playback. ISoundSystem and the backend
// (ISoundLib) give out handles of their own. A handle is not reused right after its
// playback ends, so a stale handle stays safe for a reasonable time: IsPlaying
// returns false and other operations ignore it
TChannel=type cardinal;
TMediaFile=class
source:string;
numChannels,sampleRate,bitDepth:integer;
duration:single; // in seconds
procedure DetectParams(fName:string); overload;
procedure DetectParams(data:TBuffer); overload;
end;
TPlaySettings=record
volume,pan,speed:single;
loop:boolean;
// Loop region in seconds of the media file: a looped playback continues from
// loopStart when it reaches loopEnd (0 = the end of the file). Seconds stay
// valid when the file is resampled; double keeps sample positions exact
loopStart,loopEnd:double;
startPos:double; // music: position to start from, seconds
end;
const
DefaultSettings:TPlaySettings=(
volume: 1.0;
pan:0;
speed:1.0;
loop:false;
loopStart:0;
loopEnd:0;
startPos:0;
);
type
// Generates the next piece of a procedural sound into data: count values per
// channel, interleaved (stereo: L,R,L,R...), in -1..1, sampleRate values per
// second for each channel, so data holds count*channels singles.
// Called in the audio thread: no allocations, logging, exceptions or waiting for
// locks the game thread may hold; read the game's parameters through atomics.
// Return false when the sound is over: playback stops after this piece.
// A stopped stream fades out over a few milliseconds and the procedure is still
// called meanwhile: userData must stay valid until IsPlaying turns false.
TSoundStreamProc=function(data:PSingle;count,channels,sampleRate:integer;userData:pointer):boolean;
// Interface for the backend sound library (API)
ISoundLib=interface
procedure Init(windowHandle:THandle=0);
procedure SetVolume(volumeType:TVolumeType;volume:single); // 0..1
function OpenMediaFile(fname:string;mode:TMediaLoadingMode):TMediaFile;
function PlayMedia(media:TMediaFile;const settings:TPlaySettings):TChannel;
// Start a procedural sound: it's mixed as a sample
function PlayStream(proc:TSoundStreamProc;userData:pointer;channels:integer;volume:single):TChannel;
// Stops playback and clears the handle
procedure StopChannel(var channel:TChannel);
procedure SetChannelAttribute(channel:TChannel;attr:TChannelAttribute;value:single);
// Which channel attributes can be slided
function CanSlide:TChannelAttributes;
// If full volume slide not supported: can it fade in/out music?
function CanFadeMusic:boolean;
// Can several music streams play at the same time? If not, starting a new
// track implicitly ends the previous one.
function HasSingleMusicStream:boolean;
// Is this playback still going on? (paused counts as playing, a stale handle yields false)
function IsPlaying(channel:TChannel):boolean;
// timeInterval - in seconds
procedure SlideChannel(channel:TChannel;attr:TChannelAttribute;newValue:single;timeInterval:single);
// Pause/resume everything that plays (e.g. when the application loses focus)
procedure Pause(pause:boolean);
// Housekeeping, called by the sound thread on every cycle
procedure Update;
procedure Done;
end;
// Game-side sound API (the backend interface is ISoundLib). Calls from any thread
// return at once: the work is done by the sound thread, so a handle can refer to
// a playback that has not started yet. The Sound\... events do the same work
ISoundSystem=interface
// Start the sound thread with this backend (slDefault - whichever is compiled
// in) and load the configuration soundConfigFile
procedure Init(useLibrary:TSoundLib=slDefault;windowHandle:THandle=0;waitForPreload:boolean=true);
procedure Done;
// Global
procedure SetVolume(volumeType:TVolumeType;volume:single); // 0..1
procedure Pause(pause:boolean);
// Samples: events of the config (Sound\Play). Volume and speed multiply the
// configured values, pan is added to the configured one
function Play(const event:String8;volume:single=1;pan:single=0;speed:single=1):TChannel;
procedure ClearCache(const event:String8=''); // '' = all samples
// Music (Sound\PlayMusic): fadeOut - of the current track, startAfter - delay of
// the new one (when something plays), fadeIn - of the new one, all in seconds;
// fromPos - position in the new track (sec), restart - even if it already plays
procedure PlayMusic(const name:String8;fadeOut:single=1.2;startAfter:single=1;fadeIn:single=0;
fromPos:double=0;restart:boolean=false);
procedure StopMusic(fadeOut:single=1.2);
// Is a music track playing right now? (the sound thread can change it at any moment)
function IsMusicPlaying:boolean;
// Files outside the config (Sound\PlayFile): played once, unloaded when finished
function PlayFile(const path:String8;volume:single=1;const group:String8='file'):TChannel;
procedure StopFile(const path:String8);
procedure StopGroup(const group:String8);
// Playback policy of a file group (Sound\SetGroup): duck - music volume (0..1)
// while a file of the group plays, exclusive - a new file stops the others
procedure SetGroup(const group:String8;duck:single=1;exclusive:boolean=false);
// Procedural sound: mixed with the samples, follows the sounds volume and pause
function PlayStream(proc:TSoundStreamProc;userData:pointer;channels:integer=2;volume:single=1):TChannel;
// Any playback started above; time>0 changes the value smoothly over time seconds
procedure SetChannelVolume(channel:TChannel;volume:single;time:single=0); // 1 = as started
procedure SetChannelPan(channel:TChannel;pan:single;time:single=0); // -1 = left, 1 = right
procedure SetChannelSpeed(channel:TChannel;speed:single;time:single=0); // 1 = original speed (and pitch)
// Stop with a short fade-out (a cut would click) and clear the handle;
// IsPlaying of a copy of the handle turns false when the fade-out is over
procedure StopChannel(var channel:TChannel);
function IsPlaying(channel:TChannel):boolean;
end;
var
sound:ISoundSystem; // always assigned; without a backend the calls do nothing
implementation
// The old Java SoundPool/MediaPlayer path is opt-in until it is migrated away
// from the removed MyServis API. SDL-first Android builds currently defer audio.
uses SysUtils, Apus.Config, Apus.HashMaps, Apus.Utils, Apus.EventMan, Classes
{$IFDEF IMX},Apus.Engine.SoundImx{$ENDIF}
{$IFDEF SDLMIX},Apus.Engine.SoundSDL{$ENDIF}
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_LEGACY_AUDIO)},Apus.Android,Apus.AndroidSoundPool,Apus.AndroidMediaPlayer{$IFEND}
,
Apus.Conv,
Apus.Files,
Apus.Log,
Apus.Strings,
Apus.Threads;
type
// Sound event: play sound sample
TSoundEvent=class
name:string; // Sound\Play event name
fileName:string; // name inside audio folder
sample:TMediaFile; // can be shared across multiple events
// default playback settings
volume, // 1.0 = original volume (can be >1)
pan, // -1.0 - full left, 0.0 - center, 1.0 - full right
speed:single; // 1.0 - original rate
loop:boolean;
lastChannel:TChannel; // used to control playback of the last instance
constructor Create(name:string);
procedure Preload;
end;
// Music entry (audio stream file or module)
TMusicEntry=class
name:string; // Sound\PlayMusic entry name
media:TMediaFile;
volume:single; // Required relative volume (1.0=normal volume), actual volume may be different
isModule:boolean;
channel:TChannel;
stopTime:int64; // stop channel at this time
loopPos:double; // loop start in seconds, see TPlaySettings
loop:boolean;
curVolume:TAnimatedValue;
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_LEGACY_AUDIO)}
player:TJNIMediaPlayer;
{$IFEND}
end;
// Group of file playbacks: the playback policy belongs to the group, not to the verbs
TFileGroup=class
name:string8; // uppercase
duck:single; // music volume factor while a file of the group plays (1.0 = no ducking)
exclusive:boolean; // a new file stops the other files of the group
end;
// One-shot file playback (Sound\PlayFile)
TFilePlayback=class
path:string8; // as given by the caller: Sound\FilePlayed carries it back
group:TFileGroup;
media:TMediaFile; // owned: unloaded together with the playback
channel:TChannel;
stopped:boolean; // stopped explicitly: fading out, no notification
destructor Destroy; override;
end;
// Thread processing sound events
TSoundThread=class(TThread)
waitForPreload:boolean;
procedure Execute; override;
end;
TVoiceState=(vsFree,vsPending,vsPlaying);
// Playback started through ISoundSystem: its handle is given out at once, and the
// sound thread binds it to a backend channel when it runs the command
TVoice=record
generation:cardinal; // bumped on every new playback, so older handles of the voice become stale
state:TVoiceState; // changed under soundLock
// sound thread only
channel:TChannel; // backend channel
baseVolume:single; // volume the playback started with
sliding:TChannelAttributes; // slides the backend can't do: animated in UpdateVoices
volume,pan:TAnimatedValue;
end;
TCommandKind=(ckPlay,ckPlayFile,ckPlayStream,ckPlayMusic,ckStopMusic,ckStopFile,
ckStopGroup,ckSetGroup,ckClearCache,ckSetVolume,ckPause,ckSetChannel,ckStopChannel);
// ISoundSystem call for the sound thread
TSoundCommand=record
kind:TCommandKind;
voice:TChannel; // ISoundSystem handle of the playback
name,group:String8;
a,b,c:single; // numeric parameters in the order of the ISoundSystem method
pos:double;
flag:boolean;
attr:TChannelAttribute;
volumeType:TVolumeType;
proc:TSoundStreamProc;
userData:pointer;
channels:integer;
end;
TSoundCommands=array of TSoundCommand;
TSoundSystem=class(TInterfacedObject,ISoundSystem)
procedure Init(useLibrary:TSoundLib;windowHandle:THandle;waitForPreload:boolean);
procedure Done;
procedure SetVolume(volumeType:TVolumeType;volume:single);
procedure Pause(pause:boolean);
function Play(const event:String8;volume,pan,speed:single):TChannel;
procedure ClearCache(const event:String8);
procedure PlayMusic(const name:String8;fadeOut,startAfter,fadeIn:single;fromPos:double;restart:boolean);
procedure StopMusic(fadeOut:single);
function IsMusicPlaying:boolean;
function PlayFile(const path:String8;volume:single;const group:String8):TChannel;
procedure StopFile(const path:String8);
procedure StopGroup(const group:String8);
procedure SetGroup(const group:String8;duck:single;exclusive:boolean);
function PlayStream(proc:TSoundStreamProc;userData:pointer;channels:integer;volume:single):TChannel;
procedure SetChannelVolume(channel:TChannel;volume,time:single);
procedure SetChannelPan(channel:TChannel;pan,time:single);
procedure SetChannelSpeed(channel:TChannel;speed,time:single);
procedure StopChannel(var channel:TChannel);
function IsPlaying(channel:TChannel):boolean;
private
// Queue the command for the sound thread; newVoice - it starts a playback: returns its handle
function Post(var cmd:TSoundCommand;newVoice:boolean=false):TChannel;
procedure SetAttribute(channel:TChannel;attr:TChannelAttribute;value,time:single);
end;
const
DEFAULT_FILE_GROUP = 'FILE';
FILE_FADE_TIME = 0.1; // fade-out of a stopped file (sec)
DUCK_DOWN_TIME = 1000; // music ducking (ms)
DUCK_RESTORE_TIME = 1500;
// ISoundSystem handle layout: low 8 bits = voice index+1 (so 0 is "no playback"),
// high 24 bits = generation of the voice
MAX_VOICES = 255;
VOICE_BITS = 8;
VOICE_MASK = $FF;
GENERATION_MASK = $FFFFFF;
var
soundLib:ISoundLib;
// Written by the sound thread, read by the main thread: touch them only
// through RaiseFlag/FlagIsSet so that the access is atomic on every platform
initialized:integer=0; // ready to process events
failed:integer=0;
soundThread:TSoundThread;
wndHandle:THandle=0;
evtHash:TStrHash; // event -> TSoundEvent
musHash:TStrHash; // event -> TMusicEntry
mediaFilesHash:TSimpleHashS; // Files.FixName (uppercase) -> TMediaFile
// Need to start this music entry with these parameters
needMusic:TMusicEntry;
needMusicPlayFrom:double; // position to play from (sec)
needMusicStartTime:int64; // Time to start playback
needSlide:integer; // Fade-in duration (ms)
curMusic:TMusicEntry;
// Global volume levels (multiply by particular volume)
soundVolume:single=1.0;
musicVolume:single=1.0;
// File playback (sound thread only)
fileGroups:array of TFileGroup;
filePlaybacks:array of TFilePlayback;
musicDuck:TAnimatedValue; // music volume factor requested by playing files
appliedDuck:single=1.0; // the factor music volume is currently set with
// ISoundSystem: the queue of calls and the playbacks they started
soundLock:TLock;
commands:TSoundCommands;
voices:array[0..MAX_VOICES-1] of TVoice;
musicPlaying:integer; // published by the sound thread for IsMusicPlaying
// Cross-thread boolean flags
procedure RaiseFlag(var flag:integer); inline;
begin
Atomic.Exchange(flag,1);
end;
function FlagIsSet(var flag:integer):boolean; inline;
begin
result:=Atomic.CmpExchange(flag,0,0)<>0;
end;
// Sample rate of a media file with a safe fallback: it is used as a divisor,
// and some formats can leave it unknown
function SampleRateOf(media:TMediaFile):integer;
begin
result:=media.sampleRate;
if result<=0 then result:=44100;
end;
{ TMediaFile }
procedure TMediaFile.DetectParams(data:TBuffer);
procedure ParseWAV;
begin
data.Skip(4);
if data.ReadUInt<>$45564157 {'WAVE'} then raise EError.Create('Invalid WAV format');
if data.ReadUInt<>$20746d66 {'fmt '} then raise EError.Create('Unrecognized WAV format');
data.Skip(6);
numChannels:=data.ReadWord;
sampleRate:=data.ReadInt;
data.Skip(6);
bitDepth:=data.ReadWord;
duration:=0;
if data.ReadUInt=$61746164 then
duration:=data.ReadInt div (sampleRate*numChannels*bitDepth div 8);
end;
procedure ParseOGG;
begin
data.Seek($27);
numChannels:=data.ReadByte;
sampleRate:=data.ReadInt;
bitDepth:=16;
duration:=0; // not easy to parse
end;
procedure ParseMP3;
const
// [version][sample rate index]
rates:array[0..3,0..2] of integer=(
(11025,12000,8000), // MPEG 2.5
(0,0,0), // reserved
(22050,24000,16000), // MPEG 2
(44100,48000,32000)); // MPEG 1
var
i,ver,srIndex,mode:integer;
pc:PAnsiChar;
begin
numChannels:=2;
sampleRate:=0;
bitDepth:=16;
duration:=0; // needs the whole file (or a VBR header) to be known
// Scan for the first frame header (11 sync bits): it can be preceded by an ID3 tag
pc:=PAnsiChar(data.data);
for i:=0 to data.size-4 do begin
if (ord(pc[i])=$FF) and (ord(pc[i+1]) and $E0=$E0) then begin
ver:=(ord(pc[i+1]) shr 3) and 3;
srIndex:=(ord(pc[i+2]) shr 2) and 3;
if (ver=1) or (srIndex=3) then continue; // reserved values: not a frame header
sampleRate:=rates[ver,srIndex];
mode:=(ord(pc[i+3]) shr 6) and 3;
if mode=3 then numChannels:=1; // single channel
break;
end;
end;
if sampleRate=0 then Log.Warn('[SOUND] MP3 frame header not found');
end;
var
c:cardinal;
begin
ASSERT(data.size>100);
c:=data.ReadUInt;
if c=$5367674F then ParseOGG
else
if c=$46464952 then ParseWAV
else
if ((c and $FF=$FF) and ((c shr 8) and $E0=$E0)) or (c=$03334449) then ParseMP3;
end;
procedure TMediaFile.DetectParams(fName: string);
var
data:ByteArray;
begin
data:=Files.LoadAsBytes(fName,2000);
DetectParams(TBuffer.CreateFrom(data));
end;
// Load media file and put it's reference to the mediaFilesHash
function LoadMediaAsSample(fName:string):TMediaFile;
var
st:string;
begin
st:=Files.FixName(soundFolderPath+fName);
Log.Msg('[SOUND] Load sample from '+st);
result:=soundLib.OpenMediaFile(st,mlmLoadUnpack);
if result<>nil then
mediaFilesHash.Put(UpperCase {TODO: use st.ToUpper}(fName),UIntPtr(result));
end;
constructor TSoundEvent.Create(name: string);
begin
self.name:=name;
volume:=DefaultSettings.volume;
pan:=DefaultSettings.pan;
speed:=DefaultSettings.speed;
loop:=false;
end;
procedure TSoundEvent.Preload;
var
p:int64;
begin
if sample=nil then begin
p:=mediaFilesHash.Get(UpperCase(fileName));
if p=-1 then begin
sample:=LoadMediaAsSample(fileName);
end else
sample:=TMediaFile(pointer(p));
end;
end;
(* TODO
function LoadSample(s:TSample):boolean;
var
st:string;
i:integer;
begin
result:=false;
if s=nil then exit;
if s.handle>0 then exit;
{$IFDEF IMX}
s.handle:=IMXSampleLoad(false,PAnsiChar(AnsiString(soundFolderPath+s.fname)));
{$ENDIF}
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_LEGACY_AUDIO)}
try
s.handle:=0;
// st:=Lowercase {TODO: use st.ToLower}(s.fname);
st:=s.fname;
for i:=0 to high(pools) do begin
if pools[i]=nil then pools[i]:=TSoundPool.Create;
if pools[i].count<8 then begin
Log.Force('[SOUND] Loading '+st+' to pool '+inttostr(i));
s.handle:=pools[i].LoadSoundFile('Audio/'+st);
s.pool:=i;
break;
end;
end;
except
on e:exception do Log.Msg('[Sound] '+ExceptionMsg(e));
end;
{$IFEND}
if s.handle=0 then
Log.Msg('[Sound] Warning: cannot load sample '+s.fname)
else begin
result:=true;
Log.Msg('[Sound] Sample loaded: '+s.fname+' = '+inttostr(s.handle))
end;
end; *)
// Load sound configuration
procedure LoadConfig;
var
cfg:TConfig;
root:TCfgNode;
// One parameter of a sound event: file, vol, pan, freq or speed
procedure SetEventParam(evt:TSoundEvent;name,value:string8);
begin
name:=UpperCase {TODO: use st.ToUpper}(name);
if name='FILE' then begin
evt.fileName:=value;
// check if this media file is already loaded
if mediaFilesHash.HasValue(UpperCase(evt.fileName)) then
evt.sample:=pointer(mediaFilesHash.Get(UpperCase(evt.fileName)));
end;
if name='VOL' then evt.volume:=StrToInt(value)/100;
if name='PAN' then evt.pan:=StrToInt(value)/100;
if name='FREQ' then evt.speed:=StrToInt(value)/44100;
if name='SPEED' then evt.speed:=Conv.ToFloat(value);
end;
// An event is a string "file,vol=xx,pan=yy" or a section { file = "...", vol = xx }
procedure AddEvent(node:TCfgNode);
var
st:string8;
params,param:Strings8;
i:integer;
evt:TSoundEvent;
p:TCfgNode;
begin
evt:=TSoundEvent.Create(UpperCase {TODO: use st.ToUpper}(node.Name));
try
if node.Kind=ckSection then
for p in node do SetEventParam(evt,p.Name,p.AsStr)
else begin
st:='file='+node.AsStr;
params:=st.Split(',','"');
for i:=0 to length(params)-1 do begin
param:=params[i].Split('=');
if length(param)>=2 then SetEventParam(evt,param[0],param[1]);
end;
end;
except
evt.Free;
raise;
end;
evtHash.Put(evt.name,evt);
end;
procedure AddMusicEntry(node:TCfgNode);
var
item:TMusicEntry;
fname,fExt:string;
loop:boolean;
looppos:integer;
begin
if node.Kind<>ckSection then exit;
item:=TMusicEntry.Create;
item.name:=UpperCase {TODO: use st.ToUpper}(node.Name);
fname:=node.Str('file');
item.loop:=node.Bool('loop',false);
loop:=item.loop;
fExt:=UpperCase {TODO: use st.ToUpper}(ExtractFileExt(fname));
if (fExt='.OGG') or (fExt='.MP3') or (fExt='.WAV') then begin
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_LEGACY_AUDIO)}
// Copy file to data folder
fname:=CopyAssetFile('Audio/'+lowercase {TODO: use st.ToLower}(fname));
try
item.player:=TJNIMediaPlayer.Create;
item.player.SetDataSource(fname,loop);
item.handle:=UIntPtr(item.player);
item.isModule:=false;
item.loopPos:=0;
if loop then item.loopCount:=-1
else item.loopCount:=0;
item.curVolume.Init;
Log.Msg('[SOUND] Music loaded: %s = %d '[fname,item.handle]);
except
on e:Exception do begin
Log.Msg('[SOUND] Music loading failed: '+ExceptionMsg(e));
end;
end;
{$IFEND}
// Load as stream
item.media:=soundLib.OpenMediaFile(Files.FixName(soundFolderPath+fname),mlmJustOpen);
item.isModule:=false;
end else
if (fExt='.MOD') or (fExt='.S3M') or (fExt='.XM') then begin
// load as module
item.media:=soundLib.OpenMediaFile(Files.FixName(soundFolderPath+fname),mlmLoad);
item.isModule:=true;
end;
if item.media=nil then begin
Log.Force('[SOUND] Failed to load music file '+fName);
exit;
end;
// Loop start: "loopTime" in seconds (survives resampling of the file) wins over
// "loopPos" in samples of the file (the unit of the original Engine 2 configs)
if node.Node('loopTime').Exists then
item.loopPos:=node.Float('loopTime')
else begin
looppos:=node.Int('loopPos',0);
if looppos>0 then begin
if item.media.sampleRate<=0 then
Log.Warn('[SOUND] %s: unknown sample rate, loopPos assumes %d Hz',[fname,SampleRateOf(item.media)]);
item.loopPos:=looppos/SampleRateOf(item.media);
end;
end;
item.volume:=node.Int('volume',75)/100;
MusHash.Put(item.name,item);
end;
procedure LoadSoundEvents;
var
n:TCfgNode;
begin
// a broken event is reported and skipped, the others still load
for n in root.Node('SoundEvents') do
if n.Kind in [ckScalar,ckSection] then try
AddEvent(n);
except
on e:Exception do ReportConfigProblem('[SOUND] '+n.Location+': sound event '+n.Name+' is skipped: '+String8(e.Message));
end;
end;
procedure PreloadSamples;
var
i:integer;
mode,fName:string8;
list:PointerArray;
names:Strings8;
begin
// a list of files (comma-separated or an array), ALL or NONE
names:=root.Strs('Settings.PreloadSamples');
if length(names)=1 then names:=names[0].Split(',');
if length(names)=0 then mode:='NONE'
else
if length(names)=1 then mode:=UpperCase {TODO: use st.ToUpper}(names[0])
else mode:='LIST';
Log.Force('[SOUND] Preloading mode: '+mode);
if mode<>'NONE' then Log.Msg('[SOUND] Preloading');
if mode='ALL' then begin
// preload all
list:=evtHash.GetValues;
for i:=0 to high(list) do
TSoundEvent(list[i]).Preload;
end else
if mode<>'NONE' then
// preload listed
for fName in names do LoadMediaAsSample(fName.Trim);
if mode<>'NONE' then Log.Msg('[SOUND] samples preloading done');
end;
procedure LoadMusicEntries;
var
n:TCfgNode;
begin
for n in root.Node('Music') do AddMusicEntry(n);
end;
begin
Log.Msg('[SOUND] Loading config');
cfg:=nil;
try
evtHash:=TStrHash.Create;
mediaFilesHash.Init(100);
musHash:=TStrHash.Create;
cfg:=TConfig.Create(soundConfigFile);
root:=cfg.Root;
{ SetSoundVolume(root.Int('Settings.SoundVolume'));
SetMusicVolume(root.Int('Settings.MusicVolume'));}
LoadSoundEvents;
PreloadSamples;
LoadMusicEntries;
Log.Msg('[SOUND] Config loaded');
except
// not fatal: the sound system works with what was loaded
on e:Exception do ReportConfigProblem('[SOUND] config loading error: '+String8(ExceptionMsg(e)));
end;
cfg.Free;
end;
// Sound event (uppercase name) with its sample loaded, nil if there is none
function GetEventSample(const name:string8):TSoundEvent;
begin
result:=EvtHash.Get(name);
if result=nil then begin
Log.Msg('[SOUND] Event not found: '+name);
exit;
end;
result.Preload;
if result.sample=nil then result:=nil; // can't load the sample
end;
// ISoundSystem.Play: volume and speed multiply the configured values, pan is added
function PlayEvent(const name:string8;volume,pan,speed:single;out settings:TPlaySettings):TChannel;
var
evt:TSoundEvent;
begin
result:=0;
settings:=DefaultSettings;
if soundVolume=0 then exit;
evt:=GetEventSample(UpperCase(name));
if evt=nil then exit;
settings.volume:=evt.volume*volume;
settings.pan:=Clamp(evt.pan+pan,-1.0,1.0);
settings.speed:=evt.speed*speed;
settings.loop:=evt.loop;
evt.lastChannel:=soundLib.PlayMedia(evt.sample,settings);
result:=evt.lastChannel;
end;
procedure PlaySound(event:TEventStr;tag:TTag);
var
sa:Strings8;
evt:TSoundEvent;
settings:TPlaySettings;
par:TNameValue;
slide:integer;
newVolume,newSpeed,newPan:single;
i,p:integer;
begin
Log.Msg('[SOUND] '+event+' '+IntToHex(tag,6));
if soundvolume=0 then exit;
delete(event,1,5);
sa:=event.Split(',','"');
event:=sa[0];
evt:=GetEventSample(event);
if evt=nil then exit;
// Configure playback settings
// 1. Load defaults
settings:=DefaultSettings;
with settings do begin
volume:=evt.volume;
pan:=evt.pan;
speed:=evt.speed;
loop:=evt.loop;
end;
slide:=0;
newVolume:=settings.volume;
newSpeed:=settings.speed;
newPan:=settings.pan;
// 2. Override
for i:=1 to high(sa) do begin
par.InitFrom(sa[i]);
if par.Named('vol') or par.named('v') then begin
if par.value.EndsWith('%') then
settings.volume:=settings.volume*par.GetInt/100
else
settings.volume:=par.GetInt/100;
end else
if par.Named('pan') or par.Named('p') then settings.pan:=par.GetInt/100
else
if par.Named('freq') or par.Named('f') then settings.speed:=par.GetInt/SampleRateOf(evt.sample)
else
if par.Named('speed') or par.Named('r') then settings.speed:=par.GetFloat
else
if par.Named('slide') or par.Named('s') then slide:=par.GetInt
else
if par.Named('newvol') or par.Named('nv') then newVolume:=par.GetInt/100
else
if par.Named('newpan') or par.Named('np') then newpan:=par.GetInt/100
else
if par.Named('newfreq') or par.Named('nf') then newSpeed:=par.GetInt/SampleRateOf(evt.sample);
end;
// Low byte of tag overrides volume (in %)
p:=tag and 255;
if p<>0 then settings.volume:=settings.volume*p/100;
// 8..23 bits of tag = override sample frequency (if >250) or speed (1..250 in %)
p:=(tag shr 8) and $FFFF;
if p>0 then begin
if p>250 then settings.speed:=p/SampleRateOf(evt.sample)
else settings.speed:=p/100;
end;
// High byte of tag overrides pan (-128..127 -> -1.0..1.0)
p:=shortint(tag shr 24);
if p<>0 then settings.pan:=Clamp(p/100.0,-1.0,1.0);
evt.lastChannel:=soundLib.PlayMedia(evt.sample, settings);
if slide>0 then begin
if newVolume<>settings.volume then
soundLib.SlideChannel(evt.lastChannel,caVolume,newVolume,slide/1000);
if newSpeed<>settings.speed then
soundLib.SlideChannel(evt.lastChannel,caSpeed,newSpeed,slide/1000);
if newPan<>settings.pan then
soundLib.SlideChannel(evt.lastChannel,caPanning,newPan,slide/1000);
end;
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_LEGACY_AUDIO)}
evt.channel:=pools[evt.sample.pool].PlaySound(evt.sample.handle,v/100,v/100,1.0,false);
{$IFEND}
end;
// Switch the music: fade the current track out over fadeOut seconds (0 = stop it at
// once) and start the new one (none if the name is empty or NONE) startAfter seconds
// later (at once if nothing plays) with a fade-in of fadeIn seconds, from fromPos seconds
procedure StartMusic(name:string8;fadeOut,startAfter,fadeIn:single;fromPos:double;restart:boolean);
var
mus:TMusicEntry;
downtime:integer;
begin
if name='NONE' then name:='';
mus:=nil;
if name<>'' then mus:=MusHash.Get(name);
// Already playing the requested track?
if not restart and (mus<>nil) and (curMusic=mus) then exit;
needMusicPlayFrom:=fromPos;
needSlide:=round(fadeIn*1000);
needMusicStartTime:=CoreTime.Ticks+round(startAfter*1000);
downtime:=round(fadeOut*1000);
// Fade-Out all playing music streams
if curMusic<>nil then begin
if downTime>0 then begin
Log.Msg('[SOUND] Fading out current music during '+inttostr(downtime));
if (caVolume in soundLib.CanSlide) or (soundLib.CanFadeMusic) then
soundLib.SlideChannel(curMusic.channel,caVolume,0,downTime/1000)
else begin
curMusic.curVolume.Init(curMusic.volume);
end;
curMusic.stopTime:=CoreTime.Ticks+downTime;
end else begin
Log.Msg('[SOUND] Stop current music immediately');
soundLib.StopChannel(curMusic.channel);
curMusic:=nil;
end;
end else
needMusicStartTime:=CoreTime.Ticks;
// a track that waits for its start is replaced too
needMusic:=mus;
if (name<>'') and (mus=nil) then Log.Msg('[SOUND] Music not found: '+name);
end;
// Sound\PlayMusic\Name: the low 7 bits of the tag select a transition, bit 7 restarts
// the track that already plays, the bits from 8 up give the start position (1/100000 s)
procedure PlayMusicEvent(const name:string8;tag:TTag);
const
// fade-out, start delay, fade-in (sec)
TRANSITIONS:array[0..6,0..2] of single=(
(1.2, 1.0, 0), // normal: fade-out old music, then start new
(0.4, 0.3, 0), // fast fade-out, start new almost immediately
(2.5, 3.0, 0), // very slow fade-out
(2.0, 0.8, 2.0), // slow fade-out, smooth fade-in crossfade
(2.5, 2.0, 2.0), // slow fade-out, smooth fade-in without crossfade
(0.5, 0.4, 2.0), // fast fade-out, slow fade-in crossfade
(0.5, 0.25, 0.5)); // fast fade-out, medium fade-in crossfade
var
mode:integer;
begin
mode:=tag and $7F;
if mode>high(TRANSITIONS) then begin
Log.Msg('[SOUND] PlayMusic: unknown tag %d',[mode]);
exit;
end;
StartMusic(name,TRANSITIONS[mode,0],TRANSITIONS[mode,1],TRANSITIONS[mode,2],
(tag shr 8)/100000,tag and 128<>0);
end;
// Pause/resume all playback
procedure PauseAll(pause:boolean);
var
mus:TMusicEntry;
st:string;
begin
if soundLib<>nil then begin
if pause then Log.Info('[SOUND] Pause')
else Log.Info('[SOUND] Resume');
soundLib.Pause(pause);
end;
st:=MusHash.FirstKey;
while st<>'' do begin
mus:=MusHash.Get(st);
if mus.channel<>0 then begin
{$IF DEFINED(ANDROID) AND DEFINED(ANDROID_LEGACY_AUDIO)}
if pause then begin
Log.Msg('Pause music track '+mus.name);
mus.player.Pause;
end else begin
Log.Msg('Resume music track '+mus.name);
mus.player.Resume;
end;
{$IFEND}
end;
st:=MusHash.NextKey;
end;
end;
{ TFilePlayback }
destructor TFilePlayback.Destroy;
begin
soundLib.StopChannel(channel);
media.Free;
inherited;
end;
// Find a group by name, create it with the default policy if needed
function GetFileGroup(name:string8):TFileGroup;
var
g:TFileGroup;
begin
name:=UpperCase(name);
for g in fileGroups do
if g.name=name then exit(g);
result:=TFileGroup.Create;
result.name:=name;
result.duck:=1.0;
SetLength(fileGroups,length(fileGroups)+1);
fileGroups[high(fileGroups)]:=result;
end;
// Name[,duck=N][,exclusive=0|1]
procedure SetFileGroup(const params:string8);
var
sa:Strings8;
par:TNameValue;
g:TFileGroup;
i:integer;
begin
sa:=params.Split(',','"');
if (length(sa)=0) or (sa[0]='') then exit;
g:=GetFileGroup(sa[0]);
for i:=1 to high(sa) do begin
par.InitFrom(sa[i]);
if par.Named('duck') then g.duck:=Clamp(par.GetInt/100,0.0,1.0)
else
if par.Named('exclusive') then g.exclusive:=par.GetBool
else
Log.Warn('[SOUND] SetGroup: unknown parameter '+sa[i]);
end;
end;
procedure StopFilePlayback(pb:TFilePlayback);
begin
if pb.stopped then exit;
pb.stopped:=true;
// the playback is unloaded when the fade-out ends
if (caVolume in soundLib.CanSlide) or soundLib.CanFadeMusic then
soundLib.SlideChannel(pb.channel,caVolume,0,FILE_FADE_TIME)
else
soundLib.StopChannel(pb.channel);
end;
// Stop files matching the path (any if empty) and the group (any if nil)
procedure StopFiles(const path:string8;group:TFileGroup);
var
pb:TFilePlayback;
begin
for pb in filePlaybacks do
if ((group=nil) or (pb.group=group)) and
((path='') or SameText(Files.FixName(path),Files.FixName(pb.path))) then
StopFilePlayback(pb);
end;
// Play a file once as a sample, it's unloaded when finished. Returns the backend channel
function StartFile(const path:string8;volume:single;group:TFileGroup):TChannel;
var
settings:TPlaySettings;
media:TMediaFile;
pb:TFilePlayback;
begin
result:=0;
if path='' then exit;
settings:=DefaultSettings;
settings.volume:=volume;