Debian Codegraph @

src/audio/openal/castleopenalsoundbackend.pas

raw
1 {
2 Copyright 2010-2022 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Full-featured sound engine backend using OpenAL.
17 Supports spatial (3D) sound, is cross-platform,
18 and underlying OpenAL is free and open-source. }
19 unit CastleOpenALSoundBackend;
20
21 {$I castleconf.inc}
22
23 interface
24
25 { Use this to set sound engine backend to OpenAL.
26
27 Note that OpenAL is the default sound backend on most platforms,
28 so you don't need to call this procedure in simple applications.
29 You only need to call it if you want to switch at runtime between FMOD,
30 OpenAL and other backends. }
31 procedure UseOpenALSoundBackend;
32
33 implementation
34
35 uses SysUtils, Classes, Math, StrUtils, Generics.Collections,
36 CastleInternalOpenAL, CastleVectors, CastleTimeUtils, CastleXMLConfig,
37 CastleClassUtils, CastleStringUtils, CastleInternalSoundFile,
38 CastleInternalAbstractSoundBackend, CastleSoundBase, CastleSoundEngine,
39 CastleInternalALUtils, CastleInternalEFX, CastleLog, CastleUtils, CastleUriUtils;
40
41 { sound backend classes interface -------------------------------------------- }
42
43 type
44 {$ifdef CASTLE_SUPPORTS_THREADING}
45 TOpenALStreamFeedThread = class;
46 {$endif}
47 TOpenALSoundSourceBackend = class;
48 TOpenALStreamBufferBackend = class;
49
50 TOpenALSoundBufferBackend = class(TSoundBufferBackendFromSoundFile)
51 private
52 ALBuffer: TALuint;
53 function ALVersion11: Boolean;
54 public
55 procedure ContextOpenFromSoundFile(const SoundFile: TSoundFile); override;
56 procedure ContextClose; override;
57 end;
58
59 { Manages resources (OpenAL buffers, thread) to play the given
60 sound buffer on a given sound source using streaming. }
61 TOpenALStreaming = class
62 strict private
63 const
64 StreamBuffersCount = 4;
65 HelperBufferSize = 1024 * 32; // 32kB should be enough
66 var
67 Buffer: TOpenALStreamBufferBackend;
68 ALBuffers: array [0..StreamBuffersCount - 1] of TALuint;
69 StreamedFile: TStreamedSoundFile;
70 {$ifdef CASTLE_SUPPORTS_THREADING}
71 FeedThread: TOpenALStreamFeedThread;
72 {$endif}
73 { Used in each FillBuffer.
74 Contents of this between FillBuffer are undefined,
75 we keep this field only to avoid wasting time on GetMem/FreeMem in each
76 FillBuffer call. }
77 HelperBufferPtr: Pointer;
78 private
79 Source: TOpenALSoundSourceBackend;
80 function FillBuffer(const ALBuffer: TALuint): Integer;
81 public
82 constructor Create(const ASoundSurce: TOpenALSoundSourceBackend;
83 const StreamBuffer: TOpenALStreamBufferBackend);
84 destructor Destroy; override;
85 procedure FeedBuffers;
86 end;
87
88 TOpenALStreamBufferBackend = class(TSoundBufferBackendFromStreamedFile)
89 end;
90
91 TOpenALStreamFeedThread = class(TThread)
92 private
93 Streaming: TOpenALStreaming;
94 protected
95 procedure Execute; override;
96 public
97 constructor Create(const CreateSuspended: Boolean;
98 const AStreaming: TOpenALStreaming); reintroduce;
99 end;
100
101 TOpenALSoundSourceBackend = class(TSoundSourceBackend)
102 strict private
103 Streaming: TOpenALStreaming;
104 FSpatial: Boolean; //< by default true, as this is OpenAL default
105 FPosition, FVelocity: TVector3;
106 FReferenceDistance, FMaxDistance: Single;
107 function ALVersion11: Boolean;
108 private
109 FBuffer: TSoundBufferBackend;
110 ALSource: TALuint;
111 FLoop: Boolean;
112
113 { When buffer is stremed, OpenAL source looping need to be off,
114 otherwise, one buffer will be looped. This procedure cares about that. }
115 procedure AdjustALLooping;
116 public
117 constructor Create(const ASoundEngine: TSoundEngineBackend);
118 procedure ContextOpen; override;
119 procedure ContextClose; override;
120 function PlayingOrPaused: boolean; override;
121 procedure Play(const BufferChangedRecently: Boolean); override;
122 procedure Stop; override;
123 procedure SetPosition(const Value: TVector3); override;
124 procedure SetVelocity(const Value: TVector3); override;
125 procedure SetLoop(const Value: boolean); override;
126 procedure SetSpatial(const Value: boolean); override;
127 procedure SetVolume(const Value: Single); override;
128 procedure SetMinGain(const Value: Single); override;
129 procedure SetMaxGain(const Value: Single); override;
130 procedure SetBuffer(const Value: TSoundBufferBackend); override;
131 procedure SetPitch(const Value: Single); override;
132 procedure SetReferenceDistance(const Value: Single); override;
133 procedure SetMaxDistance(const Value: Single); override;
134 procedure SetPriority(const Value: Single); override;
135 function GetOffset: Single; override;
136 procedure SetOffset(const Value: Single); override;
137 end;
138
139 TOpenALSoundEngineBackend = class(TSoundEngineBackend)
140 strict private
141 FALMajorVersion, FALMinorVersion: Integer;
142 ALDevice: PALCdevice;
143 ALContext: PALCcontext;
144 FEFXSupported: boolean;
145 { ContextOpen was already called once with result @true. }
146 WasAlreadyOpen: Boolean;
147 WasAlreadyOpenDevice: String;
148
149 { Check ALC errors. Requires valid ALDevice. }
150 procedure CheckALC(const Situation: string);
151
152 { Wrapper for alcGetString. }
153 function GetContextString(const Enum: TALCenum): String;
154 private
155 ALVersion11: Boolean;
156 public
157 procedure DetectDevices(const Devices: TSoundDeviceList); override;
158 function ContextOpen(const ADevice: String; out Information, InformationSummary: String): Boolean; override;
159 procedure ContextClose; override;
160 function CreateBuffer(const SoundLoading: TSoundLoading): TSoundBufferBackend; override;
161 function CreateSource: TSoundSourceBackend; override;
162
163 procedure SetVolume(const Value: Single); override;
164 procedure SetDistanceModel(const Value: TSoundDistanceModel); override;
165 procedure SetDopplerFactor(const Value: Single); override;
166 procedure SetListener(const Position, Direction, Up: TVector3); override;
167
168 { Is the OpenAL version at least @code(AMajor.AMinor).
169 Available only when OpenAL is initialized, that is:
170 between @link(TSoundEngine.ContextOpen) and @link(TSoundEngine.ContextClose),
171 only when @link(TSoundEngine.IsContextOpenSuccess). }
172 function ALVersionAtLeast(const AMajor, AMinor: Integer): boolean;
173
174 { Are OpenAL effects (EFX) extensions supported.
175 Meaningful only after ContextOpen,
176 when IsContextOpenSuccess, that is it's initialized by . }
177 property EFXSupported: boolean read FEFXSupported;
178 end;
179
180 const
181 ALDataFormat: array [TSoundDataFormat] of TALuint = (
182 AL_FORMAT_MONO8,
183 AL_FORMAT_MONO16,
184 AL_FORMAT_STEREO8,
185 AL_FORMAT_STEREO16
186 );
187
188 { Check and report (as warnings) OpenAL errors as often as possible.
189 This is useful to localize faulty OpenAL command, that causes OpenAL error. }
190 {.$define CASTLE_OPENAL_DEBUG}
191
192 { TOpenALStreaming ----------------------------------------- }
193
194 constructor TOpenALStreaming.Create(
195 const ASoundSurce: TOpenALSoundSourceBackend;
196 const StreamBuffer: TOpenALStreamBufferBackend);
197 var
198 I: Integer;
199 NecessaryBuffers: Integer;
200 begin
201 inherited Create;
202 Source := ASoundSurce;
203 Buffer := StreamBuffer;
204
205 HelperBufferPtr := GetMem(HelperBufferSize);
206
207 { Note: It is tempting to reuse one TStreamedSoundFile instance
208 created inside FBuffer (TSoundBufferBackendFromStreamedFile class).
209 This one instance could be used to initialize
210 TSoundBufferBackendFromStreamedFile config
211 (see TSoundBufferBackendFromStreamedFile.ReadStreamConfig)
212 and be used by TOpenALStreaming too.
213
214 However, this goes badly with threads.
215 Multiple TOpenALStreaming (so also multiple threads)
216 could then access the same TStreamedSoundFile instance,
217 which is not ready for this.
218 Random errors could be observed with examples/audio/play_sounds/ .
219
220 So instead we create new TStreamedSoundFile.Create here.
221 We can use it to initialize Buffer.ReadStreamConfig
222 (useful to avoid the need to create temporary
223 TStreamedSoundFile inside Buffer.ReadStreamConfigFromTemp
224 in some situations).
225 }
226 StreamedFile := TStreamedSoundFile.Create(Buffer.Url);
227 Buffer.ReadStreamConfig(StreamedFile);
228
229 alCreateBuffers(StreamBuffersCount, @ALBuffers[Low(ALBuffers)]);
230 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alCreateBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
231
232 try
233 NecessaryBuffers := 0;
234 for I := 0 to StreamBuffersCount - 1 do
235 begin
236 { FillBuffer may return 0 if sound is non-looping and is too short
237 to need StreamBuffersCount buffers.
238 Testcase: play_sounds example,
239 play castle-data:/sounds/misc_sound-22000Hz-8bit-mono.wav
240 with slStreaming . }
241 if FillBuffer(ALBuffers[I]) = 0 then
242 Break;
243 Inc(NecessaryBuffers);
244 end;
245 except
246 alDeleteBuffers(StreamBuffersCount, @ALBuffers);
247 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alDeleteBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
248 raise;
249 end;
250
251 Assert(NecessaryBuffers > 0);
252 Assert(NecessaryBuffers <= StreamBuffersCount);
253 alSourceQueueBuffers(Source.ALSource, NecessaryBuffers, @ALBuffers[Low(ALBuffers)]);
254 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceQueueBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
255 end;
256
257 destructor TOpenALStreaming.Destroy;
258
259 procedure StopFeedingBuffers;
260 begin
261 {$ifdef CASTLE_SUPPORTS_THREADING}
262 if FeedThread <> nil then
263 begin
264 FeedThread.Terminate;
265 FeedThread.WaitFor;
266 FreeAndNil(FeedThread);
267 end;
268 {$endif}
269 end;
270
271 var
272 ALBuffersProcessed: TALint;
273 ALBuffer: TALuint;
274 I:Integer;
275 begin
276 StopFeedingBuffers;
277 Source.Stop;
278
279 { Stoping sound source mark all buffers as processed so we can delete them safely. }
280 alGetSourcei(Source.ALSource, AL_BUFFERS_PROCESSED, @ALBuffersProcessed);
281 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alGetSourcei(.., AL_BUFFERS_PROCESSED, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
282 for I := 0 to ALBuffersProcessed - 1 do
283 alSourceUnqueueBuffers(Source.ALSource, 1, @ALBuffer);
284 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceUnqueueBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
285
286 alDeleteBuffers(StreamBuffersCount, @ALBuffers[Low(ALBuffers)]);
287 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alDeleteBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
288
289 FreeAndNil(StreamedFile);
290
291 { Sound stream can be destroyed before Source, so need to fix dangling
292 pointer here. }
293 Source.FBuffer := nil;
294
295 FreeMemNiling(HelperBufferPtr);
296
297 inherited;
298 end;
299
300 procedure TOpenALStreaming.FeedBuffers;
301 begin
302 {$ifdef CASTLE_SUPPORTS_THREADING}
303 if FeedThread <> nil then
304 begin
305 FeedThread.Terminate;
306 FeedThread.WaitFor;
307 FreeAndNil(FeedThread);
308 end;
309
310 FeedThread := TOpenALStreamFeedThread.Create(true, Self);
311 FeedThread.Start;
312 {$endif}
313 end;
314
315 function TOpenALStreaming.FillBuffer(const ALBuffer: TALuint): Integer;
316 begin
317 Result := StreamedFile.Read(HelperBufferPtr^, HelperBufferSize);
318 if Result > 0 then
319 begin
320 alBufferData(ALBuffer, ALDataFormat[StreamedFile.DataFormat],
321 HelperBufferPtr, Result, StreamedFile.Frequency);
322 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alBufferData ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
323 end else
324 if Source.FLoop then
325 begin
326 StreamedFile.Rewind;
327 Result := FillBuffer(ALBuffer);
328 end;
329 end;
330
331 { TOpenALStreamFeedThread ---------------------------------------------------- }
332
333 procedure TOpenALStreamFeedThread.Execute;
334 var
335 ALBuffersProcessed: TALint;
336 ALBuffer: TALuint;
337 ALSource: TALuint;
338 begin
339 ALBuffersProcessed := 0;
340 ALSource := Streaming.Source.ALSource;
341 while (not Terminated) do
342 begin
343 Sleep(10);
344
345 alGetSourcei(ALSource, AL_BUFFERS_PROCESSED, @ALBuffersProcessed);
346 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alGetSourcei(.., AL_BUFFERS_PROCESSED, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
347
348 while ALBuffersProcessed > 0 do
349 begin
350 alSourceUnqueueBuffers(ALSource, 1, @ALBuffer);
351 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceUnqueueBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
352
353 if Streaming.FillBuffer(ALBuffer) > 0 then
354 begin
355 alSourceQueueBuffers(ALSource, 1, @ALBuffer);
356 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceQueueBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
357 end else
358 Exit;
359
360 Dec(ALBuffersProcessed);
361 end;
362
363 if not Streaming.Source.PlayingOrPaused then
364 begin
365 alSourcePlay(ALSource);
366 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcePlay ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
367 end;
368 end;
369 end;
370
371 constructor TOpenALStreamFeedThread.Create(const CreateSuspended: Boolean;
372 const AStreaming: TOpenALStreaming);
373 begin
374 inherited Create(CreateSuspended);
375 Streaming := AStreaming;
376 Assert(not FreeOnTerminate); // should be default
377 end;
378
379 { TOpenALSoundBufferBackend -------------------------------------------------- }
380
381 function TOpenALSoundBufferBackend.ALVersion11: Boolean;
382 begin
383 Result := (SoundEngine as TOpenALSoundEngineBackend).ALVersion11;
384 end;
385
386 procedure TOpenALSoundBufferBackend.ContextOpenFromSoundFile(const SoundFile: TSoundFile);
387 begin
388 inherited;
389
390 alCreateBuffers(1, @ALBuffer);
391 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alCreateBuffers ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
392 try
393 alBufferData(ALBuffer, ALDataFormat[SoundFile.DataFormat],
394 SoundFile.Data, SoundFile.DataSize, SoundFile.Frequency);
395 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alBufferData ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
396 except
397 alFreeBuffer(ALBuffer);
398 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alFreeBuffer ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
399 raise;
400 end;
401 end;
402
403 procedure TOpenALSoundBufferBackend.ContextClose;
404 begin
405 alFreeBuffer(ALBuffer);
406 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alFreeBuffer ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
407 inherited;
408 end;
409
410 { TOpenALSoundSourceBackend -------------------------------------------------- }
411
412 constructor TOpenALSoundSourceBackend.Create(const ASoundEngine: TSoundEngineBackend);
413 begin
414 inherited;
415 FSpatial := true;
416 // correspond to OpenAL defaults, https://www.openal.org/documentation/openal-1.1-specification.pdf
417 FReferenceDistance := 1;
418 FMaxDistance := MaxSingle;
419 end;
420
421 function TOpenALSoundSourceBackend.ALVersion11: Boolean;
422 begin
423 Result := (SoundEngine as TOpenALSoundEngineBackend).ALVersion11;
424 end;
425
426 procedure TOpenALSoundSourceBackend.AdjustALLooping;
427 begin
428 if FBuffer is TOpenALStreamBufferBackend then
429 alSourcei(ALSource, AL_LOOPING, BoolToAL[false])
430 else
431 alSourcei(ALSource, AL_LOOPING, BoolToAL[FLoop]);
432 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcei(.., AL_LOOPING, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
433 end;
434
435 procedure TOpenALSoundSourceBackend.ContextOpen;
436 var
437 ErrorCode: TALenum;
438 begin
439 { We have to check alGetError now, because we may need to catch
440 (and convert to ENoMoreSources exception) alGetError after
441 alCreateSources. So we want to have "clean error state" first. }
442 CheckAL('Checking before TOpenALSoundSourceBackend.ContextOpen');
443 alCreateSources(1, @ALSource);
444
445 ErrorCode := alGetError();
446 if ErrorCode = AL_INVALID_VALUE then
447 raise ENoMoreSources.Create('No more sound sources available')
448 else
449 if ErrorCode <> AL_NO_ERROR then
450 raise EALError.Create(ErrorCode,
451 'OpenAL error AL_xxx at creation of sound : ' + alGetString(ErrorCode));
452 end;
453
454 procedure TOpenALSoundSourceBackend.ContextClose;
455 begin
456 FreeAndNil(Streaming);
457 alDeleteSources(1, @ALSource);
458 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alDeleteSources ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
459 end;
460
461 function TOpenALSoundSourceBackend.PlayingOrPaused: boolean;
462 var
463 SourceState: TALuint;
464 begin
465 SourceState := alGetSource1i(ALSource, AL_SOURCE_STATE);
466 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alGetSource1i(.., AL_SOURCE_STATE) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
467 Result := (SourceState = AL_PLAYING) or (SourceState = AL_PAUSED);
468 end;
469
470 procedure TOpenALSoundSourceBackend.Play(const BufferChangedRecently: Boolean);
471 var
472 CompleteBuffer: TOpenALSoundBufferBackend;
473 begin
474 // make a clear warning when trying to play stereo sound as spatial
475 if FSpatial and
476 (FBuffer.DataFormat in [sfStereo8, sfStereo16]) then
477 WritelnWarning('Stereo sound files are *never* played as spatial by OpenAL. Convert sound file "%s" to mono (e.g. by Audacity or SOX).', [
478 UriDisplay(FBuffer.Url)
479 ]);
480
481 if FBuffer is TOpenALStreamBufferBackend then
482 begin
483 alSourcePlay(ALSource);
484 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcePlay ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
485
486 // start feed buffers thread
487 Assert(Streaming <> nil);
488 Streaming.FeedBuffers;
489 end else
490
491 if FBuffer is TOpenALSoundBufferBackend then
492 begin
493 CompleteBuffer := TOpenALSoundBufferBackend(FBuffer);
494
495 if BufferChangedRecently and
496 (CompleteBuffer <> nil) and
497 (CompleteBuffer.ALBuffer <> 0) then
498 begin
499 { This is a workaround needed on Apple OpenAL implementation
500 (although I think that at some time I experienced similar
501 problems (that would be cured by this workaround) on Linux
502 (Loki OpenAL implementation)).
503
504 The problem: music on some
505 levels doesn't play. This happens seemingly random: sometimes
506 when you load a level music starts playing, sometimes it's
507 silent. Then when you go to another level, then go back to the
508 same level, music plays.
509
510 Investigation: I found that sometimes changing the buffer
511 of the sound doesn't work immediately. Simple
512 Writeln(SoundInfos.L[Sound].Buffer, ' ',
513 alGetSource1ui(FAllocatedSource.ALSource, AL_BUFFER));
514 right after alCommonSourceSetup shows this (may output
515 two different values). Then if you wait a little, OpenAL
516 reports correct buffer. This probably means that OpenAL
517 internally finishes some tasks related to loading buffer
518 into source. Whatever it is, it seems that it doesn't
519 occur (or rather, is not noticeable) on normal game sounds
520 that are short --- but it's noticeable delay with larger
521 sounds, like typical music.
522
523 So the natural workaround below follows. For OpenAL implementations
524 that immediately load the buffer, this will not cause any delay. }
525
526 { We have to do CheckAL first, to catch eventual errors.
527 Otherwise the loop could hang. }
528 CheckAL('TOpenALSoundSourceBackend.Play');
529 while CompleteBuffer.ALBuffer <> alGetSource1ui(ALSource, AL_BUFFER) do
530 Sleep(10);
531 end;
532
533 alSourcePlay(ALSource);
534 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcePlay ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
535 end else
536
537 // ignore FBuffer = nil which may mean that streaming sound failed to load
538 if FBuffer <> nil then
539 raise EInternalError.CreateFmt('Cannot play buffer class type %s', [FBuffer.ClassName]);
540 end;
541
542 procedure TOpenALSoundSourceBackend.Stop;
543 begin
544 { Note that alSourceStop is a valid NOP for source states like
545 AL_STOPPED or AL_INITIAL. So I don't check here current state
546 (like CurrentState := alGetSource1i(ALSource, AL_SOURCE_STATE))
547 and simply always call alSourceStop. }
548 alSourceStop(ALSource);
549 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceStop ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
550 end;
551
552 procedure TOpenALSoundSourceBackend.SetPosition(const Value: TVector3);
553 begin
554 FPosition := Value;
555
556 if not FSpatial then Exit; // apply this only if Spatial
557 alSourceVector3f(ALSource, AL_POSITION, Value);
558 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceVector3f(.., AL_POSITION, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
559 end;
560
561 procedure TOpenALSoundSourceBackend.SetVelocity(const Value: TVector3);
562 begin
563 FVelocity := Value;
564
565 if not FSpatial then Exit; // apply this only if Spatial
566 alSourceVector3f(ALSource, AL_VELOCITY, Value);
567 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceVector3f(.., AL_VELOCITY, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
568 end;
569
570 procedure TOpenALSoundSourceBackend.SetLoop(const Value: boolean);
571 begin
572 { This variable is set from main thread but can be read by 2 threads (main and
573 TOpenALStreamFeedThread, but I think this is Boolean and changeing Boolean
574 value is atomic so we don't need critical section here.
575 Can be changed if that make any issues.
576 More info:
577 https://stackoverflow.com/questions/5481030/are-delphi-simple-types-thread-safe
578 }
579 FLoop := Value;
580 AdjustALLooping;
581 end;
582
583 procedure TOpenALSoundSourceBackend.SetSpatial(const Value: boolean);
584 begin
585 FSpatial := Value;
586
587 alSourcei(ALSource, AL_SOURCE_RELATIVE, BoolToAL[not Value]);
588 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcei(.., AL_SOURCE_RELATIVE, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
589
590 if not Value then
591 begin
592 { No attenuation by distance. }
593 alSourcef(ALSource, AL_ROLLOFF_FACTOR, 0);
594 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_ROLLOFF_FACTOR, 0) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
595
596 { Note: source's AL_REFERENCE_DISTANCE , AL_MAX_DISTANCE don't matter in this case. }
597
598 { Although AL_ROLLOFF_FACTOR := 0 turns off
599 attenuation by distance, we still have to turn off
600 any changes from player's orientation (so that the sound
601 is not played on left or right side, but normally). }
602 alSourceVector3f(ALSource, AL_POSITION, TVector3.Zero);
603 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceVector3f(.., AL_POSITION, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
604
605 alSourceVector3f(ALSource, AL_VELOCITY, TVector3.Zero);
606 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourceVector3f(.., AL_VELOCITY, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
607 end else
608 begin
609 { Attenuation by distance. }
610 alSourcef(ALSource, AL_ROLLOFF_FACTOR, 1);
611 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_ROLLOFF_FACTOR, 1) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
612
613 { Set everything that was kept constant when Spatial was false.
614 We rely here on the fact that SetXxx here do not ignore "setting to the same value as previous". }
615 SetPosition(FPosition);
616 SetVelocity(FVelocity);
617 SetReferenceDistance(FReferenceDistance);
618 SetMaxDistance(FMaxDistance);
619 end;
620 end;
621
622 procedure TOpenALSoundSourceBackend.SetVolume(const Value: Single);
623 begin
624 alSourcef(ALSource, AL_GAIN, Value);
625 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_GAIN, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
626 end;
627
628 procedure TOpenALSoundSourceBackend.SetMinGain(const Value: Single);
629 begin
630 alSourcef(ALSource, AL_MIN_GAIN, Value);
631 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_MIN_GAIN, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
632 end;
633
634 procedure TOpenALSoundSourceBackend.SetMaxGain(const Value: Single);
635 begin
636 alSourcef(ALSource, AL_MAX_GAIN, Value);
637 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_MAX_GAIN, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
638 end;
639
640 procedure TOpenALSoundSourceBackend.SetBuffer(const Value: TSoundBufferBackend);
641
642 { Set buffer to 0 on this OpenAL source. }
643 procedure ClearALBuffer;
644 begin
645 alSourcei(ALSource, AL_BUFFER, 0);
646 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcei(.., AL_BUFFER, 0) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
647 end;
648
649 var
650 CompleteBuffer: TOpenALSoundBufferBackend;
651 StreamBuffer: TOpenALStreamBufferBackend;
652 begin
653 { If some streamed buffer was connected to this source, disconnect it before
654 the change. }
655 FreeAndNil(Streaming);
656
657 FBuffer := Value;
658
659 if Assigned(FBuffer) then
660 begin
661 if FBuffer is TOpenALSoundBufferBackend then
662 begin
663 AdjustALLooping;
664 CompleteBuffer := TOpenALSoundBufferBackend(FBuffer);
665 { TSoundBuffer is unsigned, while alSourcei is declared as taking signed integer.
666 But we know we can pass TSoundBuffer to alSourcei, just typecasting it to
667 whatever alSourcei requires. }
668 {$I norqcheckbegin.inc}
669 alSourcei(ALSource, AL_BUFFER, CompleteBuffer.ALBuffer);
670 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcei(.., AL_BUFFER, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
671 {$I norqcheckend.inc}
672 end else
673
674 if FBuffer is TOpenALStreamBufferBackend then
675 begin
676 AdjustALLooping;
677 StreamBuffer := TOpenALStreamBufferBackend(FBuffer);
678 try
679 Streaming := TOpenALStreaming.Create(Self, StreamBuffer);
680 except
681 { Catching exceptions in case of loading errors. Because:
682 - The programs can generally tolerate missing sound files.
683 - Error at OggVorbis reading may be caused by
684 EOggVorbisMissingLibraryError, and we try to gracefully react to missing
685 libraries.
686 See TCastleSound.ReloadBuffer for the same logic and reasons
687 for non-streaming sounds. }
688 on E: ESoundFileError do
689 begin
690 WritelnWarning('Sound', Format('Sound file "%s" cannot be loaded (with streaming): %s', [
691 // Do not use FBuffer.Url, as TOpenALStreaming.Destroy set FBuffer to nil
692 UriDisplay(StreamBuffer.Url),
693 E.Message
694 ]));
695
696 // continue like no buffer was assigned
697 FBuffer := nil; // actually TOpenALStreaming.Destroy just did it
698 ClearALBuffer;
699 end;
700 end;
701 end else
702
703 raise EInternalError.CreateFmt('Cannot assign buffer class type %s', [FBuffer.ClassName]);
704 end else
705 ClearALBuffer;
706 end;
707
708 procedure TOpenALSoundSourceBackend.SetPitch(const Value: Single);
709 begin
710 alSourcef(ALSource, AL_PITCH, Value);
711 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_PITCH, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
712 end;
713
714 (*
715 procedure TOpenALSoundSourceBackend.SetRolloffFactor(const Value: Single);
716 begin
717 FRolloffFactor := Value;
718
719 if not FSpatial then Exit; // apply this only if Spatial
720 alSourcef(ALSource, AL_ROLLOFF_FACTOR, Value);
721 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_ROLLOFF_FACTOR, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
722 end;
723 *)
724
725 procedure TOpenALSoundSourceBackend.SetReferenceDistance(const Value: Single);
726 begin
727 FReferenceDistance := Value;
728
729 if not FSpatial then Exit; // apply this only if Spatial
730 alSourcef(ALSource, AL_REFERENCE_DISTANCE, Value);
731 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_REFERENCE_DISTANCE, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
732 end;
733
734 procedure TOpenALSoundSourceBackend.SetMaxDistance(const Value: Single);
735 begin
736 FMaxDistance := Value;
737
738 if not FSpatial then Exit; // apply this only if Spatial
739 alSourcef(ALSource, AL_MAX_DISTANCE, Value);
740 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alSourcef(.., AL_MAX_DISTANCE, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
741 end;
742
743 procedure TOpenALSoundSourceBackend.SetPriority(const Value: Single);
744 begin
745 { Ignored by OpenAL backend,
746 as it depends on our manual management of sound sources in TSoundAllocator. }
747 end;
748
749 function TOpenALSoundSourceBackend.GetOffset: Single;
750 begin
751 if ALVersion11 then
752 begin
753 Result := alGetSource1f(ALSource, AL_SEC_OFFSET);
754 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alGetSource1f(.., AL_SEC_OFFSET) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
755 end else
756 Result := 0;
757 end;
758
759 procedure TOpenALSoundSourceBackend.SetOffset(const Value: Single);
760 var
761 ErrorCode: TALenum;
762 begin
763 if ALVersion11 then
764 begin
765 { We have to check alGetError now, because we need to catch
766 AL_INVALID_VALUE later.
767 TODO: only warning now, occurs when switch Stream/URL of TCastleSound. }
768 CheckAL('Checking before TOpenALSoundSourceBackend.SetOffset work', true);
769
770 alSourcef(ALSource, AL_SEC_OFFSET, Value);
771
772 { capture AL_INVALID_VALUE, otherwise it would be too easy to make mistake
773 at setting offset to something like "duration-epsilon". }
774
775 ErrorCode := alGetError();
776 if ErrorCode = AL_INVALID_VALUE then
777 WritelnWarning('Ignoring TOpenALSoundSourceBackend.SetOffset with offset %f', [Value])
778 else
779 if ErrorCode <> AL_NO_ERROR then
780 raise EALError.Create(ErrorCode,
781 'OpenAL error AL_xxx at setting sound offset : ' + alGetString(ErrorCode));
782 end;
783 end;
784
785 { TOpenALSoundEngineBackend -------------------------------------------------- }
786
787 procedure TOpenALSoundEngineBackend.DetectDevices(const Devices: TSoundDeviceList);
788
789 { Find available OpenAL devices.
790
791 It tries to use ALC_ENUMERATION_EXT extension, available on all modern
792 OpenAL implementations. If it fails, and we're dealing with
793 OpenAL "sample implementation" (older OpenAL Unix implementation)
794 then we return a hardcoded list of devices known to be supported
795 by this implementation.
796 This makes it working sensibly under all OpenAL implementations in use
797 today. }
798
799 function SampleImpALCDeviceName(const ShortDeviceName: string): string;
800 begin
801 Result := '''(( devices ''(' + ShortDeviceName + ') ))';
802 end;
803
804 var
805 DeviceListPtr: PChar;
806 begin
807 if not ALLibraryAvailable then
808 WritelnWarning('Sound', 'OpenAL is not available, cannot list available audio devices')
809 else
810 if EnumerationExtPresent(DeviceListPtr) then
811 begin
812 { parse DeviceListPtr }
813 while DeviceListPtr^ <> #0 do
814 begin
815 { automatic conversion PChar -> AnsiString below }
816 Devices.Add(DeviceListPtr, DeviceListPtr);
817
818 { advance position of DeviceListPtr }
819 DeviceListPtr := StrEnd(DeviceListPtr);
820 Inc(DeviceListPtr);
821 end;
822 end else
823 begin
824 WritelnWarning('Sound', 'OpenAL does not support getting the list of available audio devices (missing ALC_ENUMERATION_EXT), probably old OpenAL.');
825
826 if OpenALSampleImplementation then
827 begin
828 Devices.Add(SampleImpALCDeviceName('native'), 'Operating System Native');
829 Devices.Add(SampleImpALCDeviceName('sdl'), 'SDL (Simple DirectMedia Layer)');
830
831 { aRts device is too unstable on my Linux:
832
833 When trying to initialize <tt>arts</tt> backend
834 I can bring the OpenAL library (and, consequently, whole program
835 using it) to crash with message <i>can't create mcop
836 directory</i>. Right after running konqueror, I get also
837 crash with message <i>*** glibc detected *** double free or corruption (out):
838 0x08538d88 ***</i>.
839
840 This is so unstable, that I think that I do a service
841 for users by *not* listing aRts in available OpenAL
842 devices. It's listed on [https://castle-engine.io/openal_notes.php]
843 and that's enough.
844
845 Devices.Add(SampleImpALCDeviceName('arts'), 'aRts (analog Real time synthesizer)');
846 }
847
848 Devices.Add(SampleImpALCDeviceName('esd'), 'Esound (Enlightened Sound Daemon)');
849 Devices.Add(SampleImpALCDeviceName('alsa'), 'ALSA (Advanced Linux Sound Architecture)');
850 Devices.Add(SampleImpALCDeviceName('waveout'), 'WAVE File Output');
851 Devices.Add(SampleImpALCDeviceName('null'), 'Null Device (No Output)');
852 end;
853 end;
854 end;
855
856 function TOpenALSoundEngineBackend.ALVersionAtLeast(const AMajor, AMinor: Integer): boolean;
857 begin
858 Result :=
859 (AMajor < FALMajorVersion) or
860 ( (AMajor = FALMajorVersion) and (AMinor <= FALMinorVersion) );
861 end;
862
863 procedure TOpenALSoundEngineBackend.CheckALC(const Situation: string);
864 var
865 ErrCode: TALenum;
866 ErrDescription: PChar;
867 ErrDescriptionStr: string;
868 begin
869 ErrCode := alcGetError(ALDevice);
870 if ErrCode <> ALC_NO_ERROR then
871 begin
872 { Secure, in case alcGetError returns nil (so the error code is incorrect),
873 which happened long time ago on Creative Windows OpenAL implementation. }
874 ErrDescription := alcGetString(ALDevice, ErrCode);
875 if ErrDescription = nil then
876 ErrDescriptionStr := Format('Unknown OpenAL (alc) error number: %d', [ErrCode])
877 else
878 ErrDescriptionStr := ErrDescription;
879
880 raise EALCError.Create(ErrCode,
881 'OpenAL error ALC_xxx at ' + Situation + ' : ' + ErrDescriptionStr);
882 end;
883 end;
884
885 function TOpenALSoundEngineBackend.GetContextString(const Enum: TALCenum): String;
886 begin
887 Result := alcGetString(ALDevice, Enum);
888 try
889 CheckALC('alcGetString');
890 { Check also normal al error (alGetError instead
891 of alcGetError). Seems that when Darwin (macOS) Apple's OpenAL
892 implementation fails to return some alcGetString
893 it reports this by setting AL error (instead of ALC one)
894 to "invalid value". Although (after fixes to detect OpenALSampleImplementation
895 at runtime and change constants values) this shouldn't happen anymore
896 if you pass correct consts to this function. }
897 CheckAL('alcGetString');
898 except
899 on E: EALCError do result := '('+E.Message+')';
900 on E: EALError do result := '('+E.Message+')';
901 end;
902 end;
903
904 function TOpenALSoundEngineBackend.ContextOpen(const ADevice: String;
905 out Information, InformationSummary: String): Boolean;
906
907 procedure ParseVersion(const Version: string; out Major, Minor: Integer);
908 var
909 DotP, SpaceP: Integer;
910 begin
911 { version unknown }
912 Major := 0;
913 Minor := 0;
914
915 DotP := Pos('.', Version);
916 if DotP <> 0 then
917 try
918 Major := StrToInt(Trim(Copy(Version, 1, DotP - 1)));
919 SpaceP := PosEx(' ', Version, DotP + 1);
920 if SpaceP <> 0 then
921 Minor := StrToInt(Trim(Copy(Version, DotP + 1, SpaceP - DotP))) else
922 Minor := StrToInt(Trim(SEnding(Version, DotP + 1)));
923 except
924 on EConvertError do
925 begin
926 Major := 0;
927 Minor := 0;
928 end;
929 end;
930 end;
931
932 function ALSuccessInformation: string;
933 begin
934 Result := Format(
935 'OpenAL version: %s (major: %d, minor: %d)' +NL+
936 'Renderer: %s' +NL+
937 'Vendor: %s' +NL+
938 'Extensions: %s', [
939 alGetString(AL_VERSION),
940 FALMajorVersion, FALMinorVersion,
941 alGetString(AL_RENDERER),
942 alGetString(AL_VENDOR),
943 alGetString(AL_EXTENSIONS)
944 ]);
945 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alGetString ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
946 end;
947
948 function ALSuccessInformationSummary: string;
949 begin
950 Result := Format('OpenAL %d.%d', [
951 FALMajorVersion,
952 FALMinorVersion
953 ]);
954 end;
955
956 var
957 ErrMessage: String;
958 begin
959 { Workaround old OpenAL problems when trying to initialize OpenAL context again
960 with another device. }
961 if WasAlreadyOpen and (WasAlreadyOpenDevice <> ADevice) then
962 OpenALRestart;
963
964 { Try to initialize OpenAL.
965 Sets Information, EFXSupported. }
966
967 { We don't do alcProcessContext/alcSuspendContext, no need
968 (spec says that context is initially in processing state). }
969
970 Result := false;
971 try
972 //raise EOpenALError.Create('Test pretend OpenAL fails');
973
974 FEFXSupported := false;
975 Information := '';
976 InformationSummary := '';
977 FALMajorVersion := 0;
978 FALMinorVersion := 0;
979
980 if not ALLibraryAvailable then
981 raise EOpenALInitError.Create('OpenAL library is not available');
982
983 Assert(Assigned(alcOpenDevice), 'Assigned(alcOpenDevice)');
984
985 ALDevice := alcOpenDevice(PCharOrNil(ADevice));
986 if ALDevice = nil then
987 begin
988 ErrMessage := Format('OpenAL audio device "%s" is not available', [ADevice]);
989 {$ifdef MSWINDOWS}
990 if ADevice = '' then
991 ErrMessage := ErrMessage + '.' + NL + 'Note: It seems that even the default audio device is unavailable. ' + 'Please check that you have all the necessary OpenAL DLL files present (alongside the exe file, or on $PATH). In case of standard Windows OpenAL implementation, you should have OpenAL32.dll and wrap_oal.dll present.';
992 {$endif}
993 raise EOpenALError.Create(ErrMessage);
994 end;
995
996 ALContext := alcCreateContext(ALDevice, nil);
997 CheckALC('initializing OpenAL (alcCreateContext)');
998
999 alcMakeContextCurrent(ALContext);
1000 CheckALC('initializing OpenAL (alcMakeContextCurrent)');
1001
1002 FEFXSupported := Load_EFX(ALDevice);
1003
1004 ParseVersion(alGetString(AL_VERSION), FALMajorVersion, FALMinorVersion);
1005 ALVersion11 := ALVersionAtLeast(1, 1);
1006
1007 Result := true;
1008 Information := ALSuccessInformation;
1009 InformationSummary := ALSuccessInformationSummary;
1010 WasAlreadyOpen := true;
1011 WasAlreadyOpenDevice := ADevice;
1012 except
1013 on E: EOpenALError do
1014 begin
1015 Information := E.Message;
1016 InformationSummary := Information;
1017 end;
1018 end;
1019 end;
1020
1021 procedure TOpenALSoundEngineBackend.ContextClose;
1022 begin
1023 FEFXSupported := false;
1024
1025 { CheckALC first, in case some error is "hanging" not caught yet. }
1026 CheckALC('right before closing OpenAL context');
1027
1028 if ALContext <> nil then
1029 begin
1030 (* The OpenAL specification says
1031
1032 "The correct way to destroy a context is to first release
1033 it using alcMakeCurrent with a NULL context. Applications
1034 should not attempt to destroy a current context – doing so
1035 will not work and will result in an ALC_INVALID_OPERATION error."
1036
1037 (See [http://openal.org/openal_webstf/specs/oal11spec_html/oal11spec6.html])
1038
1039 However, sample implementation (used on most Unixes,
1040 before OpenAL soft came) can hang
1041 on alcMakeContextCurrent(nil) call. Actually, it doesn't hang,
1042 but it stops for a *very* long time (even a couple of minutes).
1043 This is a known problem, see
1044 [http://opensource.creative.com/pipermail/openal-devel/2005-March/002823.html]
1045 and
1046 [http://lists.berlios.de/pipermail/warzone-dev/2005-August/000441.html].
1047
1048 Tremulous code workarounds it like
1049
1050 if( Q_stricmp((const char* )qalGetString( AL_VENDOR ), "J. Valenzuela" ) ) {
1051 qalcMakeContextCurrent( NULL );
1052 }
1053
1054 ... and this seems a good idea, we do it also here.
1055 Initially I wanted to do $ifdef UNIX, but checking for Sample implementation
1056 with alGetString(AL_VENDOR) is more elegant (i.e. affecting more precisely
1057 the problematic OpenAL implementations, e.g. allowing us to work
1058 correctly with OpenAL soft too). *)
1059
1060 if not OpenALSampleImplementation then
1061 alcMakeContextCurrent(nil);
1062
1063 alcDestroyContext(ALContext);
1064 ALContext := nil;
1065 CheckALC('closing OpenAL context');
1066 end;
1067
1068 if ALDevice <> nil then
1069 begin
1070 alcCloseDevice(ALDevice);
1071 { w/g specyfikacji OpenAL generuje teraz error ALC_INVALID_DEVICE jesli
1072 device bylo nieprawidlowe; ale niby jak mam sprawdzic ten blad ?
1073 Przeciez zeby sprawdzic alcGetError potrzebuje miec valid device w reku,
1074 a po wywolaniu alcCloseDevice(device) device jest invalid (bez wzgledu
1075 na czy przed wywolaniem alcCloseDevice bylo valid) }
1076 ALDevice := nil;
1077 end;
1078 end;
1079
1080 procedure TOpenALSoundEngineBackend.SetVolume(const Value: Single);
1081 begin
1082 alListenerf(AL_GAIN, Value);
1083 end;
1084
1085 procedure TOpenALSoundEngineBackend.SetDistanceModel(const Value: TSoundDistanceModel);
1086 const
1087 ALDistanceModelConsts: array [TSoundDistanceModel] of TALenum = (
1088 AL_INVERSE_DISTANCE_CLAMPED,
1089 AL_LINEAR_DISTANCE_CLAMPED
1090 );
1091 begin
1092 { Note:
1093
1094 Initially we supported all OpenAL distance models:
1095
1096 TSoundDistanceModel = (dmNone,
1097 dmInverseDistance , dmInverseDistanceClamped,
1098 dmLinearDistance , dmLinearDistanceClamped,
1099 dmExponentDistance, dmExponentDistanceClamped);
1100
1101 mapping to
1102
1103 const
1104 ALDistanceModelConsts: array [TSoundDistanceModel] of TALenum = (
1105 AL_NONE,
1106 AL_INVERSE_DISTANCE,
1107 AL_INVERSE_DISTANCE_CLAMPED,
1108 AL_LINEAR_DISTANCE, //< only OpenAL >= 1.1
1109 AL_LINEAR_DISTANCE_CLAMPED, //< only OpenAL >= 1.1
1110 AL_EXPONENT_DISTANCE, //< only OpenAL >= 1.1
1111 AL_EXPONENT_DISTANCE_CLAMPED //< only OpenAL >= 1.1
1112 );
1113
1114 Now we support only a subset of distance models, that is common to
1115 OpenAL ( https://www.openal.org/documentation/openal-1.1-specification.pdf ),
1116 FMOD ( https://www.fmod.com/resources/documentation-api?version=2.01&page=white-papers-3d-sounds.html#inverse ).
1117
1118 Some models are actually available only since OpenAL 1.1
1119 version. We eventually may fallback on some other model.
1120 This is not be a problem in practice, as all modern OS
1121 versions (Linux distros, Windows OpenAL installers etc.) include OpenAL 1.1. }
1122
1123 (* Old version, for all models:
1124
1125 if (not ALVersion11) and (Value in [dmLinearDistance, dmExponentDistance]) then
1126 alDistanceModel(AL_INVERSE_DISTANCE)
1127 else
1128 if (not ALVersion11) and (Value in [dmLinearDistanceClamped, dmExponentDistanceClamped]) then
1129 alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED)
1130 else
1131 alDistanceModel(ALDistanceModelConsts[Value]);
1132 *)
1133
1134 if (not ALVersion11) and (Value = dmLinear) then
1135 alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED) // OpenAL < 1.1 doesn't support AL_LINEAR_DISTANCE* models.
1136 else
1137 alDistanceModel(ALDistanceModelConsts[Value]);
1138 end;
1139
1140 procedure TOpenALSoundEngineBackend.SetDopplerFactor(const Value: Single);
1141 begin
1142 alDopplerFactor(Value);
1143 end;
1144
1145 procedure TOpenALSoundEngineBackend.SetListener(const Position, Direction, Up: TVector3);
1146 begin
1147 alListenerVector3f(AL_POSITION, Position);
1148 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alListenerVector3f(AL_POSITION, ..) ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
1149 alListenerOrientation(Direction, Up);
1150 {$ifdef CASTLE_OPENAL_DEBUG} CheckAL('alListenerOrientation ' + {$include %FILE%} + ':' + {$include %LINE%}, true); {$endif}
1151 end;
1152
1153 function TOpenALSoundEngineBackend.CreateBuffer(const SoundLoading: TSoundLoading): TSoundBufferBackend;
1154 begin
1155 {$ifdef CASTLE_SUPPORTS_THREADING}
1156 case SoundLoading of
1157 slComplete : Result := TOpenALSoundBufferBackend.Create(Self);
1158 slStreaming: Result := TOpenALStreamBufferBackend.Create(Self);
1159 {$ifndef COMPILER_CASE_ANALYSIS}
1160 else raise EInternalError.Create('TOpenALSoundEngineBackend.CreateBuffer: Invalid SoundLoading');
1161 {$endif}
1162 end;
1163 {$else}
1164 Result := TOpenALSoundBufferBackend.Create(Self);
1165 {$endif}
1166 end;
1167
1168 function TOpenALSoundEngineBackend.CreateSource: TSoundSourceBackend;
1169 begin
1170 Result := TOpenALSoundSourceBackend.Create(Self);
1171 end;
1172
1173 { globals -------------------------------------------------------------------- }
1174
1175 procedure UseOpenALSoundBackend;
1176 begin
1177 SoundEngine.InternalBackend := TOpenALSoundEngineBackend.Create;
1178 end;
1179
1180 end.