Debian Codegraph @

stream_audio/streamaudio.cpp

raw symbols SCIP
1 /*
2 * Descent 3
3 * Copyright (C) 2024 Parallax Software
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 --- HISTORICAL COMMENTS FOLLOW ---
19
20 * $Logfile: /DescentIII/Main/streamaudio/streamaudio.cpp $
21 * $Revision: 1.1.1.1 $
22 * $Date: 2000/04/18 00:00:49 $
23 * $Author: icculus $
24 *
25 * Interface for streaming audio, compressed or not
26 *
27 * $Log: streamaudio.cpp,v $
28 * Revision 1.1.1.1 2000/04/18 00:00:49 icculus
29 * initial checkin
30 *
31 *
32 * 44 9/29/99 5:13p Jeff
33 * Linux now has real stream audio
34 *
35 * 43 7/28/99 2:04p Kevin
36 * Macintosh Changes
37 *
38 * 41 5/17/99 1:56p Ardussi
39 * changed to compile on Mac
40 *
41 * 40 5/10/99 9:22p Samir
42 * added code to allow for certain streams to be specified to start on
43 * next sound frame.
44 *
45 * 39 4/29/99 3:03p Samir
46 * took out mprintfs and if we're opening an opened stream, close it and
47 * continue.
48 *
49 * 38 4/17/99 5:58a Jeff
50 * Changes for linux
51 *
52 * 37 4/14/99 1:48a Jeff
53 * fixed case mismatched #includes
54 *
55 * 36 4/10/99 5:09p Samir
56 * beginning to add prioritization of sounds code. currently non
57 * functional, but allows me to change all calls to Play3dSound so that I
58 * can test later.
59 *
60 * 35 3/22/99 5:12p Samir
61 * on shutdown, CLOSE any open streams.
62 *
63 * 34 3/17/99 4:22p Samir
64 * made pause and resume for streams work.
65 *
66 * 33 3/09/99 6:40p Jeff
67 * put try/catch around StreamPlay
68 *
69 * 32 3/04/99 6:38p Samir
70 * Saved stream state per frame.
71 *
72 * 31 3/03/99 5:08p Samir
73 * added slew of debug code: hopefully the library will be revamped after
74 * OEM.
75 *
76 * 30 3/01/99 8:11p Samir
77 * fixed bug when audio stream was playing while sound system shutdown.
78 *
79 * 29 2/28/99 6:35p Samir
80 * fixed streaming bugs for very small samples.
81 *
82 * 28 2/28/99 5:11p Nate
83 * added playcount.
84 *
85 * 27 2/27/99 6:52p Samir
86 * added function to get current loop count
87 *
88 * 26 2/26/99 8:34p Samir
89 * may have fixed problem with really small streams.
90 *
91 * 25 2/26/99 5:31p Samir
92 *
93 * 24 2/25/99 9:20p Kevin
94 * Semi fix for music in DS
95 *
96 * 23 2/17/99 8:35p Samir
97 * use m_streamdone to determine whether play should reset the stream or
98 * not.
99 *
100 * 22 12/13/98 6:50p Samir
101 * fixed problems with looping and next.switching sync.
102 *
103 * 21 12/11/98 5:25p Samir
104 * took out debug messages.
105 *
106 * 20 12/11/98 5:20p Samir
107 * perhaps prevent unused buffers from playing.
108 *
109 * 19 12/11/98 3:27p Samir
110 * add debug code.
111 *
112 * 18 12/10/98 7:12p Samir
113 * fixed some bugs in file/playback buffer sequencing with new system.
114 *
115 * 17 12/10/98 10:11a Samir
116 * newer streaming audio library.
117 *
118 * 11 11/20/98 5:20p Samir
119 * correcting a lot of errors in AudioStream::Next
120 *
121 * 10 11/13/98 4:03p Nate
122 * took out volume stuff from high level sound lib
123 *
124 * 9 11/13/98 2:25p Samir
125 * added 'next' stream processing.
126 *
127 * 9 11/13/98 10:48a Samir
128 * added 'next' stream capability.
129 *
130 * 8 10/23/98 7:04p Samir
131 *
132 * 7 10/23/98 6:45p Matt
133 * Scale the streaming audio volume by the master volume.
134 *
135 * 6 8/10/98 5:54p Samir
136 * added looping streams and soft measure stopping.
137 *
138 * 5 7/30/98 4:35p Dan
139 * more error checking.
140 *
141 * 4 7/30/98 10:57a Sean
142 * if no sound, then don't do anything.
143 *
144 * 3 7/24/98 5:18p Samir
145 * use OSFArchive for stream file operations now.
146 *
147 * 2 7/09/98 8:36p Samir
148 * fully implemented redo of Stream interface.
149 *
150 * 1 7/09/98 6:48p Samir
151 *
152 * MOVED FROM MAIN PROJECT
153 *
154 * 10 6/29/98 4:15p Chris
155 * Streaming audio works
156 *
157 * 9 6/24/98 5:00p Jeff
158 * set filehandle to null on close, short circuit read data if file handle
159 * is NULL
160 *
161 * 8 6/24/98 4:41p Jeff
162 * will kill the stream is the sound is killed
163 *
164 *
165 * $NoKeywords: $
166 */
167
168 #include <cstdlib>
169 #include <cstring>
170
171 #include "adecode.h"
172 #include "cfile.h"
173 #include "ddio.h"
174 #include "Macros.h"
175 #include "mem.h"
176 #include "pserror.h"
177 #include "streamaudio.h"
178
179 #define LOGFILE(_s)
180 // this stream is for everyone (used by the StreamPlay interface)
181 static AudioStream User_audio_stream;
182 llsSystem *AudioStream::m_ll_sndsys = NULL;
183 AudioStream *AudioStream::m_streams[STRM_LIMIT];
184 int AudioStream::m_thisid = -1;
185 #define SAMPLES_PER_STREAM_SHORT_BUF 22050
186 #define SAMPLES_PER_STREAM_BUF 44100
187 // sets the low-level sound object
188 void AudioStream::InitSystem(llsSystem *sndsys) {
189 int i;
190 AudioStream::m_ll_sndsys = sndsys;
191 // reserve sound slots for streams, they should never get replaced, and always should be played.
192 for (i = 0; i < STRM_LIMIT; i++) {
193 AudioStream::m_streams[i] = NULL;
194 }
195 }
196 // shutdsown
197 void AudioStream::Shutdown() {
198 if (AudioStream::m_ll_sndsys) {
199 int i;
200 // stop all streams.
201 for (i = 0; i < STRM_LIMIT; i++) {
202 if (AudioStream::m_streams[i]) {
203 AudioStream::m_streams[i]->Close();
204 AudioStream::m_streams[i] = NULL;
205 }
206 }
207 AudioStream::m_ll_sndsys = NULL;
208 }
209 }
210 // allocates a stream slot for a stream
211 bool AudioStream::ActivateStream(AudioStream *stream) {
212 int i;
213 for (i = 0; i < STRM_LIMIT; i++) {
214 if (AudioStream::m_streams[i] == NULL) {
215 AudioStream::m_streams[i] = stream;
216 stream->m_streamindex = i;
217 return true;
218 }
219 }
220 mprintf(0, "STRMAUD: AudioStream queue filled!\n");
221 return false;
222 }
223 void AudioStream::DeactivateStream(AudioStream *stream) {
224 if (stream->m_streamindex > -1) {
225 AudioStream::m_streams[stream->m_streamindex] = NULL;
226 stream->m_streamindex = -1;
227 }
228 }
229 // called by application to allow stream playback
230 void AudioStream::Frame() {
231 int t;
232 float time = timer_GetTime();
233 if (!m_ll_sndsys)
234 return;
235 for (t = 0; t < STRM_LIMIT; t++) {
236 if (AudioStream::m_streams[t]) {
237 AudioStream *strm = AudioStream::m_streams[t];
238 if (strm->m_laststate != strm->m_state) {
239 LOGFILE((_logfp, "STRM[%d]:frame_state=%d\n", strm->m_curid, strm->m_state));
240 }
241 if (strm->m_state == STRM_PLAYING) {
242 // see if the sound is still playing if it isn't then kill it (also if no more loops)
243 strm->m_measure_timer += (time - strm->m_last_frametime);
244 if (strm->m_measure_timer >= strm->m_measure_time) {
245 strm->m_curmeasure++;
246 }
247 strm->m_last_frametime = time;
248 if (strm->m_state == STRM_PLAYING)
249 strm->UpdateData();
250 } else if (strm->m_state == STRM_STOPPING) {
251 if (!AudioStream::m_ll_sndsys->IsSoundInstancePlaying(strm->m_llshandle)) {
252 strm->Stop();
253 // mprintf(0, "STRM[%d]: Stopped!\n", strm->m_curid);
254 LOGFILE((_logfp, "STRM[%d]: Stopped!\n", strm->m_curid));
255 if (CHECK_FLAG(strm->m_flags, STRM_OPNF_ONETIME)) {
256 strm->Close();
257 }
258 strm->m_readahead = false;
259 }
260 } else if (strm->m_state == STRM_INVALID) {
261 strm->DeactivateStream(strm);
262 } else if (strm->m_start_on_frame) {
263 strm->m_llshandle = m_ll_sndsys->PlayStream(&strm->m_playinfo);
264 if (strm->m_llshandle > -1) {
265 // for one buffer samples, prepare to stop now so that the one and only one buffer gets called.
266 // looped one buffer samples dont do this though...
267 if (strm->m_nbufs == 1 && !strm->m_start_on_frame_looped) {
268 strm->m_state = STRM_STOPPING;
269 } else {
270 strm->m_state = STRM_PLAYING;
271 }
272 }
273 strm->m_start_on_frame = false;
274 strm->m_start_on_frame_looped = false;
275 }
276 strm->m_laststate = strm->m_state;
277 }
278 }
279 }
280 // called to pause all streams.
281 void AudioStream::PauseAll() {
282 int t;
283 for (t = 0; t < STRM_LIMIT; t++) {
284 if (AudioStream::m_streams[t]) {
285 AudioStream::m_streams[t]->Pause();
286 }
287 }
288 }
289 void AudioStream::ResumeAll() {
290 int t;
291 for (t = 0; t < STRM_LIMIT; t++) {
292 if (AudioStream::m_streams[t]) {
293 AudioStream::m_streams[t]->Resume();
294 }
295 }
296 }
297 // AudioStream object Interface
298 // allows dynamic playing of streams
299 AudioStream::AudioStream() {
300 m_decoder = NULL; // audio decomp object
301 m_llshandle = -1; // snd system handle
302 m_sbufidx = 0; // stream position markers for synching.
303 m_fbufidx = 0;
304 m_flags = 0;
305 m_state = STRM_INVALID;
306 m_streamindex = -1;
307 m_curmeasure = -1;
308 m_stopnextmeasure = false;
309 m_stopflag = NULL;
310 m_bytesleft = 0;
311 m_readahead_finished_loop = false;
312 m_playcount = 0;
313 m_curid = -1;
314 m_nbufs = 0;
315 m_start_on_frame = false;
316 }
317 AudioStream::~AudioStream() { AudioStream::Close(); }
318 // sets flags for playback (STRM_OPNF_XXX)
319 void AudioStream::SetFlags(int flags) { m_flags = flags; }
320 void AudioStream::SetLoopCount(int loop_count) {
321 // if loop_count = 0, then m_loopcount= -1, infinite;
322 // if loop_count = 1, then m_loopcount=0, no looping, etc.
323 m_loopcount = loop_count - 1;
324 }
325 int AudioStream::GetLoopCount() const {
326 // if loop_count = 0, then m_loopcount= -1, infinite;
327 // if loop_count = 1, then m_loopcount=0, no looping, etc.
328 return m_loopcount + 1;
329 }
330 void AudioStream::SetVolume(float vol) {
331 m_volume = vol;
332 if (m_ll_sndsys) {
333 if (m_llshandle < 0)
334 return;
335 m_ll_sndsys->AdjustSound(m_llshandle, vol, 0.0f, m_playinfo.samples_per_22khz_sample * 22050);
336 }
337 }
338 float AudioStream::GetVolume() { return m_volume; }
339 // flags specify what type of stream it is.
340 bool AudioStream::Open(const char *filename, int open_flags) {
341 // don't open a stream that's already open, or bogus filename
342 if (m_state != STRM_INVALID) {
343 AudioStream::Close();
344 // Int3();
345 // return false;
346 }
347 if (m_archive.Opened() || !filename)
348 return false;
349 if (!m_ll_sndsys)
350 return false;
351 m_state = STRM_INVALID;
352 m_streamindex = -1;
353 m_flags = open_flags;
354 m_curmeasure = 0;
355 m_volume = 1.0f;
356 m_bufsize = SAMPLES_PER_STREAM_BUF * 4;
357 m_measure_timer = 0.0f;
358 m_measure_time = 0.0f;
359 m_last_frametime = 0.0f;
360 m_readahead_finished_loop = false;
361 m_curid = -1;
362 m_nbufs = 0;
363 m_start_on_frame = m_start_on_frame_looped = false;
364 // open up stream file
365 if (m_archive.Open(filename)) {
366 int i;
367 int nbufs;
368 ASSERT(m_archive.StreamType() == OSF_DIGITAL_STRM);
369 m_thisid++;
370 m_curid = m_thisid;
371
372 for (i = 0; i < STRM_BUFCOUNT; i++) {
373 m_buffer[i].flags = 0;
374 m_buffer[i].nbytes = 0;
375 m_buffer[i].data = NULL;
376 m_buffer[i].id = -1; // marks stream buffer to be allocated.
377 }
378 // gradual streams don't readahead yet.
379 nbufs = CHECK_FLAG(m_flags, STRM_OPNF_GRADUAL) ? 1 : STRM_BUFCOUNT;
380
381 if (!AudioStream::ReopenDigitalStream(0, nbufs)) {
382 return false;
383 }
384 AudioStream::SetLoopCount(1);
385 m_laststate = m_state;
386 m_state = STRM_STOPPED;
387 return true;
388 }
389 return false;
390 }
391 // deallocates all stream buffers and decoder.
392 void AudioStream::Close() {
393 int i;
394 if (m_archive.Opened()) {
395 // stop the stream, close the archive, close the decoder.
396 AudioStream::Stop();
397 m_archive.Close();
398 m_curid = -1;
399 // free streaming buffers and decoder if we need to.
400 for (i = 0; i < STRM_BUFCOUNT; i++) {
401 if (m_buffer[i].data) {
402 mem_free(m_buffer[i].data);
403 m_buffer[i].data = NULL;
404 m_buffer[i].nbytes = 0;
405 m_buffer[i].flags = 0;
406 m_buffer[i].id = -1;
407 }
408 }
409
410 if (m_decoder) {
411 delete m_decoder;
412 m_decoder = NULL;
413 }
414 }
415 m_playcount = 0;
416 m_nbufs = 0;
417 m_state = STRM_INVALID;
418 }
419 // has stream finished with its readahead of current loop?
420 bool AudioStream::ReadAheadFinishedLoop() {
421 if (m_readahead_finished_loop) {
422 m_readahead_finished_loop = false;
423 return true;
424 }
425 return false;
426 }
427 // are we still reading from disk?
428 bool AudioStream::ReadAhead() { return m_readahead; }
429 bool AudioStream::IsReady() {
430 if (m_state == STRM_STOPPED) {
431 if (!m_readahead || m_fbufidx == (STRM_BUFCOUNT - 1)) {
432 return true;
433 }
434 }
435 return false;
436 }
437 //////////////////////////////////////////////////////////////////////////////
438 bool AudioStream::ReopenDigitalStream(uint8_t fbufidx, int nbufs) {
439 const tOSFDigiHdr *digihdr = (const tOSFDigiHdr *)m_archive.StreamHeader();
440
441 m_bytesleft = m_archive.StreamLength();
442 m_readahead = false;
443
444 // free current decoder.
445 if (m_decoder) {
446 delete m_decoder;
447 m_decoder = NULL;
448 }
449
450 // instatiate decompression facility or use raw source data
451 uint32_t sample_count = 0;
452 uint32_t channels = 0;
453 if (m_archive.StreamComp() == OSF_DIGIACM_STRM) {
454 uint32_t sample_rate;
455 m_decoder = AudioDecoder::CreateDecoder(ADecodeFileRead, this, channels, sample_rate, sample_count);
456 if (!m_decoder) {
457 delete m_decoder;
458 m_decoder = NULL;
459 return false;
460 }
461 } else {
462 return false;
463 }
464
465 // convert bufsize to true bufsize (bufsize = samples per measure for now.)
466 int bytesize, granularity;
467 switch (m_archive.StreamFormat()) {
468 case SAF_8BIT_M:
469 granularity = 1;
470 break;
471 case SAF_8BIT_S:
472 granularity = 2;
473 bytesize = digihdr->measure << 1;
474 break;
475 case SAF_16BIT_M:
476 granularity = 2;
477 bytesize = digihdr->measure << 1;
478 break;
479 case SAF_16BIT_S:
480 granularity = 4;
481 bytesize = digihdr->measure << 2;
482 break;
483 }
484
485 // bufsize is bytes per measure. now scale according to memory requirements.
486 // clear out buffer list
487 if (channels == 0 || channels > 2) {
488 // weird, faulty osf
489 mprintf(0, "STRM[%d]: Illegal OSF (no channels?): %d.\n", m_curid, channels);
490 LOGFILE((_logfp, "STRM[%d]: Illegal OSF (no channels?): %d.\n", m_curid, channels));
491 return false;
492 }
493
494 int32_t bytes_per_buf = (SAMPLES_PER_STREAM_BUF * granularity);
495 int32_t filelen = (sample_count / channels) * granularity;
496 int nbuffers = filelen / bytes_per_buf;
497 if (nbuffers >= 0 && nbuffers <= 1) {
498 if (filelen > 0) {
499 bytes_per_buf = (SAMPLES_PER_STREAM_SHORT_BUF * granularity);
500 nbuffers = filelen / bytes_per_buf;
501 if (nbuffers == 0)
502 nbuffers = 1;
503 } else {
504 mprintf(0, "STRM[%d]: Bad stream length %d\n", m_curid, filelen);
505 LOGFILE((_logfp, "STRM[%d]: Bad stream length %d\n", m_curid, filelen));
506 return false;
507 }
508 }
509 m_playbytestotal = filelen;
510 m_playbytesleft = filelen;
511 m_fbufidx = fbufidx;
512 m_sbufidx = 0;
513 // Get the file size, and figure out an ideal buffer size
514 // so our looping sounds don't have an odd silence in the middle
515 m_measure_time = (digihdr->measure / 22050.0f);
516 m_bufsize = (filelen / nbuffers);
517 // figure out if we still need to be 4-byte aligned.
518 granularity = granularity >> 1;
519 if (granularity) {
520 if (m_bufsize % 4) {
521 m_bufsize = m_bufsize + (4 - (m_bufsize % 4));
522 if (m_bufsize % 4) {
523 Int3();
524 }
525 }
526 }
527 // mprintf(0,"STRM[%d]: Using buffer size of %d\n",m_curid, m_bufsize);
528 LOGFILE((_logfp, "STRM[%d]: Using buffer size of %d\n", m_curid, m_bufsize));
529 // mark stream as not done.
530 m_readahead = true;
531 m_readahead_finished_loop = false;
532 if (!nbufs) {
533 // dont set m_readahead, because readahead only told this function whether it was going to do
534 // the read of buffers now, or let UpdateData do it later.
535 return true;
536 }
537 // fill buffers.
538 nbufs--;
539 while (!CHECK_FLAG(m_buffer[m_fbufidx].flags, STRM_BUFF_USED) && nbufs >= 0 && m_readahead) {
540 // if our stream's current id does not match the streaming buffer's id, then we need to reallocate
541 // the stream buffer with the new memory size
542 if (m_buffer[m_fbufidx].id != (int)m_curid) {
543 if (m_buffer[m_fbufidx].data) {
544 mem_free(m_buffer[m_fbufidx].data);
545 }
546 m_buffer[m_fbufidx].data = (uint8_t *)mem_malloc(m_bufsize);
547 }
548 m_buffer[m_fbufidx].nbytes = AudioStream::ReadFileData(m_fbufidx, m_bufsize);
549 m_buffer[m_fbufidx].flags = 0;
550 m_buffer[m_fbufidx].flags |= STRM_BUFF_USED;
551 m_buffer[m_fbufidx].id = m_thisid;
552 m_playbytesleft -= m_buffer[m_fbufidx].nbytes;
553 // mprintf(0, "[%d]:pbytesleft=%d\n", m_curid, m_playbytesleft);
554 LOGFILE((_logfp, "[%d]:pbytesleft=%d\n", m_curid, m_playbytesleft));
555 if (m_playbytesleft <= (m_bufsize / 4)) {
556 // mprintf(0, "STRM[%d]: ", m_curid);
557 if (m_buffer[m_fbufidx].nbytes == 0) {
558 memset(m_buffer[m_fbufidx].data, 0, 4);
559 m_buffer[m_fbufidx].nbytes = 4;
560 mprintf(0, "making empty buffer and");
561 }
562 // mprintf(0, "TERMINAL buffer.\n");
563 LOGFILE((_logfp, "STRM[%d] TERMINAL buffer. ", m_curid));
564 m_buffer[m_fbufidx].flags |= STRM_BUFF_TERMINAL;
565 m_readahead = false;
566 m_readahead_finished_loop = true;
567 }
568 m_nbufs++;
569 //@@ if (m_buffer[m_fbufidx].nbytes < m_bufsize || m_bytesleft == 0) {
570 //@@ if (m_buffer[m_fbufidx].nbytes == 0) {
571 //@@ memset(m_buffer[m_fbufidx].data, 0, 4);
572 //@@ m_buffer[m_fbufidx].nbytes = 4;
573 //@@ }
574 //@@ m_buffer[m_fbufidx].flags |= STRM_BUFF_TERMINAL;
575 //@@ m_readahead = false;
576 //@@ m_readahead_finished_loop = true;
577 //@@ }
578 m_fbufidx = (m_fbufidx + 1) % STRM_BUFCOUNT;
579 }
580 // readjust file buffer index down so that it matches the CURRENT file index, not the next one.
581 if (m_fbufidx == 0)
582 m_fbufidx = STRM_BUFCOUNT - 1;
583 else
584 m_fbufidx--;
585 return true;
586 }
587 ///////////////////////////////////////////////////////////////////////////////
588 // plays a stream
589 bool AudioStream::Play(bool start_on_frame) {
590 // call low level stream manager. - samir
591 int sflag = SIF_STREAMING_16_M, i;
592 bool looped = false;
593 if (m_state == STRM_INVALID) {
594 #ifdef WIN32
595 Int3();
596 #endif
597 return false;
598 }
599 // play stream if there's room to.
600 if (!ActivateStream(this))
601 return false;
602 switch (m_archive.StreamFormat()) {
603 case SAF_8BIT_M:
604 sflag = SIF_STREAMING_8_M;
605 break;
606 case SAF_8BIT_S:
607 sflag = SIF_STREAMING_8_S;
608 break;
609 case SAF_16BIT_M:
610 sflag = SIF_STREAMING_16_M;
611 break;
612 case SAF_16BIT_S:
613 sflag = SIF_STREAMING_16_S;
614 break;
615 default:
616 Int3();
617 return false;
618 }
619 // reset soft stopping.
620 m_stopnextmeasure = false;
621 m_curmeasure = 0;
622 m_stopflag = NULL;
623 if (m_state != STRM_STOPPED) {
624 AudioStream::Stop();
625 }
626 if (m_playcount > 0) {
627 AudioStream::Reset();
628 }
629 m_playcount++;
630 m_measure_timer = 0.0f;
631 m_last_frametime = timer_GetTime();
632 // check for terminal and if loopcount != 0 then specify terminal as looping
633 if (m_loopcount != 0) {
634 for (i = 0; i < STRM_BUFCOUNT; i++) {
635 if (CHECK_FLAG(m_buffer[i].flags, STRM_BUFF_USED)) {
636 if (CHECK_FLAG(m_buffer[i].flags, STRM_BUFF_TERMINAL)) {
637 if (m_loopcount == -1) {
638 m_buffer[m_fbufidx].flags |= STRM_BUFF_LOOPEND;
639 looped = true;
640 AudioStream::Reset();
641 } else if (m_loopcount > 0) {
642 m_buffer[m_fbufidx].flags |= STRM_BUFF_LOOPEND;
643 looped = true;
644 AudioStream::Reset();
645 m_loopcount--;
646 }
647 m_readahead_finished_loop = true;
648 }
649 }
650 }
651 }
652 // if (m_curid == 3) Int3();
653 // invoke low level sound system.
654 memset(&m_playinfo, 0, sizeof(m_playinfo));
655 m_playinfo.samples_per_22khz_sample = 1.0;
656 m_playinfo.sample_skip_interval = 0;
657 m_playinfo.m_stream_cback = AudioStreamCB;
658 m_playinfo.m_stream_data = m_buffer[m_sbufidx].data;
659 m_playinfo.m_stream_format = sflag;
660 m_playinfo.m_stream_size = m_buffer[m_sbufidx].nbytes;
661 m_playinfo.m_stream_handle = m_streamindex;
662 m_playinfo.m_stream_bufsize = m_bufsize;
663 m_playinfo.user_data = this;
664 m_playinfo.left_volume = m_playinfo.right_volume = m_volume;
665 m_playinfo.priority = SND_PRIORITY_CRITICAL; // this stream must play.
666 m_start_on_frame = start_on_frame;
667 m_start_on_frame_looped = looped;
668 if (!m_start_on_frame) {
669 m_llshandle = m_ll_sndsys->PlayStream(&m_playinfo);
670 if (m_llshandle > -1) {
671 // for one buffer samples, prepare to stop now so that the one and only one buffer gets called.
672 // looped one buffer samples dont do this though...
673 if (m_nbufs == 1 && !looped) {
674 m_state = STRM_STOPPING;
675 } else {
676 m_state = STRM_PLAYING;
677 }
678 return true;
679 } else {
680 mprintf(0, "STRMAUD:Eh? this should be reserved??\n");
681 Int3();
682 }
683 }
684 return true;
685 }
686 // pauses a stream
687 void AudioStream::Pause() {
688 if (m_state != STRM_PLAYING) {
689 return;
690 }
691 m_state = STRM_PAUSED;
692 m_ll_sndsys->PauseSound(m_llshandle);
693 // mprintf(0, "Paused stream (%d)\n", m_llshandle);
694 }
695 // pauses a stream
696 void AudioStream::Resume() {
697 if (m_state != STRM_PAUSED) {
698 return;
699 }
700 m_ll_sndsys->ResumeSound(m_llshandle);
701 m_state = STRM_PLAYING;
702 // mprintf(0, "Resumed stream (%d)\n", m_llshandle);
703 }
704 // causes a rewind to start of stream, if on_measure is true, stop occurs when measure ends
705 void AudioStream::Stop(bool on_measure, int *stop_flag) {
706 if (!m_ll_sndsys) {
707 return;
708 }
709 m_start_on_frame = false;
710 if (m_state == STRM_INVALID) {
711 if (stop_flag) {
712 *stop_flag = true;
713 }
714 return;
715 }
716 if (m_state != STRM_STOPPED) {
717 if (!on_measure) {
718 if (m_state == STRM_PLAYING || m_state == STRM_PAUSED || m_state == STRM_STOPPING) {
719 m_ll_sndsys->StopSound(m_llshandle, SKT_STOP_IMMEDIATELY);
720 m_state = STRM_STOPPED;
721 m_readahead = m_readahead_finished_loop = true;
722 DeactivateStream(this);
723 m_llshandle = -1;
724 m_curmeasure = 0;
725 }
726 } else {
727 // handle soft stopping.
728 m_stopflag = stop_flag;
729 if (m_stopflag) {
730 *m_stopflag = false;
731 }
732 m_stopnextmeasure = on_measure;
733 }
734 } else {
735 DeactivateStream(this);
736 m_llshandle = -1;
737 m_curmeasure = 0;
738 if (m_stopflag) {
739 *m_stopflag = true;
740 }
741 }
742 }
743 // performs a clean stop and play when switching to next stream
744 void AudioStream::Reset() {
745 m_archive.Rewind();
746 m_bytesleft = m_archive.StreamLength();
747 m_curmeasure = 0;
748 m_readahead = true;
749 m_playbytesleft = m_playbytestotal;
750 if (m_decoder) {
751 delete m_decoder;
752
753 uint32_t channels;
754 uint32_t sample_rate;
755 uint32_t sample_count;
756 m_decoder = AudioDecoder::CreateDecoder(ADecodeFileRead, this, channels, sample_rate, sample_count);
757 }
758 }
759 //////////////////////////////////////////////////////////////////////////////
760 // invoked by AudioStreamCB.
761 #pragma optimize("", off)
762 void *AudioStream::StreamCallback(int *size) {
763 uint8_t nextbuffer = (m_sbufidx + 1) % STRM_BUFCOUNT;
764 void *data = NULL;
765 // we're not done yet.
766 // adjust sound buffer to the next buffer
767 if (m_state == STRM_STOPPING || m_state == STRM_STOPPED) {
768 if (m_state == STRM_STOPPED) {
769 // mprintf(0, "STRM[%d]: Callback entered while stopping! Force stop.\n", m_curid);
770 LOGFILE((_logfp, "STRM[%d]: Callback entered while stopping! Force stop.\n", m_curid));
771 } else {
772 // mprintf(0, "STRM[%d]: Stopping softly\n", m_curid);
773 LOGFILE((_logfp, "STRM[%d]: Stopping softly\n", m_curid));
774 // if (m_curid == 3) Int3();
775 }
776 // mark played buffer as unused.
777 m_buffer[m_sbufidx].flags = 0;
778 m_buffer[m_sbufidx].nbytes = 0;
779 *size = 0;
780 return NULL;
781 }
782 if (!CHECK_FLAG(m_buffer[nextbuffer].flags, STRM_BUFF_USED)) {
783 // mprintf(0, "STRM[%d]: Playing onetime buffer?\n",m_curid);
784 LOGFILE((_logfp, "STRM[%d]: Playing onetime buffer?\n", m_curid));
785 m_state = STRM_STOPPED;
786 *size = 0;
787 return NULL;
788 //@@ mprintf(0, "STRMAUD: Repeating last buffer.\n");
789 //@@ data = (void *)m_buffer[m_sbufidx].data;
790 //@@ *size = m_buffer[m_sbufidx].nbytes;
791 //@@ return data;
792 }
793 // mark played buffer as unused.
794 m_buffer[m_sbufidx].flags = 0;
795 m_buffer[m_sbufidx].nbytes = 0;
796 m_sbufidx = nextbuffer;
797 // ASSERT(CHECK_FLAG(m_buffer[m_sbufidx].flags, STRM_BUFF_USED));
798 // mprintf(0,"%c",m_sbufidx+'A');
799 // increment measure count if we've entered a new measure.
800 // if stop measure has been flagged, don't return new valid data.
801 // make sure and lock mutex, because we're modifying these contents when the caller could
802 // do the same.
803 // if we reached the last buffer in an opened stream, and we're not switching prepare to stop
804 // if we are switching, release the switch lock and continue
805 // otherwise just continue.
806 data = (void *)m_buffer[m_sbufidx].data;
807 *size = m_buffer[m_sbufidx].nbytes;
808 // ASSERT((*size) > 0);
809 if (CHECK_FLAG(m_buffer[m_sbufidx].flags, STRM_BUFF_TERMINAL)) {
810 // mprintf(0, "STRMAUD: reached end of stream (%d bytes).\n", (*size));
811 if (!CHECK_FLAG(m_buffer[m_sbufidx].flags, STRM_BUFF_LOOPEND)) {
812 m_state = STRM_STOPPING;
813 }
814 if (m_stopnextmeasure) {
815 m_state = STRM_STOPPING;
816 }
817 // mprintf(0, "STRM[%d]: Start stopping softly\n", m_curid);
818 LOGFILE((_logfp, "STRM[%d]: Start stopping softly\n", m_curid));
819 // *done = true;
820 }
821 if ((*size) == 0) {
822 // *done = true;
823 // mprintf(0, "STRM[%d]: Used buffer has 0 bytes!\n", m_curid);
824 LOGFILE((_logfp, "STRM[%d]: Used buffer has 0 bytes!\n", m_curid));
825 m_state = STRM_STOPPING;
826 data = NULL;
827 }
828 return data;
829 }
830 #pragma optimize("", on)
831 // reads in decompressed raw data.
832 int AudioStream::ReadFileData(int buf, int len) {
833 if (!m_archive.Opened())
834 return 0;
835
836 if (m_decoder) {
837 // We have a compressed stream
838 return m_decoder->Read(m_buffer[buf].data, len);
839 }
840
841 // We have a non-compressed stream
842 if (len > m_bytesleft) {
843 len = m_bytesleft;
844 m_bytesleft = 0;
845 } else {
846 m_bytesleft -= len;
847 }
848
849 return m_archive.Read(m_buffer[buf].data, len);
850 }
851 // TURN OFF OPTIMIZATIONS HERE. Placement of instructions is VERY IMPORTANT here. synched with StreamCallback,
852 // which also has optimizations off.
853 #pragma optimize("", off)
854 // updates file buffers
855 void AudioStream::UpdateData() {
856 int nextbuffer = ((m_fbufidx + 1) % STRM_BUFCOUNT);
857 // check if are on a measure boundary for current stream. if so, then check if we have a next request pending
858 if (CHECK_FLAG(m_buffer[nextbuffer].flags, STRM_BUFF_USED)) {
859 return;
860 }
861 // quit out if we can.
862 if (nextbuffer == m_sbufidx) {
863 return;
864 }
865 // do read!
866 // READ DATA INTO BUFFER. UPDATE BYTES LEFT PER MEASURE, ETC.
867 if (m_readahead) {
868 // ok update the next buffer with data
869 m_fbufidx = nextbuffer;
870 // mprintf(0,"%c",m_fbufidx+'a');
871 // if our stream's current id does not match the streaming buffer's id, then we need to reallocate
872 // the stream buffer with the new memory size
873 if (m_buffer[m_fbufidx].id != (int)m_curid) {
874 if (m_buffer[m_fbufidx].data) {
875 mem_free(m_buffer[m_fbufidx].data);
876 }
877 m_buffer[m_fbufidx].data = (uint8_t *)mem_malloc(m_bufsize);
878 }
879 m_buffer[m_fbufidx].nbytes = AudioStream::ReadFileData(m_fbufidx, m_bufsize);
880 m_buffer[m_fbufidx].flags = 0;
881 m_buffer[m_fbufidx].flags |= STRM_BUFF_USED;
882 m_buffer[m_fbufidx].id = (int)m_curid;
883 m_playbytesleft -= m_buffer[m_fbufidx].nbytes;
884 // mprintf(0, "[%d]:pbytesleft=%d\n", m_curid, m_playbytesleft);
885 LOGFILE((_logfp, "[%d]:pbytesleft=%d\n", m_curid, m_playbytesleft));
886 if (m_playbytesleft <= (m_bufsize / 4)) {
887 // mprintf(0, "STRM[%d]: ", m_curid);
888 if (m_buffer[m_fbufidx].nbytes == 0) {
889 memset(m_buffer[m_fbufidx].data, 0, 4);
890 m_buffer[m_fbufidx].nbytes = 4;
891 mprintf(0, "making empty buffer and");
892 }
893 // mprintf(0, "TERMINAL buffer.\n");
894 LOGFILE((_logfp, "STRM[%d]: TERMINAL buffer.\n", m_curid));
895 m_buffer[m_fbufidx].flags |= STRM_BUFF_TERMINAL;
896 m_readahead = false;
897 m_readahead_finished_loop = true;
898 }
899 // looping?
900 if (CHECK_FLAG(m_buffer[m_fbufidx].flags, STRM_BUFF_TERMINAL)) {
901 if (m_loopcount == -1) {
902 m_buffer[m_fbufidx].flags |= STRM_BUFF_LOOPEND;
903 AudioStream::Reset();
904 } else if (m_loopcount > 0) {
905 m_buffer[m_fbufidx].flags |= STRM_BUFF_LOOPEND;
906 AudioStream::Reset();
907 m_loopcount--;
908 }
909 m_readahead_finished_loop = true;
910 }
911 }
912 }
913
914 #pragma optimize("", on)
915 ///////////////////////////////////////////////////////////////////////////////
916 // decoder
917 int ADecodeFileRead(void *data, void *buf, unsigned qty) {
918 AudioStream *stream = (AudioStream *)data;
919 int iqty = (int)qty;
920
921 if (iqty > stream->m_bytesleft) {
922 iqty = stream->m_bytesleft;
923 stream->m_bytesleft = 0;
924 } else {
925 stream->m_bytesleft -= iqty;
926 }
927
928 return stream->m_archive.Read((uint8_t *)buf, iqty);
929 }
930
931 // Router for stream callbacks.
932 // Invoked by sound system
933 void *AudioStreamCB(void *user_data, int handle, int *size) {
934 AudioStream *stream = (AudioStream *)user_data;
935 ASSERT(stream);
936 ASSERT(stream->m_streamindex == handle);
937 return stream->StreamCallback(size);
938 }
939 static float Stream_volume = 1.0f;
940 static float Stream_master_volume = 1.0f;
941 void StreamVolume(float master_volume) {
942 Stream_master_volume = master_volume;
943 User_audio_stream.SetVolume(Stream_volume * master_volume);
944 }
945 // these functions are the 'simplified' stream interface from Jeff (most of this code is from Jeff)
946 int StreamPlay(const char *filename, float volume, int flags) {
947 int retval = -1;
948 try {
949 flags = 0;
950 User_audio_stream.Close();
951 User_audio_stream.Open(filename, STRM_OPNF_ONETIME);
952 Stream_volume = volume;
953 User_audio_stream.SetVolume(Stream_volume * Stream_master_volume);
954 User_audio_stream.Play(true); // start this stream on the next frame.
955 retval = User_audio_stream.m_streamindex;
956 } catch (...) {
957 return -1;
958 }
959 return retval;
960 }
961 void StreamStop(int handle) {
962 if (handle > -1) {
963 if (AudioStream::m_streams[handle])
964 AudioStream::m_streams[handle]->Stop();
965 }
966 User_audio_stream.Close();
967 }
968 int StreamGetSoundHandle(int handle) {
969 if (handle > -1) {
970 if (AudioStream::m_streams[handle])
971 return AudioStream::m_streams[handle]->GetSoundHandle();
972 else
973 return -1;
974 }
975 return -1;
976 }