Debian Codegraph @

src/audio/castlesoundengine_engine.inc

raw
1 {%MainUnit castlesoundengine.pas}
2 {
3 Copyright 2010-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18
19 //type // allow type declaration to continue
20
21 { Sound engine, responsible for loading and playing sounds.
22 See @url(https://castle-engine.io/manual_sound.php
23 manual about sound in Castle Game Engine) for an overview of sound support.
24
25 There should always be only one instance of this class,
26 accessed through the global @link(SoundEngine) routine. }
27 TSoundEngine = class(TSoundAllocator)
28 private
29 type
30 TInternalSoundBuffersList = {$ifdef FPC}specialize{$endif} TObjectList<TInternalSoundBuffer>;
31 var
32 FInformation: string;
33 FInformationSummary: string;
34 FDevice: string;
35 FVolume: Single;
36 FEnabled: boolean;
37 FIsContextOpen: boolean;
38 FDistanceModel: TSoundDistanceModel;
39 LoadedBuffers: TInternalSoundBuffersList;
40 FDevices: TSoundDeviceList;
41 FOnOpenClose: TNotifyEventList;
42 FResumeToInitialized, FPaused: boolean;
43 FListenerPosition, FListenerDirection, FListenerUp: TVector3;
44 FDopplerFactor: Single;
45
46 procedure SetVolume(const Value: Single);
47 procedure SetDistanceModel(const Value: TSoundDistanceModel);
48 procedure SetDevice(const Value: String);
49 procedure SetEnabled(const Value: boolean);
50 procedure SetPaused(const Value: boolean);
51 procedure ReinitializeJavaActivity(Sender: TObject);
52 procedure ApplicationPause(Sender: TObject);
53 procedure ApplicationResume(Sender: TObject);
54 { Pause the sound engine, useful when Android activity gets inactive.
55 When paused, sound backend is for sure inactive, and it cannot be activated
56 (calling ContextOpen, or playing a sound, will @bold(not) activate it). }
57 property Paused: boolean read FPaused write SetPaused;
58 procedure SetInternalBackend(const Value: TSoundEngineBackend);
59 procedure SetDopplerFactor(const Value: Single);
60
61 procedure ContextOpenCore; override;
62 procedure ContextCloseCore; override;
63
64 class function GetLogSoundLoading: Boolean; static;
65 class procedure SetLogSoundLoading(const Value: Boolean); static;
66
67 { Load a sound file contents such that they can be immediately played.
68
69 This method tries to initialize backend (like OpenAL) context,
70 and loads the buffer contents. But even when it fails, it still returns
71 a valid (non-nil) TInternalSoundBuffer instance. As the OpenAL context
72 may be lost while the game is ongoing (in case of Android) we take care
73 to reload it when necessary.
74
75 The buffer should be released by @link(FreeBuffer) later when it's not needed.
76 Although we will take care to always free remaining buffers
77 before closing OpenAL context anyway.
78
79 We have a cache of sound files here. An absolute URL
80 will be recorded as being loaded to given buffer. Loading the same
81 URL second time returns the same buffer instance. The buffer
82 is released only once you call @link(FreeBuffer) as many times as you called
83 LoadBuffer for it.
84
85 @param(ExceptionOnError When to raise exception,
86 or merely make a warning by WritelnWarning,
87 in case of error when loading.
88
89 Note that it always returns non-nil, even in case of ExceptionOnError=@false
90 and an error at loading. But in this case, TInternalSoundBuffer is mostly a useless
91 empty instance. Do not depend on this behavior, and check for @nil
92 result in case you use ExceptionOnError=@false.
93 )
94
95 @param(SoundLoading Specifies whether to load sound at once, or use streaming.
96 See @link(TSoundLoading) for details.)
97
98 @raises(ESoundFileError If loading of this sound file failed.
99 There are many reasons why this may happen: we cannot read given URL,
100 or it may contain invalid contents,
101 or a library required to decompress e.g. OggVorbis is missing.)
102
103 @groupBegin }
104 function LoadBuffer(const Url: String; const SoundLoading: TSoundLoading;
105 const ExceptionOnError: Boolean = true): TInternalSoundBuffer; overload;
106 function LoadBuffer(const Url: String;
107 const ExceptionOnError: Boolean = true): TInternalSoundBuffer; overload;
108 function LoadBuffer(const Url: String; out Duration: TFloatTime): TInternalSoundBuffer;
109 overload;
110 { @groupEnd }
111
112 { Free a sound file buffer. Ignored when buffer is @nil.
113 Buffer is always set to @nil after this.
114
115 @raises(ESoundBufferNotLoaded When invalid (not @nil,
116 and not returned by LoadBuffer) buffer identifier is given.) }
117 procedure FreeBuffer(var Buffer: TInternalSoundBuffer);
118
119 { Play a sound from given buffer.
120
121 We use a smart sound allocator, so the sound will be actually
122 played only if resources allow. Use higher priority to indicate
123 sounds that are more important to play.
124
125 We set the sound properties and start playing it.
126
127 Both spatialized (3D) and not spatialized sounds are possible.
128 See the @link(TPlaySoundParameters) for a full list of sound parameters.
129 You can pass all the sound parameters as a @link(TPlaySoundParameters) instance.
130 You can destroy the @link(TPlaySoundParameters) instance right after calling
131 this method, the reference to it is not saved anywhere.
132
133 @returns(The allocated sound as TInternalSoundSource.
134
135 Returns @nil when there were no resources to play another sound
136 (and it wasn't important enough to override another sound).
137 Always returns @nil when SoundBuffer is zero (indicating that buffer
138 was not loaded).
139
140 In simple cases you can just ignore the result of this method.
141 In advanced cases, you can use it to observe and update the sound
142 later.)
143
144 @exclude
145 }
146 function PlaySound(const Parameters: TPlaySoundParameters): TInternalSoundSource;
147 public
148 const
149 DefaultVolume = 1.0;
150 DefaultDistanceModel = dmInverse;
151 DefaultDevice = '';
152 DefaultEnabled = true;
153
154 class var
155 LogVerbose: Boolean;
156
157 constructor Create;
158 destructor Destroy; override;
159
160 { Initialize sound backend.
161 Sets @link(IsContextOpen), @link(IsContextOpenSuccess), @link(Information).
162
163 You don't usually need to call this -- everything will be initialized
164 automatically when you first load a sound (or try to load and play it).
165
166 You can set @link(Device) before calling this.
167
168 Note that we continue (without any exception) if the initialization
169 failed for any reason (e.g. OpenAL library is not available,
170 or no sound output device is available).
171 You can check @link(IsContextOpenSuccess) and @link(Information) to know if
172 the initialization was actually successful. But you can also ignore it,
173 the sound engine will silently (literally) keep working even if OpenAL
174 could not be initialized. }
175 procedure ContextOpen;
176
177 { Close the sound backend, releasing all sound resources and stopping playback.
178 This sets @link(IsContextOpen) and @link(IsContextOpenSuccess) to @false.
179 It's allowed and harmless to call this when one of them is already @false.
180
181 You don't usually need to call this -- everything will be released
182 automatically when the sound engine is destroyed (at program finalization). }
183 procedure ContextClose;
184
185 { Sound backend, like OpenAL or FMOD or SOX.
186 See @url(https://castle-engine.io/openal OpenAL) or
187 @url(https://castle-engine.io/fmod FMOD).
188
189 Do not change or access this yourself.
190 You can change this only by calling procedure like UseFMODSoundBackend
191 from CastleFMODSoundBackend unit. }
192 property InternalBackend: TSoundEngineBackend read Backend write SetInternalBackend;
193
194 { Did we attempt to initialize sound rendering context.
195 This indicates that ContextOpen was called,
196 and not closed with ContextClose yet.
197 Contrary to IsContextOpenSuccess,
198 this @italic(doesn't care if ContextOpen was a success). }
199 property IsContextOpen: boolean read FIsContextOpen;
200
201 { Multiline information about the currently initialized
202 sound backend (OpenAL, FMOD etc.). }
203 property Information: string read FInformation;
204
205 { One-line information about the currently initialized
206 sound backend (OpenAL, FMOD etc.). }
207 property InformationSummary: string read FInformationSummary;
208
209 { Play given sound once (not looping).
210
211 This is the simplest method to just play the sound and "forget about it"
212 (no need to manage the playback afterwards).
213
214 It is allowed to set ASound to @nil. Nothing will be played then.
215
216 Note: Instead of this method, use @code(Play(TCastlePlayingSound))
217 overload to have more control over the sound
218 (before and after it starts playing).
219
220 This only plays non-spatial sounds, as it doesn't give any control over
221 the sound 3D position.
222 Instead of this method, use TCastleSoundSource
223 (attached to some TCastleTransform) for spatial sounds to control their 3D position. }
224 procedure Play(const ASound: TCastleSound); overload;
225
226 { Play given sound.
227
228 Set @link(TCastlePlayingSound.Sound) before passing it to this method.
229 Otherwise, if @link(TCastlePlayingSound.Sound) is left @nil, nothing will be played.
230
231 Use the PlayingSound (TCastlePlayingSound) properties to provide additional information
232 about the sound playback.
233 E.g. assign @link(TCastlePlayingSound.Loop)
234 @link(TCastlePlayingSound.OnStop) or control sound afterwards by
235 @link(TCastlePlayingSound.Stop), @link(TCastlePlayingSound.Offset).
236
237 Consider using @link(TCastlePlayingSound.FreeOnStop) if you don't want
238 to manage the lifetime of the @link(TCastlePlayingSound) instance.
239
240 This only plays non-spatial sounds, as it doesn't give any control over
241 the sound 3D position.
242 Instead of this method, use TCastleSoundSource
243 (attached to some TCastleTransform) for spatial sounds to control their 3D position. }
244 procedure Play(const PlayingSound: TCastlePlayingSound); overload;
245
246 { Internal, a bit more flexible, variant of @link(Play). @exclude }
247 procedure InternalPlay(const PlayingSound: TCastlePlayingSound;
248 const ASpatial: Boolean; const APosition: TVector3);
249
250 { Parse parameters in @link(Parameters) and interpret and remove
251 recognized options. Internally it uses Parameters.Parse with
252 ParseOnlyKnownLongOptions = @true. Recognized options:
253
254 @definitionList(
255 @itemLabel @--audio-device DEVICE-NAME
256 @item Set @link(Device) variable to given argument.
257
258 @itemLabel @--no-sound
259 @item Disable any sound (sets @link(Enabled) to @false).
260 )
261
262 More user-oriented documentation for the above options is here:
263 [https://castle-engine.io/openal_notes.php#section_options] }
264 procedure ParseParameters;
265
266 { Help string for options parsed by ParseParameters.
267
268 Note that it also lists the available sound output @link(Devices),
269 as they are valid arguments for the @--audio-device option. }
270 function ParseParametersHelp: string;
271
272 { Set the sound listener position and orientation. @exclude }
273 procedure InternalUpdateListener(const Position, Direction, Up: TVector3);
274
275 { List of available sound devices. Read-only.
276
277 Use @code(Devices[].Name) as @link(Device) values.
278
279 On some backend implementations, also some other @link(Device) values may
280 be possible. E.g. old Loki implementation of OpenAL allowed some hints
281 to be encoded in Lisp-like language inside the @link(Device) string. }
282 function Devices: TSoundDeviceList;
283
284 function DeviceCaption: string;
285
286 { Events fired after sound context is being open or closed.
287 More precisely, when IsContextOpen changes (and so, possibly, IsContextOpenSuccess
288 changed). }
289 property OnOpenClose: TNotifyEventList read FOnOpenClose;
290
291 class property LogSoundLoading: Boolean
292 read GetLogSoundLoading write SetLogSoundLoading;
293
294 { Sound volume, affects all sounds (effects and music).
295 Must be within 0..1 range.
296
297 Setting volume to 0.0 means that there is no sound output
298 (this case should be optimized). The sounds played are still tracked. }
299 property Volume: Single read FVolume write SetVolume
300 {$ifdef FPC}default DefaultVolume{$endif};
301
302 { Sound output device, used when initializing sound context.
303
304 You can change it even when context is already initialized.
305 Then we'll close the old device (ContextClose),
306 change @link(Device) value, and initialize context again (ContextOpen).
307 Note that you will need to reload your buffers and sources again. }
308 property Device: string read FDevice write SetDevice;
309
310 { Enable sound. Value @true, the default, means that we will initialize
311 sound backend and play all sounds as you expect.
312
313 If this is @false, then we will not initialize any sound backend even
314 if you try to load or play some sound.
315 This is useful if you simply want to disable any sound output
316 (or backend, like OpenAL, usage), even when sound library (like OpenAL)
317 is available.
318
319 Setting this to @false when the sound backend
320 is already initialized will close it, stopping the playback of
321 all existing sound sources.
322
323 Note that when sound backend is not initialized,
324 sounds are not tracked, and non-looping sounds are just discarded.
325 So toggling this property between @false and @true
326 will simply restart all looping sounds from the beginning.
327 So setting this to @false is not a way to "pause" or "mute" sound playback,
328 it's a way to "stop" sound playback.
329 If you want to mute all sounds, but be able to unmute them when necessary,
330 set the @link(Volume) to zero. }
331 property Enabled: boolean read FEnabled write SetEnabled default DefaultEnabled;
332
333 { How does the distance affect spatial sounds (with @link(TCastleSoundSource.Spatial)).
334 See TSoundDistanceModel for the description of possible options. }
335 property DistanceModel: TSoundDistanceModel
336 read FDistanceModel write SetDistanceModel {$ifdef FPC}default DefaultDistanceModel{$endif};
337
338 { Emphasize or deemphasize the Doppler effect.
339 See https://en.wikipedia.org/wiki/Doppler_effect and CGE demo
340 examples/audio/doppler_effect to see what it is.
341
342 Allowed values are anything > 0.
343 Value 0 disables the Doppler effect.
344 This is the default, otherwise the Doppler effect would be way too audible in 2D games.
345 Value 1 makes a correct Doppler effect if the distance in your world of 1 unit
346 corresponds to 1 meter.
347 Larger values allow to emphasize the effect more. }
348 property DopplerFactor: Single read FDopplerFactor write SetDopplerFactor {$ifdef FPC}default 0.0{$endif};
349 end;
350
351 {$endif read_interface}
352
353 {$ifdef read_implementation}
354
355 { TSoundEngine --------------------------------------------------------------- }
356
357 constructor TSoundEngine.Create;
358 begin
359 inherited;
360 FVolume := DefaultVolume;
361 FDistanceModel := DefaultDistanceModel;
362 FDopplerFactor := 0.0;
363 FEnabled := DefaultEnabled;
364 FDevice := DefaultDevice;
365 LoadedBuffers := TInternalSoundBuffersList.Create(true);
366 FOnOpenClose := TNotifyEventList.Create;
367
368 { Default listener attributes }
369 FListenerPosition := TVector3.Zero;
370 FListenerDirection := Vector3(0, 0, -1);
371 FListenerUp := Vector3(0, 1, 0);
372
373 ApplicationProperties.OnInitializeJavaActivity.Add(
374 {$ifdef FPC}@{$endif} ReinitializeJavaActivity);
375 ApplicationProperties.OnPause.Add(
376 {$ifdef FPC}@{$endif} ApplicationPause);
377 ApplicationProperties.OnResume.Add(
378 {$ifdef FPC}@{$endif} ApplicationResume);
379 end;
380
381 destructor TSoundEngine.Destroy;
382 begin
383 if ApplicationProperties(false) <> nil then
384 begin
385 ApplicationProperties(false).OnInitializeJavaActivity.Remove(
386 {$ifdef FPC}@{$endif} ReinitializeJavaActivity);
387 ApplicationProperties(false).OnPause.Remove(
388 {$ifdef FPC}@{$endif} ApplicationPause);
389 ApplicationProperties(false).OnResume.Remove(
390 {$ifdef FPC}@{$endif} ApplicationResume);
391 end;
392
393 ContextClose;
394
395 Inc(ValidSoundBufferFree);
396 try
397 FreeAndNil(LoadedBuffers);
398 finally Dec(ValidSoundBufferFree) end;
399
400 FreeAndNil(FDevices);
401 FreeAndNil(FOnOpenClose);
402 inherited;
403 end;
404
405 function TSoundEngine.Devices: TSoundDeviceList;
406 begin
407 { Create devices on demand (not immediately in TSoundEngine.Create),
408 because in case of OpenAL merely using alcGetString(nil, ALC_DEVICE_SPECIFIER)
409 may perform some OpenAL initialization (discovery of available devices).
410 E.g. with OpenAL Soft 1.13 in Debian. This is not very harmful,
411 but it causes output (on stdout or stderr) like
412
413 AL lib: pulseaudio.c:612: Context did not connect: Connection refused
414 ALSA lib pcm.c:2190:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
415 ALSA lib pcm.c:2190:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
416 ALSA lib pcm.c:2190:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
417 ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only playback stream
418
419 and it causes a temporary slowdown. So we want to defer this (until really
420 needed, or until explicit ContextOpen call). }
421
422 if FDevices = nil then
423 begin
424 FDevices := TSoundDeviceList.Create;
425 FDevices.Add('', 'Default Device');
426 Backend.DetectDevices(FDevices);
427 end;
428 Result := FDevices;
429 end;
430
431 procedure TSoundEngine.ContextOpenCore;
432
433 { initialize resources inside LoadedBuffers }
434 procedure LoadedBuffersOpen;
435 var
436 Buffer: TInternalSoundBuffer;
437 begin
438 // check LoadedBuffers.Count, because we don't want to do progress with no LoadedBuffers
439 if LoadedBuffers.Count <> 0 then
440 begin
441 { call ContextOpen on all buffers }
442 for Buffer in LoadedBuffers do
443 Buffer.ContextOpen(false);
444 end;
445 end;
446
447 var
448 BackendOpenInformation, BackendOpenInformationSummary: String;
449 begin
450 Assert(not IsContextOpenSuccess, 'Sound context is already active');
451
452 if not Enabled then
453 begin
454 FInformation := 'Sound initialization aborted: Sound engine is disabled';
455 FInformationSummary := 'Disabled';
456 end else
457 begin
458 FIsContextOpenSuccess := Backend.ContextOpen(FDevice, BackendOpenInformation, BackendOpenInformationSummary);
459 if not IsContextOpenSuccess then
460 begin
461 FInformation := 'Sound backend initialization failed:' + NL +
462 BackendOpenInformation;
463 FInformationSummary := 'Failed: ' + BackendOpenInformationSummary;
464 end else
465 begin
466 FInformation :=
467 'Sound backend initialized successfully:' + NL +
468 BackendOpenInformation + NL +
469 NL+
470 Format('Allocated sound sources: min %d, max %d' + NL +
471 NL+
472 'Library to decode OggVorbis available: %s', [
473 MinAllocatedSources, MaxAllocatedSources,
474 BoolToStr(VorbisFileInitialized, true)
475 ]);
476 FInformationSummary := 'Initialized: ' + BackendOpenInformationSummary;
477
478 try
479 Backend.SetVolume(Volume);
480 Backend.SetDistanceModel(DistanceModel);
481 Backend.SetDopplerFactor(DopplerFactor);
482 Backend.SetListener(
483 FListenerPosition,
484 FListenerDirection,
485 FListenerUp);
486 inherited; { initialize sound allocator }
487 LoadedBuffersOpen;
488 except
489 ContextClose;
490 raise;
491 end;
492 end;
493 end;
494
495 if LogVerbose then
496 WritelnLogMultiline('Sound', Information)
497 else
498 WritelnLog('Sound', InformationSummary + ' (for more info: TSoundEngine.LogVerbose:=true)');
499
500 OnOpenClose.ExecuteAll(Self);
501 end;
502
503 procedure TSoundEngine.ContextCloseCore;
504 var
505 Buffer: TInternalSoundBuffer;
506 begin
507 if IsContextOpenSuccess then
508 begin
509 { release sound allocator first. This also stops all the sources,
510 which is required before we try to release their buffers. }
511 inherited;
512 { free backend resources allocated inside LoadedBuffers }
513 for Buffer in LoadedBuffers do
514 Buffer.ContextClose;
515 Backend.ContextClose;
516 FIsContextOpenSuccess := false;
517 end;
518
519 WritelnLog('Sound', 'Sound backend closed');
520
521 OnOpenClose.ExecuteAll(Self);
522 end;
523
524 procedure TSoundEngine.ContextOpen;
525 begin
526 if Paused then
527 Exit; // do not even set IsContextOpen to true
528
529 if not IsContextOpen then
530 begin
531 FIsContextOpen := true; // set it early, so that OnOpenClose knows it's true
532 ContextOpenCore;
533 end;
534 end;
535
536 procedure TSoundEngine.ContextClose;
537 begin
538 if IsContextOpen then
539 begin
540 FIsContextOpen := false; // set it early, so that OnOpenClose knows it's false
541 ContextCloseCore;
542 end;
543 end;
544
545 function TSoundEngine.PlaySound(const Parameters: TPlaySoundParameters): TInternalSoundSource;
546 begin
547 Result := nil;
548
549 { Open context, if not open yet.
550 In general loading a buffer (LoadBuffer) should cause this already,
551 and loading a buffer should happen before this call (since you need to initialize Parameters.Buffer),
552 so usually calling ContextOpen here does nothing.
553
554 But in case you later close the audio context, and want to reopen it at PlaySound
555 -- we should call ContextOpen here.
556 Doing ContextOpen also calls TInternalSoundBuffer.ContextOpen on all open buffers. }
557 ContextOpen;
558
559 if IsContextOpenSuccess and
560 (Parameters.Buffer <> nil) and
561 { Buffer.BackendIsOpen may be false if file failed to load, e.g. file not found }
562 Parameters.Buffer.BackendIsOpen then
563 begin
564 Result := AllocateSound(Parameters.Priority);
565 if Result <> nil then
566 begin
567 Result.Buffer := Parameters.Buffer;
568 Result.Loop := Parameters.Loop;
569 Result.Pitch := Parameters.Pitch;
570 Result.Volume := Parameters.Volume;
571 { No need to set Result.Priority,
572 TSoundAllocator.AllocateSound have already done this. }
573 Assert(Result.Priority = Parameters.Priority);
574 {$warnings off} // using unportable symbols knowingly
575 Result.MinGain := Parameters.MinGain;
576 Result.MaxGain := Parameters.MaxGain;
577 {$warnings on}
578 Result.Offset := Parameters.Offset;
579 Result.Spatial := Parameters.Spatial;
580
581 Result.Position := Parameters.Position; // will be ignored when Spatial = false, which is OK
582 { Set default attenuation by distance. }
583 Result.ReferenceDistance := Parameters.ReferenceDistance; // will be ignored when Spatial = false, which is OK
584 Result.MaxDistance := Parameters.MaxDistance; // will be ignored when Spatial = false, which is OK
585
586 Result.Backend.Play(true);
587 end;
588 end;
589 end;
590
591 procedure TSoundEngine.Play(const ASound: TCastleSound);
592 var
593 PlayingSound: TCastlePlayingSound;
594 begin
595 PlayingSound := TCastlePlayingSound.Create(nil);
596 PlayingSound.Sound := ASound;
597 PlayingSound.FreeOnStop := true;
598 Play(PlayingSound);
599
600 { Note: we could make this a function and return TCastlePlayingSound.
601 But it could be risky for user not aware that (s)he @italic(must)
602 change FreeOnStop := false, otherwise TCastlePlayingSound instance
603 could be freed at any point in the future. }
604 end;
605
606 procedure TSoundEngine.Play(const PlayingSound: TCastlePlayingSound);
607 begin
608 InternalPlay(PlayingSound, false, { APosition doesn't matter when spatial = false } TVector3.Zero);
609 end;
610
611 procedure TSoundEngine.InternalPlay(const PlayingSound: TCastlePlayingSound;
612 const ASpatial: Boolean; const APosition: TVector3);
613 var
614 ASound: TCastleSound;
615 Params: TPlaySoundParameters;
616 Source: TInternalSoundSource;
617 begin
618 Assert(PlayingSound <> nil);
619 ASound := PlayingSound.Sound;
620
621 if ASound = nil then
622 begin
623 // sound cannot be played, as nil
624 PlayingSound.DoStop; // apply PlayingSound.OnStop, FreeOnStop
625 Exit;
626 end;
627
628 if ASound.InternalBuffer = nil then
629 begin
630 // sound cannot be played, as not loaded
631 PlayingSound.DoStop; // apply PlayingSound.OnStop, FreeOnStop
632 Exit;
633 end;
634
635 { TODO: This should not use
636 - TPlaySoundParameters
637 - PlaySound
638 We should remove (only private now) TPlaySoundParameters and PlaySound.
639 Other classes, like TCastleSound and TCastlePlayingSound,
640 with simpler API, carry all information now.
641 }
642
643 Params := TPlaySoundParameters.Create;
644 try
645 Params.Buffer := ASound.InternalBuffer;
646 Params.Spatial := ASpatial;
647 Params.Position := APosition;
648 Params.Loop := PlayingSound.Loop;
649 Params.Priority := PlayingSound.InternalFinalPriority;
650 Params.Pitch := PlayingSound.InternalFinalPitch;
651 Params.Volume := PlayingSound.InternalFinalVolume;
652 {$warnings off} // using unportable symbols knowingly
653 Params.MinGain := ASound.MinGain;
654 Params.MaxGain := ASound.MaxGain;
655 {$warnings on}
656 Params.Offset := PlayingSound.InitialOffset;
657 Params.ReferenceDistance := ASound.ReferenceDistance; // will be ignored when Spatial = false, which is OK
658 Params.MaxDistance := ASound.MaxDistance; // will be ignored when Spatial = false, which is OK
659
660 Source := PlaySound(Params);
661
662 if Source <> nil then
663 begin
664 PlayingSound.Start(Source);
665 end else
666 begin
667 // sound cannot be played, as no free TInternalSoundSource slot
668 PlayingSound.DoStop; // apply PlayingSound.OnStop, FreeOnStop
669 end;
670 finally FreeAndNil(Params) end;
671 end;
672
673 function TSoundEngine.LoadBuffer(const Url: String; out Duration: TFloatTime): TInternalSoundBuffer;
674 begin
675 Result := LoadBuffer(Url);
676 Duration := Result.Duration;
677 end;
678
679 function TSoundEngine.LoadBuffer(const Url: String; const SoundLoading: TSoundLoading; const ExceptionOnError: Boolean): TInternalSoundBuffer;
680 var
681 I: Integer;
682 FullUrl: String;
683 begin
684 ContextOpen;
685
686 FullUrl := AbsoluteURI(Url);
687
688 { try to load from cache Result }
689 for I := 0 to LoadedBuffers.Count - 1 do
690 if LoadedBuffers[I].Url = FullUrl then
691 begin
692 Result := LoadedBuffers[I];
693 Inc(Result.References);
694 if LogSoundLoading then
695 WritelnLog('Sound', Format('Loaded sound buffer "%s" from cache, now it has %d references',
696 [UriDisplay(FullUrl), Result.References]));
697 Exit;
698 end;
699
700 Result := TInternalSoundBuffer.Create(Backend, SoundLoading);
701 Result.FUrl := FullUrl;
702 Result.References := 1;
703 LoadedBuffers.Add(Result);
704
705 if IsContextOpenSuccess then
706 { let LoadBuffer raise exception on missing sound file }
707 Result.ContextOpen(ExceptionOnError);
708 end;
709
710 function TSoundEngine.LoadBuffer(const Url: String; const ExceptionOnError: Boolean): TInternalSoundBuffer;
711 begin
712 Result := LoadBuffer(Url, slComplete, ExceptionOnError);
713 end;
714
715 procedure TSoundEngine.FreeBuffer(var Buffer: TInternalSoundBuffer);
716 var
717 I: Integer;
718 begin
719 if Buffer = nil then Exit;
720
721 I := LoadedBuffers.IndexOf(Buffer);
722 if I <> -1 then
723 begin
724 Dec(Buffer.References);
725 if Buffer.References = 0 then
726 begin
727 // this will free Buffer, also calling Buffer.ContextClose;
728 Inc(ValidSoundBufferFree);
729 try
730 LoadedBuffers.Delete(I);
731 finally Dec(ValidSoundBufferFree) end;
732 end;
733 Buffer := nil;
734 end else
735 raise ESoundBufferNotLoaded.CreateFmt('Sound buffer "%s" not loaded by this sound engine',
736 [UriDisplay(Buffer.Url)]);
737 end;
738
739 procedure TSoundEngine.SetVolume(const Value: Single);
740 begin
741 if Value <> FVolume then
742 begin
743 FVolume := Value;
744 if IsContextOpenSuccess then
745 Backend.SetVolume(Value);
746 end;
747 end;
748
749 procedure TSoundEngine.SetDistanceModel(const Value: TSoundDistanceModel);
750 begin
751 if Value <> FDistanceModel then
752 begin
753 FDistanceModel := Value;
754 if IsContextOpenSuccess then
755 Backend.SetDistanceModel(Value);
756 end;
757 end;
758
759 procedure TSoundEngine.SetDopplerFactor(const Value: Single);
760 begin
761 if FDopplerFactor <> Value then
762 begin
763 FDopplerFactor := Value;
764 if IsContextOpenSuccess then
765 Backend.SetDopplerFactor(Value);
766 end;
767 end;
768
769 procedure TSoundEngine.SetDevice(const Value: String);
770 begin
771 if Value <> FDevice then
772 begin
773 if IsContextOpen then
774 begin
775 ContextClose;
776 FDevice := Value;
777 ContextOpen;
778 end else
779 FDevice := Value;
780 end;
781 end;
782
783 procedure TSoundEngine.SetEnabled(const Value: boolean);
784 begin
785 if Value <> FEnabled then
786 begin
787 if IsContextOpen then
788 begin
789 ContextClose;
790 FEnabled := Value;
791 ContextOpen;
792 end else
793 FEnabled := Value;
794 end;
795 end;
796
797 procedure OptionProc(OptionNum: Integer; HasArgument: boolean;
798 const Argument: string; const SeparateArgs: TSeparateArgs; Data: Pointer);
799 var
800 Engine: TSoundEngine;
801 begin
802 Engine := TSoundEngine(Data);
803 case OptionNum of
804 0: begin
805 Engine.Device := Argument;
806 end;
807 1: begin
808 Engine.Enabled := false;
809 end;
810 else raise EInternalError.Create('CastleSoundEngine.OptionProc');
811 end;
812 end;
813
814 procedure TSoundEngine.ParseParameters;
815 const
816 SoundOptions: array [0..1] of TOption =
817 ( (Short: #0; Long: 'audio-device'; Argument: oaRequired),
818 (Short: #0; Long: 'no-sound'; Argument: oaNone)
819 );
820 begin
821 Parameters.Parse(SoundOptions, @OptionProc, Self, true);
822 end;
823
824 function TSoundEngine.ParseParametersHelp: string;
825
826 function DevicesHelp: string;
827 var
828 I: Integer;
829 begin
830 Result := Format(' Available devices (%d):', [Devices.Count]) + NL;
831 for i := 0 to Devices.Count - 1 do
832 begin
833 Result := Result + ' ' + Devices[i].Caption;
834 if Devices[i].Name <> Devices[i].Caption then
835 Result := Result + ' (internal name: "' + Devices[i].Name + '")';
836 Result := Result + NL;
837 end;
838 end;
839
840 begin
841 Result :=
842 ' --audio-device DEVICE-NAME' +nl+
843 ' Choose sound output device.' +nl+
844 DevicesHelp +
845 ' --no-sound Turn off sound.';
846 end;
847
848 procedure TSoundEngine.InternalUpdateListener(const Position, Direction, Up: TVector3);
849 begin
850 FListenerPosition := Position;
851 FListenerDirection := Direction;
852 FListenerUp := Up;
853 if IsContextOpenSuccess then
854 Backend.SetListener(Position, Direction, Up);
855 end;
856
857 function TSoundEngine.DeviceCaption: string;
858 var
859 I: Integer;
860 begin
861 for I := 0 to Devices.Count - 1 do
862 if Devices[I].Name = Device then
863 Exit(Devices[I].Caption);
864
865 Result := 'Unnamed Sound Device'; // some default
866 end;
867
868 procedure TSoundEngine.ReinitializeJavaActivity(Sender: TObject);
869 begin
870 { in case Java activity got killed and is created again, be sure to resume }
871 Paused := false;
872 end;
873
874 procedure TSoundEngine.ApplicationPause(Sender: TObject);
875 begin
876 Paused := true;
877 end;
878
879 procedure TSoundEngine.ApplicationResume(Sender: TObject);
880 begin
881 Paused := false;
882 end;
883
884 procedure TSoundEngine.SetPaused(const Value: boolean);
885 begin
886 if FPaused <> Value then
887 begin
888 FPaused := Value;
889 if FPaused then
890 begin
891 FResumeToInitialized := IsContextOpen;
892 ContextClose;
893 end else
894 begin
895 if FResumeToInitialized then
896 ContextOpen;
897 end;
898 end;
899 end;
900
901 procedure TSoundEngine.SetInternalBackend(const Value: TSoundEngineBackend);
902 begin
903 ContextClose;
904 FreeAndNil(Backend);
905 Backend := Value;
906 end;
907
908 class function TSoundEngine.GetLogSoundLoading: Boolean;
909 begin
910 Result := CastleInternalSoundFile.LogSoundLoading;
911 end;
912
913 class procedure TSoundEngine.SetLogSoundLoading(const Value: Boolean);
914 begin
915 CastleInternalSoundFile.LogSoundLoading := Value;
916 end;
917
918 {$endif read_implementation}