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 function CheckALError(): Boolean;
125 e_ALError := alGetError();
126 Result := e_ALError <> AL_NO_ERROR;
129 function GetALError(): string;
133 AL_NO_ERROR: Result := '';
134 AL_INVALID_NAME: Result := 'AL_INVALID_NAME';
135 AL_INVALID_ENUM: Result := 'AL_INVALID_ENUM';
136 AL_INVALID_VALUE: Result := 'AL_INVALID_VALUE';
137 AL_INVALID_OPERATION: Result := 'AL_INVALID_OPERATION';
138 AL_OUT_OF_MEMORY: Result := 'AL_OUT_OF_MEMORY';
139 else Result := Format('unknown error %x', [e_ALError]);
143 function e_InitSoundSystem(NoOutput: Boolean = False): Boolean;
145 alExt, alRend, alVendor, alVer: string;
146 WantDev: string = '';
147 WantAttrs: array [0..4] of ALCint = (
148 ALC_STEREO_SOURCES, 1,
149 ALC_MONO_SOURCES, NUM_SOURCES,
155 WantDev := alcGetString(nil, ALC_DEVICE_SPECIFIER);
156 e_LogWritefln('AL: available devices: %s', [WantDev]);
158 // TODO: open a dummy device when NoOutput is true or something
159 WantDev := alcGetString(nil, ALC_DEFAULT_DEVICE_SPECIFIER);
160 e_LogWritefln('AL: trying to open device %s', [WantDev]);
162 alDevice := alcOpenDevice(PChar(WantDev));
163 if alDevice = nil then
165 e_LogWritefln('AL: ERROR: could not open device %s: %s', [WantDev, GetALError()]);
169 alContext := alcCreateContext(alDevice, WantAttrs);
170 if alContext = nil then
172 e_LogWritefln('AL: ERROR: could not create context: %s', [GetALError()]);
173 alcCloseDevice(alDevice);
178 alcMakeContextCurrent(alContext);
180 // TODO: actually parse these from alc attributes or something
181 e_SoundFormat.SampleRate := 48000;
182 e_SoundFormat.SampleBits := 16;
183 e_SoundFormat.Channels := 2;
185 alVendor := alGetString(AL_VENDOR);
186 alRend := alGetString(AL_RENDERER);
187 alVer := alGetString(AL_VERSION);
188 alExt := alGetString(AL_EXTENSIONS);
190 e_LogWriteln('AL INFO:');
191 e_LogWriteln(' Version: ' + alVer);
192 e_LogWriteln(' Vendor: ' + alVendor);
193 e_LogWriteln(' Renderer: ' + alRend);
194 e_LogWriteln(' Device: ' + WantDev);
195 e_LogWriteln(' Sample rate: ' + IntToStr(e_SoundFormat.SampleRate));
196 e_LogWriteln(' Extensions:');
197 e_LogWriteln(' ' + alExt);
199 ZeroMemory(@alSources[0], sizeof(alSources));
200 ZeroMemory(@alOwners[0], sizeof(alOwners));
201 ZeroMemory(@alStreamBufs[0], sizeof(alStreamBufs));
202 ZeroMemory(@alStreamData[0], sizeof(alStreamData));
203 CurStream := NO_SOUND_ID;
205 alGetError(); // reset the goddamn error state
206 alGenSources(1, @alSources[0]); // generate the music source
207 if CheckALError() then
208 e_LogWriteln('AL: ERROR: alGenSources() for music failed: ' + GetALError());
211 alGenBuffers(NUM_STREAM_BUFFERS, @alStreamBufs[0]); // generate buffers for the music stream
212 if CheckALError() then
213 e_LogWriteln('AL: ERROR: alGenSources() for music failed: ' + GetALError())
215 alStreamAvail := NUM_STREAM_BUFFERS;
220 function FindESound(): DWORD;
225 if e_SoundsArray <> nil then
226 for i := 0 to High(e_SoundsArray) do
227 if (e_SoundsArray[i].alBuffer = 0) and (e_SoundsArray[i].Loader = nil) then
233 if e_SoundsArray = nil then
235 SetLength(e_SoundsArray, 16);
240 Result := High(e_SoundsArray) + 1;
241 SetLength(e_SoundsArray, Length(e_SoundsArray) + 16);
245 function GetALSoundFormat(Fmt: TSoundFormat): ALenum; inline;
247 if Fmt.Channels = 2 then
249 if Fmt.SampleBits = 16 then
250 Result := AL_FORMAT_STEREO16
252 Result := AL_FORMAT_STEREO8;
256 if Fmt.SampleBits = 16 then
257 Result := AL_FORMAT_MONO16
259 Result := AL_FORMAT_MONO8;
263 function GetALSourceState(S: ALuint): ALint; inline;
265 alGetSourcei(S, AL_SOURCE_STATE, Result);
268 function LoadEntireSound(var Snd: TSoundRec; Loader: TSoundLoader): Boolean;
273 DataLen, OldLen: LongWord;
275 CHUNK_SIZE = 65536 * 2 * 2;
279 Frame := GetMem(CHUNK_SIZE);
280 if Frame = nil then exit;
286 Rx := Loader.FillBuffer(Frame, CHUNK_SIZE);
287 if Rx = 0 then break;
290 DataLen := DataLen + Rx;
291 Data := ReAllocMem(Data, DataLen);
292 if Data = nil then begin FreeMem(Frame); exit; end;
294 Move(Frame^, (Data + OldLen)^, Rx);
295 until Loader.Finished();
299 alGenBuffers(1, Addr(Snd.alBuffer));
300 if CheckALError() then
302 e_LogWritefln('AL: Could not create AL buffer: %s', [GetALError()]);
309 GetALSoundFormat(Loader.Format),
312 Loader.Format.SampleRate
317 if CheckALError() then
319 e_LogWriteln('AL: Could not fill AL buffer: ' + GetALError());
320 alDeleteBuffers(1, Addr(Snd.alBuffer));
328 function e_LoadSound(FileName: String; var ID: DWORD; isMusic: Boolean; ForceNoLoop: Boolean = False): Boolean;
331 Loader: TSoundLoader;
336 find_id := FindESound();
338 e_SoundsArray[find_id].Loader := nil;
339 e_SoundsArray[find_id].isMusic := isMusic;
340 e_SoundsArray[find_id].Loops := isMusic and not ForceNoLoop;
341 e_SoundsArray[find_id].nRefs := 0;
343 Loader := e_GetSoundLoader(FileName);
346 e_LogWritefln('Could not find loader for sound `%s`', [FileName]);
350 if not Loader.Load(FileName, e_SoundsArray[find_id].Loops) then
352 e_LogWritefln('Could not load sound `%s`', [FileName]);
356 alGetError(); // reset error state, god damn it
360 if not LoadEntireSound(e_SoundsArray[find_id], Loader) then
361 e_LogWritefln('AL: Could not buffer sound effect `%s`', [FileName]);
362 // don't need this anymore
368 e_SoundsArray[find_id].alBuffer := 0;
369 e_SoundsArray[find_id].Loader := Loader;
376 function e_LoadSoundMem(pData: Pointer; Length: Integer; var ID: DWORD; isMusic: Boolean; ForceNoLoop: Boolean = False): Boolean;
379 Loader: TSoundLoader;
384 find_id := FindESound();
386 e_SoundsArray[find_id].Loader := nil;
387 e_SoundsArray[find_id].isMusic := isMusic;
388 e_SoundsArray[find_id].Loops := isMusic and not ForceNoLoop;
389 e_SoundsArray[find_id].nRefs := 0;
391 Loader := e_GetSoundLoader(pData, LongWord(Length));
394 e_LogWritefln('Could not find loader for sound `%p`', [pData]);
398 if not Loader.Load(pData, LongWord(Length), e_SoundsArray[find_id].Loops) then
400 e_LogWritefln('Could not load sound `%p`', [pData]);
404 alGetError(); // reset error state, god damn it
408 if not LoadEntireSound(e_SoundsArray[find_id], Loader) then
409 e_LogWritefln('AL: Could not buffer sound effect `%p`', [pData]);
410 // don't need this anymore
416 e_SoundsArray[find_id].alBuffer := 0;
417 e_SoundsArray[find_id].Loader := Loader;
420 // the calling side won't free this, the loader will get a copy, so fuck it
426 function FindSourceForSound(ID: DWORD): Integer;
431 if ID > High(e_SoundsArray) then
434 if e_SoundsArray[ID].Loader <> nil then
436 // first source is for streaming sounds
438 alOwners[MUSIC_SOURCE] := nil;
439 Result := MUSIC_SOURCE;
443 for S := 1 to High(alSources) do
444 if alSources[S] = 0 then
446 alOwners[S] := nil; // TBasicSounds will set this if needed
451 if Result = -1 then Exit; // no voices left
453 alGetError(); // reset error state
454 alGenSources(1, @alSources[Result]);
455 if CheckALError() then
457 e_LogWriteln('AL: FindSourceForSound(): alGenSources() failed: ' + GetALError());
462 procedure AssignSound(ID: DWORD; Src: ALuint); inline;
466 alGetError(); // reset error state
468 if e_SoundsArray[ID].Loader <> nil then
472 e_SoundsArray[ID].Loader.Restart();
473 if CurStream <> ID then // changing streams
475 alSourceStop(Src); // this should mark all buffers as processed
476 alGetSourcei(Src, AL_BUFFERS_PROCESSED, S);
477 // unqueue all buffers
480 alSourceUnqueueBuffers(Src, S, @alStreamBufs[alStreamAvail]);
481 alStreamAvail := NUM_STREAM_BUFFERS;
484 // this shit is playing now
489 // this is a full chunk, assign local buffer
490 alSourcei(Src, AL_BUFFER, e_SoundsArray[ID].alBuffer);
492 if (e_SoundsArray[ID].Loops) then
493 alSourcei(Src, AL_LOOPING, AL_TRUE)
495 alSourcei(Src, AL_LOOPING, AL_FALSE);
498 alSourcei(Src, AL_SOURCE_RELATIVE, AL_TRUE);
501 function e_PlaySound(ID: DWORD): Integer;
503 Result := FindSourceForSound(ID);
506 AssignSound(ID, alSources[Result]);
507 alSourcef(alSources[Result], AL_GAIN, 1);
508 alSourcefv(alSources[Result], AL_POSITION, e_ZeroPosition);
509 alSourcePlay(alSources[Result]);
513 function e_PlaySoundPan(ID: DWORD; Pan: Single): Integer;
515 Pos: array [0..2] of ALfloat;
517 Result := FindSourceForSound(ID);
523 AssignSound(ID, alSources[Result]);
524 alSourcef(alSources[Result], AL_GAIN, 1);
525 alSourcefv(alSources[Result], AL_POSITION, Pos);
526 alSourcePlay(alSources[Result]);
530 function e_PlaySoundVolume(ID: DWORD; Volume: Single): Integer;
532 Result := FindSourceForSound(ID);
535 AssignSound(ID, alSources[Result]);
536 alSourcef(alSources[Result], AL_GAIN, Volume);
537 alSourcefv(alSources[Result], AL_POSITION, e_ZeroPosition);
538 alSourcePlay(alSources[Result]);
542 function e_PlaySoundPanVolume(ID: DWORD; Pan, Volume: Single): Integer;
544 Pos: array [0..2] of ALfloat;
546 Result := FindSourceForSound(ID);
552 AssignSound(ID, alSources[Result]);
553 alSourcefv(alSources[Result], AL_POSITION, Pos);
554 alSourcef(alSources[Result], AL_GAIN, Volume);
555 alSourcePlay(alSources[Result]);
559 procedure e_DeleteSound(ID: DWORD);
561 if ID > High(e_SoundsArray) then
563 if (e_SoundsArray[ID].alBuffer <> 0) then
565 alDeleteBuffers(1, Addr(e_SoundsArray[ID].alBuffer));
566 e_SoundsArray[ID].alBuffer := 0;
568 if (e_SoundsArray[ID].Loader <> nil) then
570 e_SoundsArray[ID].Loader.Free();
571 e_SoundsArray[ID].Loader := nil;
572 if ID = CurStream then
573 CurStream := NO_SOUND_ID;
577 procedure e_ModifyChannelsVolumes(SoundMod: Single; setMode: Boolean);
582 // TODO: replace manual volume calculations everywhere with
583 // alListenerf(AL_GAIN) or something
586 for S := 1 to High(alSources) do
587 if alSources[S] <> 0 then
588 alSourcef(alSources[S], AL_GAIN, SoundMod)
592 for S := 1 to High(alSources) do
593 if alSources[S] <> 0 then
595 alGetSourcef(alSources[S], AL_GAIN, V);
596 alSourcef(alSources[S], AL_GAIN, V * SoundMod);
601 procedure e_MuteChannels(Enable: Boolean);
603 if Enable = SoundMuted then
606 SoundMuted := Enable;
609 procedure e_StopChannels();
613 alGetError(); // reset error state
614 for S := Low(alSources) to High(alSources) do
615 if (alSources[S] <> 0) and (GetALSourceState(alSources[S]) = AL_PLAYING) then
617 alSourceStop(alSources[S]);
618 alDeleteSources(1, @alSources[S]);
623 procedure e_RemoveAllSounds();
627 for i := 0 to High(e_SoundsArray) do
628 if e_SoundsArray[i].alBuffer <> 0 then
630 SetLength(e_SoundsArray, 0);
631 e_SoundsArray := nil;
632 CurStream := NO_SOUND_ID;
635 procedure e_ReleaseSoundSystem();
639 alcMakeContextCurrent(nil);
640 alcDestroyContext(alContext);
641 alcCloseDevice(alDevice);
647 procedure UpdateStreamSource(Src: Integer);
653 if alSources[Src] = 0 then Exit;
655 alGetError(); // reset error state
657 alGetSourcei(alSources[Src], AL_BUFFERS_PROCESSED, S);
658 // unqueue processed buffers
661 alSourceUnqueueBuffers(alSources[Src], S, @alStreamBufs[alStreamAvail]);
662 alStreamAvail := alStreamAvail + S;
665 alGetError(); // reset error state
667 if (alStreamAvail > 0) and (CurStream <> NO_SOUND_ID) then
669 // some buffers have freed up, advance stream playback
670 OutLen := e_SoundsArray[CurStream].Loader.FillBuffer(@alStreamData[0], STREAM_BUFSIZE);
671 if OutLen = 0 then Exit; // ran out of stream
672 Buf := alStreamBufs[alStreamAvail-1];
677 GetALSoundFormat(e_SoundsArray[CurStream].Loader.Format),
680 e_SoundsArray[CurStream].Loader.Format.SampleRate
683 alSourceQueueBuffers(alSources[Src], 1, @Buf);
685 S := GetALSourceState(alSources[Src]);
686 if (S = AL_STOPPED) or (S = AL_INITIAL) then
687 alSourcePlay(alSources[Src]);
691 procedure e_SoundUpdate();
695 alGetError(); // reset error state
697 // clear out all stopped sources
698 for S := 1 to High(alSources) do
699 if (alSources[S] <> 0) and (GetALSourceState(alSources[S]) = AL_STOPPED) then
701 alDeleteSources(1, @alSources[S]);
706 // update the stream sources
707 UpdateStreamSource(MUSIC_SOURCE);
712 constructor TBasicSound.Create();
722 destructor TBasicSound.Destroy();
728 function TBasicSound.InvalidSource(): Boolean; inline;
730 Result := (FSource < 0) or (alSources[FSource] = 0) or (alOwners[FSource] <> self);
733 procedure TBasicSound.FreeSound();
735 if FID = NO_SOUND_ID then
744 function TBasicSound.RawPlay(Pan: Single; Volume: Single; aPos: DWORD): Boolean;
747 if FID = NO_SOUND_ID then Exit;
749 if e_SoundsArray[FID].nRefs >= gMaxSimSounds then
755 FSource := e_PlaySoundPanVolume(FID, Pan, Volume);
758 alOwners[FSource] := self;
763 procedure TBasicSound.SetID(ID: DWORD);
767 if ID > High(e_SoundsArray) then
771 FMusic := e_SoundsArray[ID].isMusic;
774 function TBasicSound.IsPlaying(): Boolean;
777 if InvalidSource() then
779 Result := GetALSourceState(alSources[FSource]) = AL_PLAYING;
782 procedure TBasicSound.Stop();
784 if FID = CurStream then
785 CurStream := NO_SOUND_ID;
786 if InvalidSource() then
789 alSourceStop(alSources[FSource]);
792 function TBasicSound.IsPaused(): Boolean;
795 if InvalidSource() then
797 Result := GetALSourceState(alSources[FSource]) = AL_PAUSED;
800 procedure TBasicSound.Pause(Enable: Boolean);
802 if InvalidSource() then
805 alSourcePause(alSources[FSource])
807 alSourcePlay(alSources[FSource]);
810 function TBasicSound.GetVolume(): Single;
813 if InvalidSource() then
815 alGetSourcef(alSources[FSource], AL_GAIN, Result);
818 procedure TBasicSound.SetVolume(Volume: Single);
820 if InvalidSource() then
822 alSourcef(alSources[FSource], AL_GAIN, Volume);
825 function TBasicSound.GetPan(): Single;
827 Pos: array [0..2] of ALfloat = (0, 0, 0);
830 if InvalidSource() then
832 alGetSourcefv(alSources[FSource], AL_POSITION, Pos);
836 procedure TBasicSound.SetPan(Pan: Single);
838 Pos: array [0..2] of ALfloat;
840 if InvalidSource() then
845 alSourcefv(alSources[FSource], AL_POSITION, Pos);
848 function TBasicSound.IsMuted(): Boolean;
850 if InvalidSource() then
856 procedure TBasicSound.Mute(Enable: Boolean);
858 if InvalidSource() then
862 FOldGain := GetVolume();
873 function TBasicSound.GetPosition(): DWORD;
878 if InvalidSource() then
880 alGetSourcei(alSources[FSource], AL_BYTE_OFFSET, Bytes);
885 procedure TBasicSound.SetPosition(aPos: DWORD);
888 if InvalidSource() then
890 alSourcei(alSources[FSource], AL_BYTE_OFFSET, aPos);
893 procedure TBasicSound.SetPriority(priority: Integer);