]> icculus.org git repositories - taylor/freespace2.git/blob - src/sound/audiostr.cpp
bypass Emscripten bug when AL source is relative
[taylor/freespace2.git] / src / sound / audiostr.cpp
1 /*
2  * $Logfile: $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * OpenAL based audio streaming
8  *
9  * $Log$
10  * Revision 1.4  2005/10/01 21:53:06  taylor
11  * include file cleanup
12  * byte-swap streaming PCM to avoid the endless, loud, static
13  *
14  * Revision 1.3  2005/08/13 16:59:23  taylor
15  * type check
16  *
17  * Revision 1.2  2005/08/12 20:21:06  taylor
18  * woorps!
19  *
20  * Revision 1.1  2005/08/12 08:44:39  taylor
21  * import of FS2_Open audio code which is now *nix only, does not include windows or ogg support that FS2_Open has
22  *
23  * Revision 1.12  2005/06/24 19:36:49  taylor
24  * we only want to have m_data_offset be 0 for oggs since the seeking callback will account for the true offset
25  * only extern the one int we need for the -nosound speech fix rather than including the entire header
26  *
27  * Revision 1.11  2005/06/19 02:45:55  taylor
28  * OGG streaming fixes to get data reading right and avoid skipping
29  * properly handle seeking in OGG streams
30  * compiler warning fix in OpenAL builds
31  *
32  * Revision 1.10  2005/06/01 09:41:14  taylor
33  * bit of cleanup for audiostr-openal and fix a Windows-only enum error
34  * bunch of OGG related fixes for Linux and Windows (DirectSound and OpenAL), fixes audio related TBP 3.2 crashes
35  * gracefully handle OGG logical bitstream changes, shouldn't even load if there is more than 1
36  *
37  * Revision 1.9  2005/05/28 19:43:28  taylor
38  * debug message fixing
39  * a little bit of code clarity
40  *
41  * Revision 1.8  2005/05/24 03:11:38  taylor
42  * an extra bounds check in sound.cpp
43  * fix audiostr error when filename is !NULL but 0 in len might hit on SDL debug code
44  *
45  * Revision 1.7  2005/05/15 06:47:57  taylor
46  * don't let the ogg callbacks close the file handle on us, let us do it ourselves to keep things straight
47  *
48  * Revision 1.6  2005/05/13 23:09:28  taylor
49  * Ooops!  Added the wrong version of the streaming patch from Jens
50  *
51  * Revision 1.5  2005/05/12 17:47:57  taylor
52  * use vm_malloc(), vm_free(), vm_realloc(), vm_strdup() rather than system named macros
53  *   fixes various problems and is past time to make the switch
54  * fix a few streaming errors in OpenAL code (Jens Granseuer)
55  * temporary change to help deal with missing music in OpenAL Windows builds
56  * don't assert when si->data is NULL unless we really need to check (OpenAL only)
57  *
58  * Revision 1.4  2005/04/05 11:48:22  taylor
59  * remove acm-unix.cpp, replaced by acm-openal.cpp since it's properly cross-platform now
60  * better error handling for OpenAL functions
61  * Windows can now build properly with OpenAL
62  * extra check to make sure we don't try and use too many hardware bases sources
63  * fix memory error from OpenAL extension list in certain instances
64  *
65  * Revision 1.3  2005/04/01 07:33:08  taylor
66  * fix hanging on exit with OpenAL
67  * some better error handling on OpenAL init and make it more Windows friendly too
68  * basic 3d sound stuff for OpenAL, not working right yet
69  *
70  * Revision 1.2  2005/03/27 08:51:24  taylor
71  * this is what coding on an empty stomach will get you
72  *
73  * Revision 1.1  2005/03/27 05:48:58  taylor
74  * initial import of OpenAL streaming (many thanks to Pierre Willenbrock for the missing parts)
75  *
76  *
77  * $NoKeywords: $
78  */
79
80
81 #include <vector>
82
83 #include "pstypes.h"
84 #include "audiostr.h"
85 #include "oal.h"
86 #include "acm.h"
87 #include "cfile.h"
88 #include "sound.h"
89 #include "timer.h"
90
91
92 #define MAX_STREAM_BUFFERS 4
93
94 // Constants
95 #define BIGBUF_SIZE                                     180000                  // This can be reduced to 88200 once we don't use any stereo
96 //#define BIGBUF_SIZE                                   88300                   // This can be reduced to 88200 once we don't use any stereo
97 static ubyte *Wavedata_load_buffer = NULL;              // buffer used for cueing audiostreams
98 static ubyte *Wavedata_service_buffer = NULL;   // buffer used for servicing audiostreams
99
100 SDL_mutex *Global_service_lock;
101
102 typedef bool (*TIMERCALLBACK)(ptr_u);
103
104 #define COMPRESSED_BUFFER_SIZE  88300
105 static ubyte *Compressed_buffer = NULL;                         // Used to load in compressed data during a cueing interval
106 static ubyte *Compressed_service_buffer = NULL; // Used to read in compressed data during a service interval
107
108 #define AS_HIGHEST_MAX  999999999       // max uncompressed filesize supported is 999 meg
109
110 // status
111 #define ASF_FREE        0
112 #define ASF_USED        1
113
114 static int Audiostream_inited = 0;
115
116
117 class Timer
118 {
119 public:
120     void constructor();
121     void destructor();
122
123     bool Create(uint nPeriod, ptr_u dwUser, TIMERCALLBACK pfnCallback);
124
125 protected:
126         static Uint32 TimeProc(Uint32 interval, void *dwUser);
127
128         TIMERCALLBACK m_pfnCallback;
129     ptr_u m_dwUser;
130     uint m_nPeriod;
131     SDL_TimerID m_nIDTimer;
132 };
133
134 class WaveFile
135 {
136 public:
137         void Init();
138         void Close();
139         bool Open(const char *pszFilename);
140         bool Cue();
141         int     Read(ubyte *pbDest, uint cbSize, int service = 1);
142         ubyte GetSilenceData();
143
144         uint GetNumBytesRemaining()
145         {
146                 return (m_nDataSize - m_nBytesPlayed);
147         }
148
149         uint GetUncompressedAvgDataRate()
150         {
151                 return m_nUncompressedAvgDataRate;
152         }
153
154         uint GetDataSize()
155         {
156                 return m_nDataSize;
157         }
158
159         uint GetNumBytesPlayed()
160         {
161                 return m_nBytesPlayed;
162         }
163
164         ALenum GetOALFormat()
165         {
166                 return m_oal_format;
167         }
168
169         WAVE_chunk m_wfmt;                                      // format of wave file
170         WAVE_chunk *m_pwfmt_original;   // foramt of wave file from actual wave source
171         uint m_total_uncompressed_bytes_read;
172         uint m_max_uncompressed_bytes_to_read;
173         uint m_bits_per_sample_uncompressed;
174
175 protected:
176         uint m_data_offset;                                             // number of bytes to actual wave data
177         int  m_data_bytes_left;
178         CFILE *cfp;
179
180         ALenum m_oal_format;
181         uint m_wave_format;                                             // format of wave source (ie WAVE_FORMAT_PCM, WAVE_FORMAT_ADPCM)
182         uint m_nBlockAlign;                                             // wave data block alignment spec
183         uint m_nUncompressedAvgDataRate;                // average wave data rate
184         uint m_nDataSize;                                                       // size of data chunk
185         uint m_nBytesPlayed;                                            // offset into data chunk
186         bool m_abort_next_read;
187
188         void *m_hStream;
189         int m_hStream_open;
190         WAVE_chunk m_wfxDest;
191 };
192
193 class AudioStream
194 {
195 public:
196         AudioStream();
197         ~AudioStream();
198
199         bool Create(const char *pszFilename);
200         bool Destroy();
201         void Play(float volume, int looping);
202         void Stop(bool paused = false);
203         void Stop_and_Rewind();
204         void Fade_and_Destroy();
205         void Fade_and_Stop();
206         void Set_Volume(float vol);
207         float Get_Volume();
208         void Init_Data();
209         void Set_Byte_Cutoff(uint num_bytes_cutoff);
210         uint Get_Bytes_Committed();
211
212         bool Is_Playing()
213         {
214                 return m_fPlaying;
215         }
216
217         bool Is_Paused()
218         {
219                 return m_bIsPaused;
220         }
221
222         bool Is_Past_Limit()
223         {
224                 return m_bPastLimit;
225         }
226
227         void Set_Default_Volume(float _volume)
228         {
229                 m_lDefaultVolume = _volume;
230         }
231
232         float Get_Default_Volume()
233         {
234                 return m_lDefaultVolume;
235         }
236
237         bool Is_looping()
238         {
239                 return m_bLooping;
240         }
241
242         int status;
243         int     type;
244         ushort m_bits_per_sample_uncompressed;
245
246 protected:
247         void Cue();
248         bool WriteWaveData(uint cbSize, uint* num_bytes_written,int service=1);
249         uint GetMaxWriteSize();
250         bool ServiceBuffer();
251         static bool TimerCallback(ptr_u dwUser);
252
253         ALuint m_source_id;   // name of openAL source
254         ALuint m_buffer_ids[MAX_STREAM_BUFFERS]; //names of buffers
255         int m_play_buffer_id;
256
257         Timer m_timer;              // ptr to Timer object
258         WaveFile *m_pwavefile;        // ptr to WaveFile object
259         bool m_fCued;                  // semaphore (stream cued)
260         bool m_fPlaying;               // semaphore (stream playing)
261         long m_lInService;             // reentrancy semaphore
262         uint m_cbBufOffset;            // last write position
263         uint m_nBufLength;             // length of sound buffer in msec
264         uint m_cbBufSize;              // size of sound buffer in bytes
265         uint m_nBufService;            // service interval in msec
266         uint m_nTimeStarted;           // time (in system time) playback started
267
268         bool    m_bLooping;                                             // whether or not to loop playback
269         bool    m_bFade;                                                        // fade out music
270         bool    m_bDestroy_when_faded;
271         float   m_lVolume;                                              // volume of stream ( 0 -> -10 000 )
272         float   m_lCutoffVolume;
273         bool    m_bIsPaused;                                    // stream is stopped, but not rewinded
274         ushort  m_silence_written;                      // number of bytes of silence written to buffer
275         ushort  m_bReadingDone;                         // no more bytes to be read from disk, still have remaining buffer to play
276         uint    m_fade_timer_id;                                // timestamp so we know when to start fade
277         uint    m_finished_id;                                  // timestamp so we know when we've played #bytes required
278         bool    m_bPastLimit;                                   // flag to show we've played past the number of bytes requred
279         float   m_lDefaultVolume;
280 };
281
282
283 // Timer class implementation
284 //
285 ////////////////////////////////////////////////////////////
286
287 void Timer::constructor()
288 {
289         m_nIDTimer = 0;
290 }
291
292 void Timer::destructor()
293 {
294         if (m_nIDTimer) {
295                 SDL_RemoveTimer(m_nIDTimer);
296                 m_nIDTimer = 0;
297         }
298 }
299
300 bool Timer::Create(uint nPeriod, ptr_u dwUser, TIMERCALLBACK pfnCallback)
301 {
302         SDL_assert( pfnCallback != NULL );
303         SDL_assert( nPeriod > 10 );
304
305         m_nPeriod = nPeriod;
306         m_dwUser = dwUser;
307         m_pfnCallback = pfnCallback;
308
309         m_nIDTimer = SDL_AddTimer(m_nPeriod, TimeProc, (void*)this);
310
311         if ( !m_nIDTimer ) {
312                 nprintf(("SOUND", "SOUND ==> Error, unable to create timer\n"));
313                 return false;
314         }
315
316         return true;
317 }
318
319 // Calls procedure specified when Timer object was created. The 
320 // dwUser parameter contains "this" pointer for associated Timer object.
321 // 
322 Uint32 Timer::TimeProc(Uint32 interval, void *dwUser)
323 {
324     // dwUser contains ptr to Timer object
325         Timer *ptimer = (Timer *)dwUser;
326
327     // Call user-specified callback and pass back user specified data
328     (ptimer->m_pfnCallback)(ptimer->m_dwUser);
329
330     if (ptimer->m_nPeriod) {
331                 return interval;
332     } else {
333                 SDL_RemoveTimer(ptimer->m_nIDTimer);
334                 ptimer->m_nIDTimer = 0;
335
336                 return 0;
337     }
338 }
339
340
341 // WaveFile class implementation
342 //
343 ////////////////////////////////////////////////////////////
344
345 void WaveFile::Init()
346 {
347         // Init data members
348         m_data_offset = 0;
349         cfp = NULL;
350         m_pwfmt_original = NULL;
351         m_nBlockAlign= 0;
352         m_nUncompressedAvgDataRate = 0;
353         m_nDataSize = 0;
354         m_nBytesPlayed = 0;
355         m_total_uncompressed_bytes_read = 0;
356         m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
357         SDL_zero(m_wfmt);
358         SDL_zero(m_wfxDest);
359
360         m_hStream_open = 0;
361         m_abort_next_read = false;
362 }
363
364 void WaveFile::Close()
365 {
366         // Free memory
367         if (m_pwfmt_original) {
368                 if (m_pwfmt_original->extra_data) {
369                         free(m_pwfmt_original->extra_data);
370                 }
371
372                 free(m_pwfmt_original);
373                 m_pwfmt_original = NULL;
374         }
375
376         if (m_hStream_open) {
377                 ACM_stream_close((void*)m_hStream);
378                 m_hStream_open = 0;
379         }
380
381         // Close file
382         if (cfp) {
383                 cfclose(cfp);
384                 cfp = NULL;
385         }
386 }
387
388 bool WaveFile::Open(const char *pszFilename)
389 {
390         int done = false;
391         bool fRtn = true;    // assume success
392         int id = 0;
393         uint tag = 0, size = 0, next_chunk;
394
395         m_total_uncompressed_bytes_read = 0;
396         m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
397
398         m_pwfmt_original = (WAVE_chunk*) malloc (sizeof(WAVE_chunk));
399
400         if (m_pwfmt_original == NULL) {
401                 goto OPEN_ERROR;
402         }
403
404         SDL_zerop(m_pwfmt_original);
405
406         cfp = cfopen(pszFilename, "rb");
407
408         if (cfp == NULL) {
409                 goto OPEN_ERROR;
410         }
411
412         // check for valid file type
413         id = cfread_int(cfp);
414
415         // 'RIFF'
416         if (id != 0x46464952) {
417                 nprintf(("Error", "Not a WAVE file '%s'\n", pszFilename));
418                 goto OPEN_ERROR;
419         }
420
421         // skip RIFF size
422         cfread_int(cfp);
423
424         // check for valid RIFF type
425         id = cfread_int(cfp);
426
427         // 'WAVE'
428         if (id != 0x45564157) {
429                 nprintf(("Error", "Not a WAVE file '%s'\n", pszFilename));
430                 goto OPEN_ERROR;
431         }
432
433         while ( !done ) {
434                 tag = cfread_uint(cfp);
435                 size = cfread_uint(cfp);
436
437                 next_chunk = cftell(cfp) + size;
438
439                 switch (tag) {
440                         // 'fmt '
441                         case 0x20746d66: {
442                                 m_pwfmt_original->code = cfread_short(cfp);
443                                 m_pwfmt_original->num_channels = cfread_ushort(cfp);
444                                 m_pwfmt_original->sample_rate = cfread_uint(cfp);
445                                 m_pwfmt_original->bytes_per_second = cfread_uint(cfp);
446                                 m_pwfmt_original->block_align = cfread_ushort(cfp);
447                                 m_pwfmt_original->bits_per_sample = cfread_ushort(cfp);
448
449                                 if (m_pwfmt_original->code != 1) {
450                                         m_pwfmt_original->extra_size = cfread_ushort(cfp);
451                                 }
452
453                                 if (m_pwfmt_original->extra_size) {
454                                         m_pwfmt_original->extra_data = (ubyte*) malloc (m_pwfmt_original->extra_size);
455                                         SDL_assert( m_pwfmt_original->extra_data != NULL );
456
457                                         if (m_pwfmt_original->extra_data == NULL) {
458                                                 goto OPEN_ERROR;
459                                         }
460
461                                         cfread(m_pwfmt_original->extra_data, m_pwfmt_original->extra_size, 1, cfp);
462                                 }
463
464                                 break;
465                         }
466
467                         // 'data'
468                         case 0x61746164: {
469                                 m_nDataSize = size;     // size of data, compressed size if ADPCM
470                                 m_data_bytes_left = size;
471                                 m_data_offset = cftell(cfp);
472
473                                 done = true;
474
475                                 break;
476                         }
477
478                         // drop everything else
479                         default:
480                                 break;
481                 }
482
483                 cfseek(cfp, next_chunk, CF_SEEK_SET);
484         }
485
486         // we force PCM format, so keep track of original format for later
487         switch (m_pwfmt_original->code) {
488                 case WAVE_FORMAT_PCM:
489                         m_wave_format = WAVE_FORMAT_PCM;
490                         m_wfmt.bits_per_sample = m_pwfmt_original->bits_per_sample;
491                         break;
492
493                 case WAVE_FORMAT_ADPCM:
494                         m_wave_format = WAVE_FORMAT_ADPCM;
495                         m_wfmt.bits_per_sample = 16;
496                         m_bits_per_sample_uncompressed = 16;
497                         break;
498
499                 default:
500                         nprintf(("SOUND", "SOUND => Not supporting %d format for playing wave files\n", m_pwfmt_original->code));
501                         //Int3();
502                         goto OPEN_ERROR;
503                         break;
504
505         }
506             
507         m_wfmt.code = WAVE_FORMAT_PCM;
508         m_wfmt.num_channels = m_pwfmt_original->num_channels;
509         m_wfmt.sample_rate = m_pwfmt_original->sample_rate;
510         m_wfmt.extra_size = 0;
511         m_wfmt.block_align = (ushort)(( m_wfmt.num_channels * m_wfmt.bits_per_sample ) / 8);
512         m_wfmt.bytes_per_second = m_wfmt.block_align * m_wfmt.sample_rate;
513
514         // set OpenAL format
515         m_oal_format = AL_FORMAT_MONO8;
516
517         if (m_wfmt.num_channels == 1) {
518                 if (m_wfmt.bits_per_sample == 8) {
519                         m_oal_format = AL_FORMAT_MONO8;
520                 } else if (m_wfmt.bits_per_sample == 16) {
521                         m_oal_format = AL_FORMAT_MONO16;
522                 }
523         } else if (m_wfmt.num_channels == 2) {
524                 if (m_wfmt.bits_per_sample == 8) {
525                         m_oal_format = AL_FORMAT_STEREO8;
526                 } else if (m_wfmt.bits_per_sample == 16) {
527                         m_oal_format = AL_FORMAT_STEREO16;
528                 }
529         }
530
531         // Init some member data from format chunk
532         m_nBlockAlign = m_pwfmt_original->block_align;
533         m_nUncompressedAvgDataRate = m_wfmt.bytes_per_second;
534
535         // Successful open
536         goto OPEN_DONE;
537
538 OPEN_ERROR:
539         // Handle all errors here
540         nprintf(("SOUND","SOUND ==> Could not open wave file %s for streaming\n", pszFilename));
541
542         fRtn = false;
543
544         if (m_pwfmt_original) {
545                 if (m_pwfmt_original->extra_data) {
546                         free(m_pwfmt_original->extra_data);
547                 }
548
549                 free(m_pwfmt_original);
550                 m_pwfmt_original = NULL;
551         }
552
553         if (cfp != NULL) {
554                 cfclose(cfp);
555                 cfp = NULL;
556         }
557
558 OPEN_DONE:
559         return (fRtn);
560 }
561
562 // Cue
563 //
564 // Set the file pointer to the start of wave data
565 //
566 bool WaveFile::Cue()
567 {
568         bool fRtn = true;    // assume success
569         int rval = -1;
570
571         m_total_uncompressed_bytes_read = 0;
572         m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
573
574         rval = cfseek(cfp, m_data_offset, CF_SEEK_SET);
575
576         if (rval) {
577                 fRtn = false;
578         }
579
580         m_data_bytes_left = m_nDataSize;
581         m_abort_next_read = false;
582
583         return fRtn;
584 }
585
586 // Read
587 //
588 // Returns number of bytes actually read.
589 // 
590 //      Returns -1 if there is nothing more to be read.  This function can return 0, since
591 // sometimes the amount of bytes requested is too small for the ACM decompression to 
592 // locate a suitable block
593 int WaveFile::Read(ubyte *pbDest, uint cbSize, int service)
594 {
595         void *dest_buf = NULL, *uncompressed_wave_data;
596         int rc, uncompressed_bytes_written;
597         uint src_bytes_used, convert_len, num_bytes_desired=0, num_bytes_read;
598
599 //      nprintf(("Alan","Reqeusted: %d\n", cbSize));
600
601         if ( service ) {
602                 uncompressed_wave_data = Wavedata_service_buffer;
603         } else {
604                 uncompressed_wave_data = Wavedata_load_buffer;
605         }
606
607         switch (m_wave_format) {
608                 case WAVE_FORMAT_PCM: {
609                         num_bytes_desired = cbSize;
610                         dest_buf = pbDest;
611
612                         break;
613                 }
614
615                 case WAVE_FORMAT_ADPCM: {
616                         if ( !m_hStream_open ) {
617                                 if ( !ACM_stream_open(m_pwfmt_original, &m_wfxDest, (void**)&m_hStream, m_bits_per_sample_uncompressed) ) {
618                                         m_hStream_open = 1;
619                                 } else {
620                                         Int3();
621                                 }
622                         }
623
624                         num_bytes_desired = cbSize;
625         
626                         if (service) {
627                                 dest_buf = Compressed_service_buffer;
628                         } else {
629                                 dest_buf = Compressed_buffer;
630                         }
631
632                         if (num_bytes_desired <= 0) {
633                                 num_bytes_desired = 0;
634 //                              nprintf(("Alan","No bytes required for ADPCM time interval\n"));
635                         } else {
636                                 num_bytes_desired = ACM_query_source_size((void*)m_hStream, cbSize);
637 //                              nprintf(("Alan","Num bytes desired: %d\n", num_bytes_desired));
638                         }
639
640                         break;
641                 }
642
643                 default:
644                         nprintf(("SOUND", "SOUND => Not supporting %d format for playing wave files\n"));
645                         Int3();
646                         break;
647
648         } // end switch
649
650         num_bytes_read = 0;
651         convert_len = 0;
652         src_bytes_used = 0;
653
654         // read data from disk
655         if (m_data_bytes_left <= 0) {
656                 return -1;
657         }
658
659         if ( (m_data_bytes_left > 0) && (num_bytes_desired > 0) ) {
660                 int actual_read = 0;
661
662                 if (num_bytes_desired <= (uint)m_data_bytes_left) {
663                         num_bytes_read = num_bytes_desired;
664                 } else {
665                         num_bytes_read = m_data_bytes_left;
666                 }
667
668                 actual_read = cfread(dest_buf, 1, num_bytes_read, cfp);
669
670                 if ( (actual_read <= 0) || (m_abort_next_read) ) {
671                         return -1;
672                 }
673
674                 if (num_bytes_desired >= (uint)m_data_bytes_left) {
675                         m_abort_next_read = 1;                  
676                 }
677
678                 num_bytes_read = actual_read;
679         }
680
681         // convert data if necessary, to PCM
682         if (m_wave_format == WAVE_FORMAT_ADPCM) {
683                 if ( num_bytes_read > 0 ) {
684                         rc = ACM_convert((void*)m_hStream, (ubyte*)dest_buf, num_bytes_read, (ubyte*)uncompressed_wave_data, BIGBUF_SIZE, &convert_len, &src_bytes_used);
685
686                         if (rc == -1) {
687                                 goto READ_ERROR;
688                         }
689
690                         if (convert_len == 0) {
691                                 Int3();
692                         }
693                 }
694
695                 SDL_assert( src_bytes_used <= num_bytes_read );
696
697                 if (src_bytes_used < num_bytes_read) {
698                         // seek back file pointer to reposition before unused source data
699                         cfseek(cfp, src_bytes_used - num_bytes_read, CF_SEEK_CUR);
700                 }
701
702                 // Adjust number of bytes left
703                 m_data_bytes_left -= src_bytes_used;
704                 m_nBytesPlayed += src_bytes_used;
705                 uncompressed_bytes_written = convert_len;
706
707                 // Successful read, keep running total of number of data bytes read
708                 goto READ_DONE;
709         } else {
710                 // Successful read, keep running total of number of data bytes read
711                 // Adjust number of bytes left
712                 m_data_bytes_left -= num_bytes_read;
713                 m_nBytesPlayed += num_bytes_read;
714                 uncompressed_bytes_written = num_bytes_read;
715
716 #if BYTE_ORDER == BIG_ENDIAN
717                 if (m_wave_format == WAVE_FORMAT_PCM) {
718                         // swap 16-bit sound data
719                         if (m_wfmt.bits_per_sample == 16) {
720                                 ushort *swap_tmp;
721                                 
722                                 for (int i = 0; i < uncompressed_bytes_written; i = (i+2)) {
723                                         swap_tmp = (ushort*)((ubyte*)dest_buf + i);
724                                         *swap_tmp = INTEL_SHORT(*swap_tmp);
725                                 }
726                         }
727                 }
728 #endif
729
730                 goto READ_DONE;
731         }
732     
733 READ_ERROR:
734         uncompressed_bytes_written = 0;
735
736 READ_DONE:
737         m_total_uncompressed_bytes_read += uncompressed_bytes_written;
738 //      nprintf(("Alan","Read: %d\n", uncompressed_bytes_written));
739
740         return uncompressed_bytes_written;
741 }
742
743 // GetSilenceData
744 //
745 // Returns 8 bits of data representing silence for the Wave file format.
746 //
747 // Since we are dealing only with PCM format, we can fudge a bit and take
748 // advantage of the fact that for all PCM formats, silence can be represented
749 // by a single byte, repeated to make up the proper word size. The actual size
750 // of a word of wave data depends on the format:
751 //
752 // PCM Format       Word Size       Silence Data
753 // 8-bit mono       1 byte          0x80
754 // 8-bit stereo     2 bytes         0x8080
755 // 16-bit mono      2 bytes         0x0000
756 // 16-bit stereo    4 bytes         0x00000000
757 //
758 ubyte WaveFile::GetSilenceData()
759 {
760         ubyte bSilenceData = 0;
761
762         // Silence data depends on format of Wave file
763         if (m_pwfmt_original) {
764                 if (m_wfmt.bits_per_sample == 8) {
765                         // For 8-bit formats (unsigned, 0 to 255)
766                         // Packed DWORD = 0x80808080;
767                         bSilenceData = 0x80;
768                 } else if (m_wfmt.bits_per_sample == 16) {
769                         // For 16-bit formats (signed, -32768 to 32767)
770                         // Packed DWORD = 0x00000000;
771                         bSilenceData = 0x00;
772                 } else {
773                         Int3();
774                 }
775         } else {
776                 Int3();
777         }
778
779         return bSilenceData;
780 }
781
782 //
783 // AudioStream class implementation
784 //
785 ////////////////////////////////////////////////////////////
786
787 // The following constants are the defaults for our streaming buffer operation.
788 static const ushort DefBufferLength          = 2000; // default buffer length in msec
789 static const ushort DefBufferServiceInterval = 250;  // default buffer service interval in msec
790
791 // Constructor
792 AudioStream::AudioStream()
793 {
794 }
795
796 // Destructor
797 AudioStream::~AudioStream()
798 {
799 }
800
801 void AudioStream::Init_Data()
802 {
803         m_bLooping = false;
804         m_bFade = false;
805         m_fade_timer_id = 0;
806         m_finished_id = 0;
807         m_bPastLimit = false;
808
809         m_bDestroy_when_faded = false;
810         m_lDefaultVolume = 1.0f;
811         m_lVolume = 1.0f;
812         m_lCutoffVolume = 0.0f;
813         m_bIsPaused = false;
814         m_silence_written = 0;
815         m_bReadingDone = false;
816
817         m_pwavefile = NULL;
818
819         m_fPlaying = m_fCued = false;
820         m_lInService = false;
821         m_cbBufOffset = 0;
822         m_nBufLength = DefBufferLength;
823         m_cbBufSize = 0;
824         m_nBufService = DefBufferServiceInterval;
825         m_nTimeStarted = 0;
826
827         memset(m_buffer_ids, 0, sizeof(m_buffer_ids));
828         m_source_id = 0;
829         m_play_buffer_id = 0;
830 }
831
832 // Create
833 bool AudioStream::Create(const char *pszFilename)
834 {
835         SDL_assert( pszFilename != NULL );
836
837         Init_Data();
838
839         if (pszFilename == NULL) {
840                 return false;
841         }
842
843         // make 100% sure we got a good filename
844         if ( !strlen(pszFilename) ) {
845                 return false;
846         }
847
848         // Create a new WaveFile object
849         m_pwavefile = (WaveFile *)malloc(sizeof(WaveFile));
850         SDL_assert( m_pwavefile != NULL );
851
852         if (m_pwavefile == NULL) {
853                 nprintf(("Sound", "SOUND => Failed to create WaveFile object %s\n\r", pszFilename));
854                 return false;
855         }
856
857         // Call constructor
858         m_pwavefile->Init();
859
860         m_pwavefile->m_bits_per_sample_uncompressed = m_bits_per_sample_uncompressed;
861
862         // Open given file
863         if ( m_pwavefile->Open(pszFilename) ) {
864                 // Calculate sound buffer size in bytes
865                 // Buffer size is average data rate times length of buffer
866                 // No need for buffer to be larger than wave data though
867                 m_cbBufSize = (m_nBufLength/1000) * (m_pwavefile->m_wfmt.bits_per_sample/8) * m_pwavefile->m_wfmt.num_channels * m_pwavefile->m_wfmt.sample_rate;
868                 m_cbBufSize /= MAX_STREAM_BUFFERS;
869                 // align buffer to format
870                 m_cbBufSize += m_cbBufSize % ((m_pwavefile->m_wfmt.bits_per_sample/8) * m_pwavefile->m_wfmt.num_channels);
871                 // if the requested buffer size is too big then cap it
872                 m_cbBufSize = (m_cbBufSize > BIGBUF_SIZE) ? BIGBUF_SIZE : m_cbBufSize;
873
874 //              nprintf(("SOUND", "SOUND => Stream buffer created using %d bytes\n", m_cbBufSize));
875
876                 // Create sound buffer
877                 alGenBuffers(MAX_STREAM_BUFFERS, m_buffer_ids);
878
879                 Snd_sram += m_cbBufSize * MAX_STREAM_BUFFERS;
880         } else {
881                 // Error opening file
882                 nprintf(("SOUND", "SOUND => Failed to open wave file: %s\n\r", pszFilename));
883
884                 m_pwavefile->Close();
885
886                 free(m_pwavefile);
887                 m_pwavefile = NULL;
888
889                 return false;
890         }
891
892         return true;
893 }
894
895 // Destroy
896 bool AudioStream::Destroy()
897 {
898         // Stop playback
899         Stop();
900
901         // Release sound buffer
902         alDeleteBuffers(MAX_STREAM_BUFFERS, m_buffer_ids);
903
904         Snd_sram -= m_cbBufSize;
905
906         // Delete WaveFile object
907         if (m_pwavefile) {
908                 m_pwavefile->Close();
909
910                 free(m_pwavefile);
911                 m_pwavefile = NULL;
912         }
913
914         status = ASF_FREE;
915
916         return true;
917 }
918
919 // WriteWaveData
920 //
921 // Writes wave data to sound buffer. This is a helper method used by Create and
922 // ServiceBuffer; it's not exposed to users of the AudioStream class.
923 bool AudioStream::WriteWaveData(uint size, uint *num_bytes_written, int service)
924 {
925         ubyte *uncompressed_wave_data;
926
927         *num_bytes_written = 0;
928
929         if ( (size == 0) || m_bReadingDone ) {
930                 return true;
931         }
932
933         if ( (m_buffer_ids[0] == 0) || !m_pwavefile ) {
934                 return true;
935         }
936
937         if ( service ) {
938                 SDL_LockMutex(Global_service_lock);
939         }
940                     
941         if ( service ) {
942                 uncompressed_wave_data = Wavedata_service_buffer;
943         } else {
944                 uncompressed_wave_data = Wavedata_load_buffer;
945         }
946
947         int num_bytes_read = 0;
948
949         oal_check_for_errors("AudioStream::WriteWaveData() begin");
950
951         if ( !service ) {
952                 for (int ib = 0; ib < MAX_STREAM_BUFFERS; ib++) {
953                         num_bytes_read = m_pwavefile->Read(uncompressed_wave_data, m_cbBufSize, service);
954
955                         if (num_bytes_read < 0) {
956                                 m_bReadingDone = 1;
957                         } else if (num_bytes_read > 0) {
958                                 alBufferData(m_buffer_ids[ib], m_pwavefile->GetOALFormat(), uncompressed_wave_data, num_bytes_read, m_pwavefile->m_wfmt.sample_rate);
959                                 alSourceQueueBuffers(m_source_id, 1, &m_buffer_ids[ib]);
960                                 *num_bytes_written += num_bytes_read;
961                         }
962                 }
963         } else {
964                 ALint buffers_processed = 0;
965                 ALuint buffer_id = 0;
966
967                 alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &buffers_processed);
968
969                 while (buffers_processed) {
970                         alSourceUnqueueBuffers(m_source_id, 1, &buffer_id);
971
972                         num_bytes_read = m_pwavefile->Read(uncompressed_wave_data, m_cbBufSize, service);
973
974                         if (num_bytes_read < 0) {
975                                 m_bReadingDone = 1;
976                         } else if (num_bytes_read > 0) {
977                                 alBufferData(buffer_id, m_pwavefile->GetOALFormat(), uncompressed_wave_data, num_bytes_read, m_pwavefile->m_wfmt.sample_rate);
978                                 alSourceQueueBuffers(m_source_id, 1, &buffer_id);
979                                 *num_bytes_written += num_bytes_read;
980                         }
981
982                         buffers_processed--;
983                 }
984         }
985
986         oal_check_for_errors("AudioStream::WriteWaveData() end");
987
988         if ( service ) {
989                 SDL_UnlockMutex(Global_service_lock);
990         }
991     
992         return true;
993 }
994
995 // GetMaxWriteSize
996 //
997 // Helper function to calculate max size of sound buffer write operation, i.e. how much
998 // free space there is in buffer.
999 uint AudioStream::GetMaxWriteSize()
1000 {
1001         uint dwMaxSize = m_cbBufSize;
1002         ALint n = 0, q = 0;
1003
1004         oal_check_for_errors("AudioStream::GetMaxWriteSize() begin");
1005
1006         alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &n);
1007
1008         alGetSourcei(m_source_id, AL_BUFFERS_QUEUED, &q);
1009
1010         if ( !n && (q >= MAX_STREAM_BUFFERS) ) {
1011                 //all buffers queued
1012                 dwMaxSize = 0;
1013         }
1014
1015         oal_check_for_errors("AudioStream::GetMaxWriteSize() end");
1016
1017         //      nprintf(("Alan","Max write size: %d\n", dwMaxSize));
1018         return dwMaxSize;
1019 }
1020
1021 #define VOLUME_ATTENUATION_BEFORE_CUTOFF        0.03f           //  12db
1022 #define VOLUME_ATTENUATION                                      0.65f
1023
1024 bool AudioStream::ServiceBuffer()
1025 {
1026         float vol;
1027         bool fRtn = true;
1028
1029         if (type == ASF_FREE) {
1030                 return false;
1031         }
1032
1033         if (m_bFade) {
1034                 if (m_lCutoffVolume == 0.0f) {
1035                         vol = Get_Volume();
1036 //                      nprintf(("Alan","Volume is: %d\n",vol));
1037                         m_lCutoffVolume = vol * VOLUME_ATTENUATION_BEFORE_CUTOFF;
1038                 }
1039
1040                 vol = Get_Volume() * VOLUME_ATTENUATION;
1041 //              nprintf(("Alan","Volume is now: %d\n",vol));
1042                 Set_Volume(vol);
1043
1044 //              nprintf(("Sound","SOUND => Volume for stream sound is %d\n",vol));
1045 //              nprintf(("Alan","Cuttoff Volume is: %d\n",m_lCutoffVolume));
1046                 if (vol < m_lCutoffVolume) {
1047                         m_bFade = false;
1048                         m_lCutoffVolume = 0.0f;
1049
1050                         if (m_bDestroy_when_faded) {
1051                                 Destroy();      
1052
1053                                 return false;
1054                         }
1055                         else {
1056                                 Stop_and_Rewind();
1057
1058                                 return true;
1059                         }
1060                 }
1061         }
1062
1063         // All of sound not played yet, send more data to buffer
1064         uint dwFreeSpace = GetMaxWriteSize();
1065
1066         // Determine free space in sound buffer
1067         if (dwFreeSpace) {
1068                 // Some wave data remains, but not enough to fill free space
1069                 // Send wave data to buffer, fill remainder of free space with silence
1070                 uint num_bytes_written;
1071
1072                 if ( WriteWaveData(dwFreeSpace, &num_bytes_written) ) {
1073 //                      nprintf(("Alan","Num bytes written: %d\n", num_bytes_written));
1074
1075                         if (m_pwavefile->m_total_uncompressed_bytes_read >= m_pwavefile->m_max_uncompressed_bytes_to_read) {
1076                                 m_fade_timer_id = timer_get_milliseconds() + 1700;              // start fading 1.7 seconds from now
1077                                 m_finished_id = timer_get_milliseconds() + 2000;                // 2 seconds left to play out buffer
1078                                 m_pwavefile->m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
1079                         }
1080
1081                         if ( (m_fade_timer_id > 0) && ((uint)timer_get_milliseconds() > m_fade_timer_id) ) {
1082                                 m_fade_timer_id = 0;
1083                                 Fade_and_Stop();
1084                         }
1085
1086                         if ( (m_finished_id > 0) && ((uint)timer_get_milliseconds() > m_finished_id) ) {
1087                                 m_finished_id = 0;
1088                                 m_bPastLimit = true;
1089                         }
1090
1091                         // see if we're done
1092                         ALint state = 0;
1093
1094                         alGetSourcei(m_source_id, AL_SOURCE_STATE, &state);
1095
1096                         if ( m_bReadingDone && (state != AL_PLAYING) ) {
1097                                 if ( m_bDestroy_when_faded == true ) {
1098                                         Destroy();
1099                                         // Reset reentrancy semaphore
1100
1101                                         return false;
1102                                 }
1103
1104                                 // All of sound has played, stop playback or loop again
1105                                 if ( m_bLooping && !m_bFade) {
1106                                         Play(m_lVolume, m_bLooping);
1107                                 } else {
1108                                         Stop_and_Rewind();
1109                                 }
1110                         }
1111                 } else {
1112                         // Error writing wave data
1113                         fRtn = false;
1114                         Int3(); 
1115                 }
1116         }
1117
1118         return fRtn;
1119 }
1120
1121 // Cue
1122 void AudioStream::Cue()
1123 {
1124         uint num_bytes_written;
1125
1126         if ( !m_fCued ) {
1127                 m_bFade = false;
1128                 m_fade_timer_id = 0;
1129                 m_finished_id = 0;
1130                 m_bPastLimit = false;
1131                 m_lVolume = 1.0f;
1132                 m_lCutoffVolume = 0.0f;
1133
1134                 m_bDestroy_when_faded = false;
1135
1136                 // Reset buffer ptr
1137                 m_cbBufOffset = 0;
1138
1139                 // Reset file ptr, etc
1140                 m_pwavefile->Cue();
1141
1142                 // Unqueue all buffers
1143                 ALint buffers_processed = 0;
1144                 ALuint buffer_id = 0;
1145
1146                 alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &buffers_processed);
1147
1148                 while (buffers_processed) {
1149                         alSourceUnqueueBuffers(m_source_id, 1, &buffer_id);
1150
1151                         buffers_processed--;
1152                 }
1153
1154                 // Fill buffer with wave data
1155                 WriteWaveData(m_cbBufSize, &num_bytes_written, 0);
1156
1157                 m_fCued = true;
1158         }
1159 }
1160
1161 // Play
1162 void AudioStream::Play(float volume, int looping)
1163 {
1164         if ( m_buffer_ids[0] ) {
1165                 oal_check_for_errors("AudioStream::Play() begin");
1166
1167                 // If playing, stop
1168                 if (m_fPlaying) {
1169                         if ( m_bIsPaused == false)
1170                                 Stop_and_Rewind();
1171                 }
1172
1173                 // get source id if we don't have one
1174                 if ( !m_source_id ) {
1175                         sound_channel *chan = oal_get_free_channel(1.0f, -1, SND_PRIORITY_MUST_PLAY);
1176
1177                         if (chan) {
1178                                 m_source_id = chan->source_id;
1179                         } else {
1180                                 return;
1181                         }
1182                 }
1183
1184                 // Cue for playback if necessary
1185                 if (!m_fCued) {
1186                         Cue ();
1187                 }
1188
1189                 if (looping == 1) {
1190                         m_bLooping = true;
1191                 } else {
1192                         m_bLooping = false;
1193                 }
1194
1195                 m_nTimeStarted = timer_get_milliseconds();
1196                 Set_Volume(volume);
1197
1198                 // Kick off timer to service buffer
1199                 m_timer.constructor();
1200
1201                 m_timer.Create(m_nBufService, (ptr_u)this, TimerCallback);
1202
1203                 alSourcef(m_source_id, AL_GAIN, m_lVolume);
1204                 alSource3f(m_source_id, AL_POSITION, 0.0f, 0.0f, 0.0f);
1205                 alSource3f(m_source_id, AL_VELOCITY, 0.0f, 0.0f, 0.0f);
1206                 alSource3f(m_source_id, AL_DIRECTION, 0.0f, 0.0f, 0.0f);
1207                 alSourcef(m_source_id, AL_ROLLOFF_FACTOR, 0.0f);
1208 #ifdef __EMSCRIPTEN__
1209                 // Grrrrr....
1210                 alSourcei(m_source_id, AL_SOURCE_RELATIVE, AL_FALSE);
1211 #else
1212                 alSourcei(m_source_id, AL_SOURCE_RELATIVE, AL_TRUE);
1213 #endif
1214                 alSourcei(m_source_id, AL_LOOPING, AL_FALSE);
1215
1216                 alSourcePlay(m_source_id);
1217
1218                 // Playback begun, no longer cued
1219                 m_fPlaying = true;
1220                 m_bIsPaused = false;
1221
1222                 oal_check_for_errors("AudioStream::Play() end");
1223         }
1224 }
1225
1226 // Timer callback for Timer object created by ::Play method.
1227 bool AudioStream::TimerCallback(ptr_u dwUser)
1228 {
1229     // dwUser contains ptr to AudioStream object
1230     AudioStream * pas = (AudioStream *) dwUser;
1231
1232     return (pas->ServiceBuffer ());
1233 }
1234
1235 void AudioStream::Set_Byte_Cutoff(unsigned int byte_cutoff)
1236 {
1237         if ( m_pwavefile == NULL )
1238                 return;
1239
1240         m_pwavefile->m_max_uncompressed_bytes_to_read = byte_cutoff;
1241 }
1242
1243 uint AudioStream::Get_Bytes_Committed(void)
1244 {
1245         if (m_pwavefile == NULL) {
1246                 return 0;
1247         }
1248
1249         return m_pwavefile->m_total_uncompressed_bytes_read;
1250 }
1251
1252 // Fade_and_Destroy
1253 void AudioStream::Fade_and_Destroy()
1254 {
1255         m_bFade = true;
1256         m_bDestroy_when_faded = true;
1257 }
1258
1259 // Fade_and_Destroy
1260 void AudioStream::Fade_and_Stop()
1261 {
1262         m_bFade = true;
1263         m_bDestroy_when_faded = false;
1264 }
1265
1266 // Stop
1267 void AudioStream::Stop(bool paused)
1268 {
1269         if (m_fPlaying) {
1270                 if (paused) {
1271                         alSourcePause(m_source_id);
1272                 } else {
1273                         alSourceStop(m_source_id);
1274                         alSourcei(m_source_id, AL_BUFFER, 0);
1275                         m_source_id = 0;
1276                 }
1277
1278                 m_fPlaying = false;
1279                 m_bIsPaused = paused;
1280
1281                 // Delete Timer object
1282                 m_timer.destructor();
1283         }
1284 }
1285
1286 // Stop_and_Rewind
1287 void AudioStream::Stop_and_Rewind()
1288 {
1289         if (m_fPlaying) {
1290                 // Stop playback
1291                 alSourceStop(m_source_id);
1292                 alSourcei(m_source_id, AL_BUFFER, 0);
1293                 m_source_id = 0;
1294
1295                 // Delete Timer object
1296                 m_timer.destructor();
1297
1298                 m_fPlaying = false;
1299         }
1300
1301         m_fCued = false;        // this will cause wave file to start from beginning
1302         m_bReadingDone = false;
1303 }
1304
1305 // Set_Volume
1306 void AudioStream::Set_Volume(float vol)
1307 {
1308         if (m_fPlaying) {
1309                 alSourcef(m_source_id, AL_GAIN, vol);
1310         }
1311
1312         m_lVolume = vol;
1313 }
1314
1315
1316 // Set_Volume
1317 float AudioStream::Get_Volume()
1318 {
1319         return m_lVolume;
1320 }
1321
1322
1323 #define MAX_AUDIO_STREAMS       30
1324 static AudioStream *Audio_streams = NULL;
1325
1326
1327 void audiostream_init()
1328 {
1329         if (Audiostream_inited) {
1330                 return;
1331         }
1332
1333         // Allocate memory for the buffer which holds the uncompressed wave data that is streamed from the
1334         // disk during a load/cue
1335         if (Wavedata_load_buffer == NULL) {
1336                 Wavedata_load_buffer = (ubyte*)malloc(BIGBUF_SIZE);
1337
1338                 if (Wavedata_load_buffer == NULL) {
1339                         goto INIT_ERROR;
1340                 }
1341         }
1342
1343         // Allocate memory for the buffer which holds the uncompressed wave data that is streamed from the
1344         // disk during a service interval
1345         if (Wavedata_service_buffer == NULL) {
1346                 Wavedata_service_buffer = (ubyte*)malloc(BIGBUF_SIZE);
1347
1348                 if (Wavedata_service_buffer == NULL) {
1349                         goto INIT_ERROR;
1350                 }
1351         }
1352
1353         // Allocate memory for the buffer which holds the compressed wave data that is read from the hard disk
1354         if (Compressed_buffer == NULL) {
1355                 Compressed_buffer = (ubyte*)malloc(COMPRESSED_BUFFER_SIZE);
1356
1357                 if (Compressed_buffer == NULL) {
1358                         goto INIT_ERROR;
1359                 }
1360         }
1361
1362         if (Compressed_service_buffer == NULL) {
1363                 Compressed_service_buffer = (ubyte*)malloc(COMPRESSED_BUFFER_SIZE);
1364
1365                 if (Compressed_service_buffer == NULL) {
1366                         goto INIT_ERROR;
1367                 }
1368         }
1369
1370         if (Audio_streams == NULL) {
1371                 Audio_streams = (AudioStream*)malloc(sizeof(AudioStream) * MAX_AUDIO_STREAMS);
1372
1373                 if (Audio_streams == NULL) {
1374                         goto INIT_ERROR;
1375                 }
1376         }
1377
1378         for (int i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
1379                 Audio_streams[i].Init_Data();
1380                 Audio_streams[i].status = ASF_FREE;
1381                 Audio_streams[i].type = ASF_NONE;
1382         }
1383
1384         Global_service_lock = SDL_CreateMutex();
1385
1386         Audiostream_inited = 1;
1387
1388         return;
1389
1390 INIT_ERROR:
1391         if (Wavedata_service_buffer) {
1392                 free(Wavedata_service_buffer);
1393                 Wavedata_service_buffer = NULL;
1394         }
1395
1396         if (Compressed_buffer) {
1397                 free(Compressed_buffer);
1398                 Compressed_buffer = NULL;
1399         }
1400
1401         if (Compressed_service_buffer) {
1402                 free(Compressed_service_buffer);
1403                 Compressed_service_buffer = NULL;
1404         }
1405
1406         if (Audio_streams) {
1407                 free(Audio_streams);
1408                 Audio_streams = NULL;
1409         }
1410
1411         Audiostream_inited = 0;
1412 }
1413
1414 // Close down the audiostream system.  Must call audiostream_init() before any audiostream functions can
1415 // be used.
1416 void audiostream_close()
1417 {
1418         if ( !Audiostream_inited ) {
1419                 return;
1420         }
1421
1422         SDL_assert( Audio_streams != NULL );
1423
1424         for (int i = 0; i < MAX_AUDIO_STREAMS; i++) {
1425                 if ( Audio_streams[i].status == ASF_USED ) {
1426                         Audio_streams[i].status = ASF_FREE;
1427                         Audio_streams[i].Destroy();
1428                 }
1429         }
1430
1431         free(Audio_streams);
1432         Audio_streams = NULL;
1433
1434         // free global buffers
1435         if (Wavedata_load_buffer) {
1436                 free(Wavedata_load_buffer);
1437                 Wavedata_load_buffer = NULL;
1438         }
1439
1440         if (Wavedata_service_buffer) {
1441                 free(Wavedata_service_buffer);
1442                 Wavedata_service_buffer = NULL;
1443         }
1444
1445         if (Compressed_buffer) {
1446                 free(Compressed_buffer);
1447                 Compressed_buffer = NULL;
1448         }
1449
1450         if (Compressed_service_buffer) {
1451                 free(Compressed_service_buffer);
1452                 Compressed_service_buffer = NULL;
1453         }
1454
1455         SDL_DestroyMutex( Global_service_lock );
1456
1457         Audiostream_inited = 0;
1458
1459 }
1460
1461 // Open a digital sound file for streaming
1462 //
1463 // input:       filename        =>      disk filename of sound file
1464 //                              type            => what type of audio stream do we want to open:
1465 //                                                                      ASF_SOUNDFX
1466 //                                                                      ASF_EVENTMUSIC
1467 //                                                                      ASF_VOICE
1468 //      
1469 // returns:     success => handle to identify streaming sound
1470 //                              failure => -1
1471 int audiostream_open( const char *filename, int type )
1472 {
1473         int i;
1474
1475         if ( !Audiostream_inited ) {
1476                 return -1;
1477         }
1478
1479         for (i = 0; i < MAX_AUDIO_STREAMS; i++) {
1480                 if (Audio_streams[i].status == ASF_FREE) {
1481                         Audio_streams[i].status = ASF_USED;
1482                         Audio_streams[i].type = type;
1483                         break;
1484                 }
1485         }
1486
1487         if (i == MAX_AUDIO_STREAMS) {
1488                 nprintf(("Sound", "SOUND => No more audio streams available!\n"));
1489                 return -1;
1490         }
1491
1492         switch (type) {
1493                 case ASF_VOICE:
1494                 case ASF_SOUNDFX:
1495                         Audio_streams[i].m_bits_per_sample_uncompressed = 8;
1496                         break;
1497
1498                 case ASF_EVENTMUSIC:
1499                         Audio_streams[i].m_bits_per_sample_uncompressed = 16;
1500                         break;
1501
1502                 default:
1503                         Int3();
1504                         return -1;
1505         }
1506
1507         if ( !Audio_streams[i].Create(filename) ) {
1508                 Audio_streams[i].status = ASF_FREE;
1509                 return -1;
1510         }
1511
1512         return i;
1513 }
1514
1515 void audiostream_close_file(int i, int fade)
1516 {
1517         if ( !Audiostream_inited ) {
1518                 return;
1519         }
1520
1521         if (i < 0) {
1522                 return;
1523         }
1524
1525         SDL_assert( i < MAX_AUDIO_STREAMS );
1526
1527         if (Audio_streams[i].status == ASF_FREE) {
1528                 return;
1529         }
1530
1531         if (fade) {
1532                 Audio_streams[i].Fade_and_Destroy();
1533         } else {
1534                 Audio_streams[i].Destroy();
1535         }
1536 }
1537
1538 void audiostream_close_all(int fade)
1539 {
1540         int i;
1541
1542         if ( !Audiostream_inited ) {
1543                 return;
1544         }
1545
1546         for (i = 0; i < MAX_AUDIO_STREAMS; i++) {
1547                 if (Audio_streams[i].status == ASF_FREE) {
1548                         continue;
1549                 }
1550
1551                 audiostream_close_file(i, fade);
1552         }
1553 }
1554
1555 void audiostream_play(int i, float volume, int looping)
1556 {
1557         if ( !Audiostream_inited ) {
1558                 return;
1559         }
1560
1561         if (i < 0) {
1562                 return;
1563         }
1564
1565         SDL_assert( i < MAX_AUDIO_STREAMS );
1566
1567         if (Audio_streams[i].status == ASF_FREE) {
1568                 return;
1569         }
1570
1571         if (volume < 0.0f) {
1572                 volume = Audio_streams[i].Get_Default_Volume();
1573         }
1574
1575         Audio_streams[i].Set_Default_Volume(volume);
1576         Audio_streams[i].Play(volume, looping);
1577 }
1578
1579 // use as buffer service function
1580 bool audiostream_is_playing(int i)
1581 {
1582         if ( !Audiostream_inited ) {
1583                 return false;
1584         }
1585
1586         if (i < 0) {
1587                 return false;
1588         }
1589
1590         SDL_assert( i < MAX_AUDIO_STREAMS );
1591
1592         if (Audio_streams[i].status == ASF_FREE) {
1593                 return false;
1594         }
1595
1596         return Audio_streams[i].Is_Playing();
1597 }
1598
1599 void audiostream_stop(int i, int rewind, int paused)
1600 {
1601         if ( !Audiostream_inited ) {
1602                 return;
1603         }
1604
1605         if (i < 0) {
1606                 return;
1607         }
1608
1609         SDL_assert( i < MAX_AUDIO_STREAMS );
1610
1611         if (Audio_streams[i].status == ASF_FREE) {
1612                 return;
1613         }
1614
1615         if (rewind) {
1616                 Audio_streams[i].Stop_and_Rewind();
1617         } else {
1618                 Audio_streams[i].Stop( (paused != 0) );
1619         }
1620 }
1621
1622 void audiostream_set_volume_all(float volume, int type)
1623 {
1624         int i;
1625
1626         if ( !Audiostream_inited ) {
1627                 return;
1628         }
1629
1630         for (i = 0; i < MAX_AUDIO_STREAMS; i++) {
1631                 if (Audio_streams[i].status == ASF_FREE) {
1632                         continue;
1633                 }
1634
1635                 if (Audio_streams[i].type == type) {
1636                         Audio_streams[i].Set_Volume(volume);
1637                 }
1638         }
1639 }
1640
1641 void audiostream_set_volume(int i, float volume)
1642 {
1643         if ( !Audiostream_inited ) {
1644                 return;
1645         }
1646
1647         if (i < 0) {
1648                 return;
1649         }
1650
1651         SDL_assert( i < MAX_AUDIO_STREAMS );
1652
1653         if (Audio_streams[i].status == ASF_FREE) {
1654                 return;
1655         }
1656
1657         Audio_streams[i].Set_Volume(volume);
1658 }
1659
1660 bool audiostream_is_paused(int i)
1661 {
1662         if ( !Audiostream_inited ) {
1663                 return false;
1664         }
1665
1666         if (i < 0) {
1667                 return false;
1668         }
1669
1670         SDL_assert( i < MAX_AUDIO_STREAMS );
1671
1672         if (Audio_streams[i].status == ASF_FREE) {
1673                 return false;
1674         }
1675
1676         return Audio_streams[i].Is_Paused();
1677 }
1678
1679 void audiostream_set_byte_cutoff(int i, uint cutoff)
1680 {
1681         if ( !Audiostream_inited ) {
1682                 return;
1683         }
1684
1685         if (i < 0) {
1686                 return;
1687         }
1688
1689         SDL_assert( i < MAX_AUDIO_STREAMS );
1690
1691         if (Audio_streams[i].status == ASF_FREE) {
1692                 return;
1693         }
1694
1695         Audio_streams[i].Set_Byte_Cutoff(cutoff);
1696 }
1697
1698 uint audiostream_get_bytes_committed(int i)
1699 {
1700         if ( !Audiostream_inited ) {
1701                 return 0;
1702         }
1703
1704         if (i < 0) {
1705                 return 0;
1706         }
1707
1708         SDL_assert( i < MAX_AUDIO_STREAMS );
1709
1710         if (Audio_streams[i].status == ASF_FREE) {
1711                 return 0;
1712         }
1713
1714         return Audio_streams[i].Get_Bytes_Committed();
1715 }
1716
1717 bool audiostream_done_reading(int i)
1718 {
1719         if ( !Audiostream_inited ) {
1720                 return true;
1721         }
1722
1723         if (i < 0) {
1724                 return true;
1725         }
1726
1727         SDL_assert( i < MAX_AUDIO_STREAMS );
1728
1729         if (Audio_streams[i].status == ASF_FREE) {
1730                 return true;
1731         }
1732
1733         return Audio_streams[i].Is_Past_Limit();
1734 }
1735
1736 int audiostream_is_inited()
1737 {
1738         return Audiostream_inited;
1739 }
1740
1741 void audiostream_pause(int i)
1742 {
1743         if ( !Audiostream_inited ) {
1744                 return;
1745         }
1746
1747         if (i < 0) {
1748                 return;
1749         }
1750
1751         SDL_assert( i < MAX_AUDIO_STREAMS );
1752
1753         if (Audio_streams[i].status == ASF_FREE) {
1754                 return;
1755         }
1756
1757         if ( audiostream_is_playing(i) ) {
1758                 audiostream_stop(i, 0, 1);
1759         }
1760 }
1761
1762 void audiostream_pause_all()
1763 {
1764         int i;
1765
1766         if ( !Audiostream_inited ) {
1767                 return;
1768         }
1769
1770         for (i = 0; i < MAX_AUDIO_STREAMS; i++) {
1771                 if (Audio_streams[i].status == ASF_FREE) {
1772                         continue;
1773                 }
1774
1775                 audiostream_pause(i);
1776         }
1777 }
1778
1779 void audiostream_unpause(int i)
1780 {
1781         int is_looping;
1782
1783         if ( !Audiostream_inited ) {
1784                 return;
1785         }
1786
1787         if (i < 0) {
1788                 return;
1789         }
1790
1791         SDL_assert( i < MAX_AUDIO_STREAMS );
1792
1793         if (Audio_streams[i].status == ASF_FREE) {
1794                 return;
1795         }
1796
1797         if ( audiostream_is_paused(i) ) {
1798                 is_looping = Audio_streams[i].Is_looping();
1799                 audiostream_play(i, -1.0f, is_looping);
1800         }
1801 }
1802
1803 void audiostream_unpause_all()
1804 {
1805         int i;
1806
1807         if ( !Audiostream_inited ) {
1808                 return;
1809         }
1810
1811         for (i = 0; i < MAX_AUDIO_STREAMS; i++) {
1812                 if (Audio_streams[i].status == ASF_FREE) {
1813                         continue;
1814                 }
1815
1816                 audiostream_unpause(i);
1817         }
1818 }