Advertisement
Kitomas

sfx_callback.cpp 2023-12-08

Dec 8th, 2023 (edited)
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include "_sfx.hpp"
  2.  
  3.  
  4.  
  5.  
  6. //workaround for having _sfx_callback pause the device,
  7.  //without having to call SDL_PauseAudioDevice inside the callback itself
  8. int _sfx_pauseThread(void* data){
  9.   sfx_class* sfx = (sfx_class*)data;
  10.   if(sfx->isClosing()) return 0;
  11.   sfx->lockDevice(true);
  12.  
  13.   //note: might cause problems if sfx is dangling for whatever reason
  14.   try {
  15.     sfx->lock(true);
  16.   } catch(...){
  17.     sfx->lockDevice(false);
  18.     sfx->_getFadeInDelay() = 0xffffffff; //this should work, right?
  19.     return -1;
  20.   }
  21.  
  22.   //make sure current buffer finishes playing
  23.   float bufferLengthSeconds = (float)sfx->getBufferLength() / sfx->getSampleRate();
  24.   SDL_Delay(bufferLengthSeconds*1000 + 10); //+10ms just to be sure
  25.  
  26.   SDL_PauseAudioDevice(sfx->getDeviceID(),1);
  27.   sfx->_setPlaying(false);
  28.  
  29.   sfx->lockDevice(false);
  30.   sfx->lock(false);
  31.   return 0;
  32. }
  33.  
  34.  
  35.  
  36. void _sfx_callback(void* userdata, Uint8* _stream, int size){
  37.   sfx_class*   sfx = (sfx_class*)userdata;
  38.   sfx_f32s* stream = (sfx_f32s*)_stream;
  39.   int          len = size/sizeof(sfx_f32s);
  40.  
  41.   size_t numTracks = sfx->getNumTracks();
  42.   std::vector<sfx_track>& tracks = sfx->_getTracks();
  43.   Uint64 timeStampEnd = sfx->getTimeStampEnd();
  44.  
  45.   sfx->_setTimeStampStart();
  46.   SDL_memset(stream,0,size); //stream must be filled no matter what
  47.   if(sfx->isClosing()) goto _skip_everything_; //if device is closing, exit early
  48.  
  49.   //if previous attempt to pause sfx failed, exit early
  50.   try {
  51.     sfx->lock(true);
  52.   } catch(...){
  53.     sfx->_getFadeInDelay() = 0xffffffff; //should work
  54.     goto _skip_everything_;
  55.   }
  56.   if(sfx->_getFadeInDelay() == 0xffffffff) goto _unlock_device_;
  57.  
  58.  
  59.   /**/
  60.   for(size_t ti=0; ti<numTracks; ++ti){
  61.     if(tracks[ti].pcm != nullptr){
  62.       _sfx_mixTrack(tracks[ti],
  63.                     timeStampEnd,
  64.                     stream, len);
  65.     }
  66.   }
  67.   /**/
  68.  
  69.  
  70.   //apply linear fade to reduce popping when pausing and unpausing the device
  71.   _sfx_globalFade(sfx, stream, len);
  72.  
  73.   _unlock_device_  : try { sfx->lock(false); } catch(...){} //just in case
  74.   _skip_everything_: sfx->_setTimeStampEnd();
  75. }
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement