1 (* Copyright (C) Doom 2D: Forever Developers
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 {$IFDEF USE_MEMPOOL}mempool,{$ENDIF}
33 TBasicSound = class{$IFDEF USE_MEMPOOL}(TPoolObject){$ENDIF}
39 function InvalidSource(): Boolean; inline;
46 function RawPlay(Pan: Single; Volume: Single; aPos: DWORD): Boolean;
50 destructor Destroy(); override;
51 procedure SetID(ID: DWORD);
52 procedure FreeSound();
53 function IsPlaying(): Boolean;
55 function IsPaused(): Boolean;
56 procedure Pause(Enable: Boolean);
57 function GetVolume(): Single;
58 procedure SetVolume(Volume: Single);
59 function GetPan(): Single;
60 procedure SetPan(Pan: Single);
61 function IsMuted(): Boolean;
62 procedure Mute(Enable: Boolean);
63 function GetPosition(): DWORD;
64 procedure SetPosition(aPos: DWORD);
65 procedure SetPriority(priority: Integer);
69 NO_SOUND_ID = DWORD(-1);
71 function e_InitSoundSystem(NoOutput: Boolean = False): Boolean;
73 function e_LoadSound(FileName: string; var ID: DWORD; isMusic: Boolean; ForceNoLoop: Boolean = False): Boolean;
74 function e_LoadSoundMem(pData: Pointer; Length: Integer; var ID: DWORD; isMusic: Boolean; ForceNoLoop: Boolean = False): Boolean;
76 function e_PlaySound(ID: DWORD): Integer;
77 function e_PlaySoundPan(ID: DWORD; Pan: Single): Integer;
78 function e_PlaySoundVolume(ID: DWORD; Volume: Single): Integer;
79 function e_PlaySoundPanVolume(ID: DWORD; Pan, Volume: Single): Integer;
81 procedure e_ModifyChannelsVolumes(SoundMod: Single; setMode: Boolean);
82 procedure e_MuteChannels(Enable: Boolean);
83 procedure e_StopChannels();
85 procedure e_DeleteSound(ID: DWORD);
86 procedure e_RemoveAllSounds();
87 procedure e_ReleaseSoundSystem();
88 procedure e_SoundUpdate();
91 e_SoundFormat: TSoundFormat; // desired sound format
92 e_SoundsArray: array of TSoundRec = nil;
93 e_ZeroPosition: array [0..2] of ALfloat = (0, 0, 0);
94 e_ALError: ALenum = 0;
95 e_SoundFont: string = '';
96 e_MusicLerp: Boolean = True;
104 NUM_SOURCES = 255; // + 1 stereo
105 NUM_STREAM_BUFFERS = 8;
106 STREAM_BUFSIZE = 8192;
110 SoundMuted: Boolean = False;
111 CurStream: DWORD = NO_SOUND_ID;
112 alDevice: PALCdevice = nil;
113 alContext: PALCcontext = nil;
114 // sources for everything
115 alSources: array [0..NUM_SOURCES] of ALuint;
116 // last TBasicSound that has played on each source
117 alOwners: array [0..NUM_SOURCES] of TBasicSound;
118 // buffers for the music stream
119 alStreamBufs: array [0..NUM_STREAM_BUFFERS-1] of ALuint;
120 alStreamData: array [0..STREAM_BUFSIZE-1] of Byte;
121 alStreamAvail: Integer = NUM_STREAM_BUFFERS;
123 {$IFNDEF OPENAL_SINGLETHREADED}
125 StreamThread: TThreadID = NilThreadId;
126 StreamThreadRunning: Boolean = False;
127 StreamLock: TRTLCriticalSection;
128 StreamBufTime: Integer = 100; // time to sleep between buffer checks
130 procedure UpdateStreamSource(Src: Integer); forward;
132 function StreamThreadProc(Param: Pointer): PtrInt;
134 while StreamThreadRunning do
136 EnterCriticalSection(StreamLock);
137 UpdateStreamSource(MUSIC_SOURCE);
138 LeaveCriticalSection(StreamLock);
139 Sleep(StreamBufTime);
145 function CheckALError(): Boolean;
147 e_ALError := alGetError();
148 Result := e_ALError <> AL_NO_ERROR;
151 function GetALError(): string;
155 AL_NO_ERROR: Result := '';
156 AL_INVALID_NAME: Result := 'AL_INVALID_NAME';
157 AL_INVALID_ENUM: Result := 'AL_INVALID_ENUM';
158 AL_INVALID_VALUE: Result := 'AL_INVALID_VALUE';
159 AL_INVALID_OPERATION: Result := 'AL_INVALID_OPERATION';
160 AL_OUT_OF_MEMORY: Result := 'AL_OUT_OF_MEMORY';
161 else Result := Format('unknown error %x', [e_ALError]);
165 function e_InitSoundSystem(NoOutput: Boolean = False): Boolean;
167 alExt, alRend, alVendor, alVer: string;
168 WantDev: string = '';
169 WantAttrs: array [0..4] of ALCint = (
170 ALC_STEREO_SOURCES, 1,
171 ALC_MONO_SOURCES, NUM_SOURCES,
177 WantDev := alcGetString(nil, ALC_DEVICE_SPECIFIER);
178 e_LogWritefln('AL: available devices: %s', [WantDev]);
180 // TODO: open a dummy device when NoOutput is true or something
181 WantDev := alcGetString(nil, ALC_DEFAULT_DEVICE_SPECIFIER);
182 e_LogWritefln('AL: trying to open device %s', [WantDev]);
184 alDevice := alcOpenDevice(PChar(WantDev));
185 if alDevice = nil then
187 e_LogWritefln('AL: ERROR: could not open device %s: %s', [WantDev, GetALError()]);
191 alContext := alcCreateContext(alDevice, WantAttrs);
192 if alContext = nil then
194 e_LogWritefln('AL: ERROR: could not create context: %s', [GetALError()]);
195 alcCloseDevice(alDevice);
200 alcMakeContextCurrent(alContext);
202 // TODO: actually parse these from alc attributes or something
203 e_SoundFormat.SampleRate := 48000;
204 e_SoundFormat.SampleBits := 16;
205 e_SoundFormat.Channels := 2;
207 alVendor := alGetString(AL_VENDOR);
208 alRend := alGetString(AL_RENDERER);
209 alVer := alGetString(AL_VERSION);
210 alExt := alGetString(AL_EXTENSIONS);
212 e_LogWriteln('AL INFO:');
213 e_LogWriteln(' Version: ' + alVer);
214 e_LogWriteln(' Vendor: ' + alVendor);
215 e_LogWriteln(' Renderer: ' + alRend);
216 e_LogWriteln(' Device: ' + WantDev);
217 e_LogWriteln(' Sample rate: ' + IntToStr(e_SoundFormat.SampleRate));
218 e_LogWriteln(' Extensions:');
219 e_LogWriteln(' ' + alExt);
221 ZeroMemory(@alSources[0], sizeof(alSources));
222 ZeroMemory(@alOwners[0], sizeof(alOwners));
223 ZeroMemory(@alStreamBufs[0], sizeof(alStreamBufs));
224 ZeroMemory(@alStreamData[0], sizeof(alStreamData));
225 CurStream := NO_SOUND_ID;
227 alGetError(); // reset the goddamn error state
228 alGenSources(1, @alSources[0]); // generate the music source
229 if CheckALError() then
230 e_LogWriteln('AL: ERROR: alGenSources() for music failed: ' + GetALError());
233 alGenBuffers(NUM_STREAM_BUFFERS, @alStreamBufs[0]); // generate buffers for the music stream
234 if CheckALError() then
235 e_LogWriteln('AL: ERROR: alGenSources() for music failed: ' + GetALError())
237 alStreamAvail := NUM_STREAM_BUFFERS;
239 {$IFNDEF OPENAL_SINGLETHREADED}
240 InitCriticalSection(StreamLock);
241 StreamThreadRunning := True;
242 StreamThread := BeginThread(Addr(StreamThreadProc));
248 function FindESound(): DWORD;
253 if e_SoundsArray <> nil then
254 for i := 0 to High(e_SoundsArray) do
255 if (e_SoundsArray[i].alBuffer = 0) and (e_SoundsArray[i].Loader = nil) then
261 if e_SoundsArray = nil then
263 SetLength(e_SoundsArray, 16);
268 Result := High(e_SoundsArray) + 1;
269 SetLength(e_SoundsArray, Length(e_SoundsArray) + 16);
273 function GetALSoundFormat(Fmt: TSoundFormat): ALenum; inline;
275 if Fmt.Channels = 2 then
277 if Fmt.SampleBits = 16 then
278 Result := AL_FORMAT_STEREO16
280 Result := AL_FORMAT_STEREO8;
284 if Fmt.SampleBits = 16 then
285 Result := AL_FORMAT_MONO16
287 Result := AL_FORMAT_MONO8;
291 function GetALSourceState(S: ALuint): ALint; inline;
293 alGetSourcei(S, AL_SOURCE_STATE, Result);
296 function LoadEntireSound(var Snd: TSoundRec; Loader: TSoundLoader): Boolean;
301 DataLen, OldLen: LongWord;
303 CHUNK_SIZE = 65536 * 2 * 2;
307 Frame := GetMem(CHUNK_SIZE);
308 if Frame = nil then exit;
314 Rx := Loader.FillBuffer(Frame, CHUNK_SIZE);
315 if Rx = 0 then break;
318 DataLen := DataLen + Rx;
319 Data := ReAllocMem(Data, DataLen);
320 if Data = nil then begin FreeMem(Frame); exit; end;
322 Move(Frame^, (Data + OldLen)^, Rx);
323 until Loader.Finished();
327 alGenBuffers(1, Addr(Snd.alBuffer));
328 if CheckALError() then
330 e_LogWritefln('AL: Could not create AL buffer: %s', [GetALError()]);
337 GetALSoundFormat(Loader.Format),
340 Loader.Format.SampleRate
345 if CheckALError() then
347 e_LogWriteln('AL: Could not fill AL buffer: ' + GetALError());
348 alDeleteBuffers(1, Addr(Snd.alBuffer));
356 function e_LoadSound(FileName: String; var ID: DWORD; isMusic: Boolean; ForceNoLoop: Boolean = False): Boolean;
359 Loader: TSoundLoader;
364 find_id := FindESound();
366 e_SoundsArray[find_id].Loader := nil;
367 e_SoundsArray[find_id].isMusic := isMusic;
368 e_SoundsArray[find_id].Loops := isMusic and not ForceNoLoop;
369 e_SoundsArray[find_id].nRefs := 0;
371 Loader := e_GetSoundLoader(FileName);
374 e_LogWritefln('Could not find loader for sound `%s`', [FileName]);
378 if not Loader.Load(FileName, e_SoundsArray[find_id].Loops) then
380 e_LogWritefln('Could not load sound `%s`', [FileName]);
384 alGetError(); // reset error state, god damn it
388 if not LoadEntireSound(e_SoundsArray[find_id], Loader) then
389 e_LogWritefln('AL: Could not buffer sound effect `%s`', [FileName]);
390 // don't need this anymore
396 e_SoundsArray[find_id].alBuffer := 0;
397 e_SoundsArray[find_id].Loader := Loader;
404 function e_LoadSoundMem(pData: Pointer; Length: Integer; var ID: DWORD; isMusic: Boolean; ForceNoLoop: Boolean = False): Boolean;
407 Loader: TSoundLoader;
412 find_id := FindESound();
414 e_SoundsArray[find_id].Loader := nil;
415 e_SoundsArray[find_id].isMusic := isMusic;
416 e_SoundsArray[find_id].Loops := isMusic and not ForceNoLoop;
417 e_SoundsArray[find_id].nRefs := 0;
419 Loader := e_GetSoundLoader(pData, LongWord(Length));
422 e_LogWritefln('Could not find loader for sound `%p`', [pData]);
426 if not Loader.Load(pData, LongWord(Length), e_SoundsArray[find_id].Loops) then
428 e_LogWritefln('Could not load sound `%p`', [pData]);
432 alGetError(); // reset error state, god damn it
436 if not LoadEntireSound(e_SoundsArray[find_id], Loader) then
437 e_LogWritefln('AL: Could not buffer sound effect `%p`', [pData]);
438 // don't need this anymore
444 e_SoundsArray[find_id].alBuffer := 0;
445 e_SoundsArray[find_id].Loader := Loader;
448 // the calling side won't free this, the loader will get a copy, so fuck it
454 function FindSourceForSound(ID: DWORD): Integer;
459 if ID > High(e_SoundsArray) then
462 if e_SoundsArray[ID].Loader <> nil then
464 // first source is for streaming sounds
466 alOwners[MUSIC_SOURCE] := nil;
467 Result := MUSIC_SOURCE;
471 for S := 1 to High(alSources) do
472 if alSources[S] = 0 then
474 alOwners[S] := nil; // TBasicSounds will set this if needed
479 if Result = -1 then Exit; // no voices left
481 alGetError(); // reset error state
482 alGenSources(1, @alSources[Result]);
483 if CheckALError() then
485 e_LogWriteln('AL: FindSourceForSound(): alGenSources() failed: ' + GetALError());
490 procedure AssignSound(ID: DWORD; Src: ALuint); inline;
494 alGetError(); // reset error state
496 if e_SoundsArray[ID].Loader <> nil then
499 {$IFNDEF OPENAL_SINGLETHREADED}
500 // lock the stream so the stream thread doesn't shit itself
501 EnterCriticalSection(StreamLock);
502 // number of stereo samples / samplerate =
503 // time until buffer runs out
505 (STREAM_BUFSIZE div (2 * e_SoundsArray[ID].Loader.Format.SampleBits div 8)) div
506 (e_SoundsArray[ID].Loader.Format.SampleRate div 1000) - 1;
507 if StreamBufTime < 1 then StreamBufTime := 1;
508 e_LogWritefln('sleep time = %d', [StreamBufTime]);
511 e_SoundsArray[ID].Loader.Restart();
512 if CurStream <> ID then // changing streams
514 alSourceStop(Src); // this should mark all buffers as processed
515 alGetSourcei(Src, AL_BUFFERS_PROCESSED, S);
516 // unqueue all buffers
519 alSourceUnqueueBuffers(Src, S, @alStreamBufs[alStreamAvail]);
520 alStreamAvail := NUM_STREAM_BUFFERS;
523 // this shit is playing now
525 {$IFNDEF OPENAL_SINGLETHREADED}
527 LeaveCriticalSection(StreamLock);
532 // this is a full chunk, assign local buffer
533 alSourcei(Src, AL_BUFFER, e_SoundsArray[ID].alBuffer);
535 if (e_SoundsArray[ID].Loops) then
536 alSourcei(Src, AL_LOOPING, AL_TRUE)
538 alSourcei(Src, AL_LOOPING, AL_FALSE);
541 alSourcei(Src, AL_SOURCE_RELATIVE, AL_TRUE);
544 function e_PlaySound(ID: DWORD): Integer;
546 Result := FindSourceForSound(ID);
549 AssignSound(ID, alSources[Result]);
550 alSourcef(alSources[Result], AL_GAIN, 1);
551 alSourcefv(alSources[Result], AL_POSITION, e_ZeroPosition);
552 alSourcePlay(alSources[Result]);
556 function e_PlaySoundPan(ID: DWORD; Pan: Single): Integer;
558 Pos: array [0..2] of ALfloat;
560 Result := FindSourceForSound(ID);
566 AssignSound(ID, alSources[Result]);
567 alSourcef(alSources[Result], AL_GAIN, 1);
568 alSourcefv(alSources[Result], AL_POSITION, Pos);
569 alSourcePlay(alSources[Result]);
573 function e_PlaySoundVolume(ID: DWORD; Volume: Single): Integer;
575 Result := FindSourceForSound(ID);
578 AssignSound(ID, alSources[Result]);
579 alSourcef(alSources[Result], AL_GAIN, Volume);
580 alSourcefv(alSources[Result], AL_POSITION, e_ZeroPosition);
581 alSourcePlay(alSources[Result]);
585 function e_PlaySoundPanVolume(ID: DWORD; Pan, Volume: Single): Integer;
587 Pos: array [0..2] of ALfloat;
589 Result := FindSourceForSound(ID);
595 AssignSound(ID, alSources[Result]);
596 alSourcefv(alSources[Result], AL_POSITION, Pos);
597 alSourcef(alSources[Result], AL_GAIN, Volume);
598 alSourcePlay(alSources[Result]);
602 procedure e_DeleteSound(ID: DWORD);
604 if ID > High(e_SoundsArray) then
606 if (e_SoundsArray[ID].alBuffer <> 0) then
608 alDeleteBuffers(1, Addr(e_SoundsArray[ID].alBuffer));
609 e_SoundsArray[ID].alBuffer := 0;
611 if (e_SoundsArray[ID].Loader <> nil) then
613 e_SoundsArray[ID].Loader.Free();
614 e_SoundsArray[ID].Loader := nil;
615 if ID = CurStream then
616 CurStream := NO_SOUND_ID;
620 procedure e_ModifyChannelsVolumes(SoundMod: Single; setMode: Boolean);
625 // TODO: replace manual volume calculations everywhere with
626 // alListenerf(AL_GAIN) or something
629 for S := 1 to High(alSources) do
630 if alSources[S] <> 0 then
631 alSourcef(alSources[S], AL_GAIN, SoundMod)
635 for S := 1 to High(alSources) do
636 if alSources[S] <> 0 then
638 alGetSourcef(alSources[S], AL_GAIN, V);
639 alSourcef(alSources[S], AL_GAIN, V * SoundMod);
644 procedure e_MuteChannels(Enable: Boolean);
646 if Enable = SoundMuted then
649 SoundMuted := Enable;
652 procedure e_StopChannels();
656 alGetError(); // reset error state
657 for S := Low(alSources) to High(alSources) do
658 if (alSources[S] <> 0) and (GetALSourceState(alSources[S]) = AL_PLAYING) then
660 alSourceStop(alSources[S]);
661 alDeleteSources(1, @alSources[S]);
666 procedure e_RemoveAllSounds();
670 for i := 0 to High(e_SoundsArray) do
671 if e_SoundsArray[i].alBuffer <> 0 then
673 SetLength(e_SoundsArray, 0);
674 e_SoundsArray := nil;
675 CurStream := NO_SOUND_ID;
678 procedure e_ReleaseSoundSystem();
680 {$IFNDEF OPENAL_SINGLETHREADED}
681 if StreamThread <> NilThreadId then
683 StreamThreadRunning := False;
684 WaitForThreadTerminate(StreamThread, 66666);
685 StreamThread := NilThreadId;
686 DoneCriticalSection(StreamLock);
692 alcMakeContextCurrent(nil);
693 alcDestroyContext(alContext);
694 alcCloseDevice(alDevice);
700 procedure UpdateStreamSource(Src: Integer);
706 if alSources[Src] = 0 then Exit;
708 alGetError(); // reset error state
710 alGetSourcei(alSources[Src], AL_BUFFERS_PROCESSED, S);
711 // unqueue processed buffers
714 alSourceUnqueueBuffers(alSources[Src], S, @alStreamBufs[alStreamAvail]);
715 alStreamAvail := alStreamAvail + S;
718 alGetError(); // reset error state
720 if (alStreamAvail > 0) and (CurStream <> NO_SOUND_ID) then
722 // some buffers have freed up, advance stream playback
723 OutLen := e_SoundsArray[CurStream].Loader.FillBuffer(@alStreamData[0], STREAM_BUFSIZE);
724 if OutLen = 0 then Exit; // ran out of stream
725 Buf := alStreamBufs[alStreamAvail-1];
730 GetALSoundFormat(e_SoundsArray[CurStream].Loader.Format),
733 e_SoundsArray[CurStream].Loader.Format.SampleRate
736 alSourceQueueBuffers(alSources[Src], 1, @Buf);
738 S := GetALSourceState(alSources[Src]);
739 if (S = AL_STOPPED) or (S = AL_INITIAL) then
740 alSourcePlay(alSources[Src]);
744 procedure e_SoundUpdate();
748 alGetError(); // reset error state
750 // clear out all stopped sources
751 for S := 1 to High(alSources) do
752 if (alSources[S] <> 0) and (GetALSourceState(alSources[S]) = AL_STOPPED) then
754 alDeleteSources(1, @alSources[S]);
759 {$IFDEF OPENAL_SINGLETHREADED}
760 // update the stream sources
761 UpdateStreamSource(MUSIC_SOURCE);
767 constructor TBasicSound.Create();
777 destructor TBasicSound.Destroy();
783 function TBasicSound.InvalidSource(): Boolean; inline;
785 Result := (FSource < 0) or (alSources[FSource] = 0) or (alOwners[FSource] <> self);
788 procedure TBasicSound.FreeSound();
790 if FID = NO_SOUND_ID then
799 function TBasicSound.RawPlay(Pan: Single; Volume: Single; aPos: DWORD): Boolean;
802 if FID = NO_SOUND_ID then Exit;
804 if e_SoundsArray[FID].nRefs >= gMaxSimSounds then
810 FSource := e_PlaySoundPanVolume(FID, Pan, Volume);
813 alOwners[FSource] := self;
818 procedure TBasicSound.SetID(ID: DWORD);
822 if ID > High(e_SoundsArray) then
826 FMusic := e_SoundsArray[ID].isMusic;
829 function TBasicSound.IsPlaying(): Boolean;
832 if InvalidSource() then
834 Result := GetALSourceState(alSources[FSource]) = AL_PLAYING;
837 procedure TBasicSound.Stop();
839 if FID = CurStream then
840 CurStream := NO_SOUND_ID;
841 if InvalidSource() then
844 alSourceStop(alSources[FSource]);
847 function TBasicSound.IsPaused(): Boolean;
850 if InvalidSource() then
852 Result := GetALSourceState(alSources[FSource]) = AL_PAUSED;
855 procedure TBasicSound.Pause(Enable: Boolean);
857 if InvalidSource() then
860 alSourcePause(alSources[FSource])
862 alSourcePlay(alSources[FSource]);
865 function TBasicSound.GetVolume(): Single;
868 if InvalidSource() then
870 alGetSourcef(alSources[FSource], AL_GAIN, Result);
873 procedure TBasicSound.SetVolume(Volume: Single);
875 if InvalidSource() then
877 alSourcef(alSources[FSource], AL_GAIN, Volume);
880 function TBasicSound.GetPan(): Single;
882 Pos: array [0..2] of ALfloat = (0, 0, 0);
885 if InvalidSource() then
887 alGetSourcefv(alSources[FSource], AL_POSITION, Pos);
891 procedure TBasicSound.SetPan(Pan: Single);
893 Pos: array [0..2] of ALfloat;
895 if InvalidSource() then
900 alSourcefv(alSources[FSource], AL_POSITION, Pos);
903 function TBasicSound.IsMuted(): Boolean;
905 if InvalidSource() then
911 procedure TBasicSound.Mute(Enable: Boolean);
913 if InvalidSource() then
917 FOldGain := GetVolume();
928 function TBasicSound.GetPosition(): DWORD;
933 if InvalidSource() then
935 alGetSourcei(alSources[FSource], AL_BYTE_OFFSET, Bytes);
940 procedure TBasicSound.SetPosition(aPos: DWORD);
943 if InvalidSource() then
945 alSourcei(alSources[FSource], AL_BYTE_OFFSET, aPos);
948 procedure TBasicSound.SetPriority(priority: Integer);