SoundSource.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Audio/Audio.h"
  5. #include "../Audio/AudioEvents.h"
  6. #include "../Audio/Sound.h"
  7. #include "../Audio/SoundSource.h"
  8. #include "../Audio/SoundStream.h"
  9. #include "../Core/Context.h"
  10. #include "../IO/Log.h"
  11. #include "../Resource/ResourceCache.h"
  12. #include "../Scene/Node.h"
  13. #include "../Scene/ReplicationState.h"
  14. #include "../DebugNew.h"
  15. namespace Urho3D
  16. {
  17. #define INC_POS_LOOPED() \
  18. pos += intAdd; \
  19. fractPos += fractAdd; \
  20. if (fractPos > 65535) \
  21. { \
  22. fractPos &= 65535; \
  23. ++pos; \
  24. } \
  25. while (pos >= end) \
  26. pos -= (end - repeat); \
  27. #define INC_POS_ONESHOT() \
  28. pos += intAdd; \
  29. fractPos += fractAdd; \
  30. if (fractPos > 65535) \
  31. { \
  32. fractPos &= 65535; \
  33. ++pos; \
  34. } \
  35. if (pos >= end) \
  36. { \
  37. pos = 0; \
  38. break; \
  39. } \
  40. #define INC_POS_STEREO_LOOPED() \
  41. pos += ((unsigned)intAdd << 1u); \
  42. fractPos += fractAdd; \
  43. if (fractPos > 65535) \
  44. { \
  45. fractPos &= 65535; \
  46. pos += 2; \
  47. } \
  48. while (pos >= end) \
  49. pos -= (end - repeat); \
  50. #define INC_POS_STEREO_ONESHOT() \
  51. pos += ((unsigned)intAdd << 1u); \
  52. fractPos += fractAdd; \
  53. if (fractPos > 65535) \
  54. { \
  55. fractPos &= 65535; \
  56. pos += 2; \
  57. } \
  58. if (pos >= end) \
  59. { \
  60. pos = 0; \
  61. break; \
  62. } \
  63. #define GET_IP_SAMPLE() (((((int)pos[1] - (int)pos[0]) * fractPos) / 65536) + (int)pos[0])
  64. #define GET_IP_SAMPLE_LEFT() (((((int)pos[2] - (int)pos[0]) * fractPos) / 65536) + (int)pos[0])
  65. #define GET_IP_SAMPLE_RIGHT() (((((int)pos[3] - (int)pos[1]) * fractPos) / 65536) + (int)pos[1])
  66. static const int STREAM_SAFETY_SAMPLES = 4;
  67. extern const char* AUDIO_CATEGORY;
  68. extern const char* autoRemoveModeNames[];
  69. SoundSource::SoundSource(Context* context) :
  70. Component(context),
  71. soundType_(SOUND_EFFECT),
  72. frequency_(0.0f),
  73. gain_(1.0f),
  74. attenuation_(1.0f),
  75. panning_(0.0f),
  76. sendFinishedEvent_(false),
  77. autoRemove_(REMOVE_DISABLED),
  78. position_(nullptr),
  79. fractPosition_(0),
  80. timePosition_(0.0f),
  81. unusedStreamSize_(0)
  82. {
  83. audio_ = GetSubsystem<Audio>();
  84. if (audio_)
  85. audio_->AddSoundSource(this);
  86. UpdateMasterGain();
  87. }
  88. SoundSource::~SoundSource()
  89. {
  90. if (audio_)
  91. audio_->RemoveSoundSource(this);
  92. }
  93. void SoundSource::RegisterObject(Context* context)
  94. {
  95. context->RegisterFactory<SoundSource>(AUDIO_CATEGORY);
  96. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, true, AM_DEFAULT);
  97. URHO3D_ACCESSOR_ATTRIBUTE("Sound", GetSoundAttr, SetSoundAttr, ResourceRef(Sound::GetTypeStatic()), AM_DEFAULT);
  98. URHO3D_ACCESSOR_ATTRIBUTE("Type", GetSoundType, SetSoundType, SOUND_EFFECT, AM_DEFAULT);
  99. URHO3D_ATTRIBUTE("Frequency", frequency_, 0.0f, AM_DEFAULT);
  100. URHO3D_ATTRIBUTE("Gain", gain_, 1.0f, AM_DEFAULT);
  101. URHO3D_ATTRIBUTE("Attenuation", attenuation_, 1.0f, AM_DEFAULT);
  102. URHO3D_ATTRIBUTE("Panning", panning_, 0.0f, AM_DEFAULT);
  103. URHO3D_ACCESSOR_ATTRIBUTE("Is Playing", IsPlaying, SetPlayingAttr, false, AM_DEFAULT);
  104. URHO3D_ENUM_ATTRIBUTE("Autoremove Mode", autoRemove_, autoRemoveModeNames, REMOVE_DISABLED, AM_DEFAULT);
  105. URHO3D_ACCESSOR_ATTRIBUTE("Play Position", GetPositionAttr, SetPositionAttr, 0, AM_FILE);
  106. }
  107. void SoundSource::Seek(float seekTime)
  108. {
  109. // Ignore buffered sound stream
  110. if (!audio_ || !sound_ || (soundStream_ && !sound_->IsCompressed()))
  111. return;
  112. // Set to valid range
  113. seekTime = Clamp(seekTime, 0.0f, sound_->GetLength());
  114. if (!soundStream_)
  115. {
  116. // Raw or wav format
  117. SetPositionAttr((int)(seekTime * (sound_->GetSampleSize() * sound_->GetFrequency())));
  118. }
  119. else
  120. {
  121. // Ogg format
  122. if (soundStream_->Seek((unsigned)(seekTime * soundStream_->GetFrequency())))
  123. {
  124. timePosition_ = seekTime;
  125. }
  126. }
  127. }
  128. void SoundSource::Play(Sound* sound)
  129. {
  130. if (!audio_)
  131. return;
  132. // If no frequency set yet, set from the sound's default
  133. if (frequency_ == 0.0f && sound)
  134. SetFrequency(sound->GetFrequency());
  135. // If sound source is currently playing, have to lock the audio mutex
  136. if (position_)
  137. {
  138. MutexLock lock(audio_->GetMutex());
  139. PlayLockless(sound);
  140. }
  141. else
  142. PlayLockless(sound);
  143. // Forget the Sound & Is Playing attribute previous values so that they will be sent again, triggering
  144. // the sound correctly on network clients even after the initial playback
  145. if (networkState_ && networkState_->attributes_ && networkState_->previousValues_.Size())
  146. {
  147. for (unsigned i = 1; i < networkState_->previousValues_.Size(); ++i)
  148. {
  149. // The indexing is different for SoundSource & SoundSource3D, as SoundSource3D removes two attributes,
  150. // so go by attribute types
  151. VariantType type = networkState_->attributes_->At(i).type_;
  152. if (type == VAR_RESOURCEREF || type == VAR_BOOL)
  153. networkState_->previousValues_[i] = Variant::EMPTY;
  154. }
  155. }
  156. MarkNetworkUpdate();
  157. }
  158. void SoundSource::Play(Sound* sound, float frequency)
  159. {
  160. SetFrequency(frequency);
  161. Play(sound);
  162. }
  163. void SoundSource::Play(Sound* sound, float frequency, float gain)
  164. {
  165. SetFrequency(frequency);
  166. SetGain(gain);
  167. Play(sound);
  168. }
  169. void SoundSource::Play(Sound* sound, float frequency, float gain, float panning)
  170. {
  171. SetFrequency(frequency);
  172. SetGain(gain);
  173. SetPanning(panning);
  174. Play(sound);
  175. }
  176. void SoundSource::Play(SoundStream* stream)
  177. {
  178. if (!audio_)
  179. return;
  180. // If no frequency set yet, set from the stream's default
  181. if (frequency_ == 0.0f && stream)
  182. SetFrequency(stream->GetFrequency());
  183. SharedPtr<SoundStream> streamPtr(stream);
  184. // If sound source is currently playing, have to lock the audio mutex. When stream playback is explicitly
  185. // requested, clear the existing sound if any
  186. if (position_)
  187. {
  188. MutexLock lock(audio_->GetMutex());
  189. sound_.Reset();
  190. PlayLockless(streamPtr);
  191. }
  192. else
  193. {
  194. sound_.Reset();
  195. PlayLockless(streamPtr);
  196. }
  197. // Stream playback is not supported for network replication, no need to mark network dirty
  198. }
  199. void SoundSource::Stop()
  200. {
  201. if (!audio_)
  202. return;
  203. // If sound source is currently playing, have to lock the audio mutex
  204. if (position_)
  205. {
  206. MutexLock lock(audio_->GetMutex());
  207. StopLockless();
  208. }
  209. else
  210. StopLockless();
  211. MarkNetworkUpdate();
  212. }
  213. void SoundSource::SetSoundType(const String& type)
  214. {
  215. if (type == SOUND_MASTER)
  216. return;
  217. soundType_ = type;
  218. soundTypeHash_ = StringHash(type);
  219. UpdateMasterGain();
  220. MarkNetworkUpdate();
  221. }
  222. void SoundSource::SetFrequency(float frequency)
  223. {
  224. frequency_ = Clamp(frequency, 0.0f, 535232.0f);
  225. MarkNetworkUpdate();
  226. }
  227. void SoundSource::SetGain(float gain)
  228. {
  229. gain_ = Max(gain, 0.0f);
  230. MarkNetworkUpdate();
  231. }
  232. void SoundSource::SetAttenuation(float attenuation)
  233. {
  234. attenuation_ = Clamp(attenuation, 0.0f, 1.0f);
  235. MarkNetworkUpdate();
  236. }
  237. void SoundSource::SetPanning(float panning)
  238. {
  239. panning_ = Clamp(panning, -1.0f, 1.0f);
  240. MarkNetworkUpdate();
  241. }
  242. void SoundSource::SetAutoRemoveMode(AutoRemoveMode mode)
  243. {
  244. autoRemove_ = mode;
  245. MarkNetworkUpdate();
  246. }
  247. bool SoundSource::IsPlaying() const
  248. {
  249. return (sound_ || soundStream_) && position_ != nullptr;
  250. }
  251. void SoundSource::SetPlayPosition(signed char* pos)
  252. {
  253. // Setting play position on a stream is not supported
  254. if (!audio_ || !sound_ || soundStream_)
  255. return;
  256. MutexLock lock(audio_->GetMutex());
  257. SetPlayPositionLockless(pos);
  258. }
  259. void SoundSource::Update(float timeStep)
  260. {
  261. if (!audio_ || !IsEnabledEffective())
  262. return;
  263. // If there is no actual audio output, perform fake mixing into a nonexistent buffer to check stopping/looping
  264. if (!audio_->IsInitialized())
  265. MixNull(timeStep);
  266. // Free the stream if playback has stopped
  267. if (soundStream_ && !position_)
  268. StopLockless();
  269. bool playing = IsPlaying();
  270. if (!playing && sendFinishedEvent_)
  271. {
  272. sendFinishedEvent_ = false;
  273. // Make a weak pointer to self to check for destruction during event handling
  274. WeakPtr<SoundSource> self(this);
  275. using namespace SoundFinished;
  276. VariantMap& eventData = context_->GetEventDataMap();
  277. eventData[P_NODE] = node_;
  278. eventData[P_SOUNDSOURCE] = this;
  279. eventData[P_SOUND] = sound_;
  280. node_->SendEvent(E_SOUNDFINISHED, eventData);
  281. if (self.Expired())
  282. return;
  283. DoAutoRemove(autoRemove_);
  284. }
  285. }
  286. void SoundSource::Mix(int* dest, unsigned samples, int mixRate, bool stereo, bool interpolation)
  287. {
  288. if (!position_ || (!sound_ && !soundStream_) || !IsEnabledEffective())
  289. return;
  290. int streamFilledSize, outBytes;
  291. if (soundStream_ && streamBuffer_)
  292. {
  293. int streamBufferSize = streamBuffer_->GetDataSize();
  294. // Calculate how many bytes of stream sound data is needed
  295. auto neededSize = (int)((float)samples * frequency_ / (float)mixRate);
  296. // Add a little safety buffer. Subtract previous unused data
  297. neededSize += STREAM_SAFETY_SAMPLES;
  298. neededSize *= soundStream_->GetSampleSize();
  299. neededSize -= unusedStreamSize_;
  300. neededSize = Clamp(neededSize, 0, streamBufferSize - unusedStreamSize_);
  301. // Always start play position at the beginning of the stream buffer
  302. position_ = streamBuffer_->GetStart();
  303. // Request new data from the stream
  304. signed char* destination = streamBuffer_->GetStart() + unusedStreamSize_;
  305. outBytes = neededSize ? soundStream_->GetData(destination, (unsigned)neededSize) : 0;
  306. destination += outBytes;
  307. // Zero-fill rest if stream did not produce enough data
  308. if (outBytes < neededSize)
  309. memset(destination, 0, (size_t)(neededSize - outBytes));
  310. // Calculate amount of total bytes of data in stream buffer now, to know how much went unused after mixing
  311. streamFilledSize = neededSize + unusedStreamSize_;
  312. }
  313. // If streaming, play the stream buffer. Otherwise play the original sound
  314. Sound* sound = soundStream_ ? streamBuffer_ : sound_;
  315. if (!sound)
  316. return;
  317. // Choose the correct mixing routine
  318. if (!sound->IsStereo())
  319. {
  320. if (interpolation)
  321. {
  322. if (stereo)
  323. MixMonoToStereoIP(sound, dest, samples, mixRate);
  324. else
  325. MixMonoToMonoIP(sound, dest, samples, mixRate);
  326. }
  327. else
  328. {
  329. if (stereo)
  330. MixMonoToStereo(sound, dest, samples, mixRate);
  331. else
  332. MixMonoToMono(sound, dest, samples, mixRate);
  333. }
  334. }
  335. else
  336. {
  337. if (interpolation)
  338. {
  339. if (stereo)
  340. MixStereoToStereoIP(sound, dest, samples, mixRate);
  341. else
  342. MixStereoToMonoIP(sound, dest, samples, mixRate);
  343. }
  344. else
  345. {
  346. if (stereo)
  347. MixStereoToStereo(sound, dest, samples, mixRate);
  348. else
  349. MixStereoToMono(sound, dest, samples, mixRate);
  350. }
  351. }
  352. // Update the time position. In stream mode, copy unused data back to the beginning of the stream buffer
  353. if (soundStream_)
  354. {
  355. timePosition_ += ((float)samples / (float)mixRate) * frequency_ / soundStream_->GetFrequency();
  356. unusedStreamSize_ = Max(streamFilledSize - (int)(size_t)(position_ - streamBuffer_->GetStart()), 0);
  357. if (unusedStreamSize_)
  358. memcpy(streamBuffer_->GetStart(), (const void*)position_, (size_t)unusedStreamSize_);
  359. // If stream did not produce any data, stop if applicable
  360. if (!outBytes && soundStream_->GetStopAtEnd())
  361. {
  362. position_ = nullptr;
  363. return;
  364. }
  365. }
  366. else if (sound_)
  367. timePosition_ = ((float)(int)(size_t)(position_ - sound_->GetStart())) / (sound_->GetSampleSize() * sound_->GetFrequency());
  368. }
  369. void SoundSource::UpdateMasterGain()
  370. {
  371. if (audio_)
  372. masterGain_ = audio_->GetSoundSourceMasterGain(soundType_);
  373. }
  374. void SoundSource::SetSoundAttr(const ResourceRef& value)
  375. {
  376. auto* cache = GetSubsystem<ResourceCache>();
  377. auto* newSound = cache->GetResource<Sound>(value.name_);
  378. if (IsPlaying())
  379. Play(newSound);
  380. else
  381. {
  382. // When changing the sound and not playing, free previous sound stream and stream buffer (if any)
  383. soundStream_.Reset();
  384. streamBuffer_.Reset();
  385. sound_ = newSound;
  386. }
  387. }
  388. void SoundSource::SetPlayingAttr(bool value)
  389. {
  390. if (value)
  391. {
  392. if (!IsPlaying())
  393. Play(sound_);
  394. }
  395. else
  396. Stop();
  397. }
  398. void SoundSource::SetPositionAttr(int value)
  399. {
  400. if (sound_)
  401. SetPlayPosition(sound_->GetStart() + value);
  402. }
  403. ResourceRef SoundSource::GetSoundAttr() const
  404. {
  405. return GetResourceRef(sound_, Sound::GetTypeStatic());
  406. }
  407. int SoundSource::GetPositionAttr() const
  408. {
  409. if (sound_ && position_)
  410. return (int)(GetPlayPosition() - sound_->GetStart());
  411. else
  412. return 0;
  413. }
  414. void SoundSource::PlayLockless(Sound* sound)
  415. {
  416. // Reset the time position in any case
  417. timePosition_ = 0.0f;
  418. if (sound)
  419. {
  420. if (!sound->IsCompressed())
  421. {
  422. // Uncompressed sound start
  423. signed char* start = sound->GetStart();
  424. if (start)
  425. {
  426. // Free existing stream & stream buffer if any
  427. soundStream_.Reset();
  428. streamBuffer_.Reset();
  429. sound_ = sound;
  430. position_ = start;
  431. fractPosition_ = 0;
  432. sendFinishedEvent_ = true;
  433. return;
  434. }
  435. }
  436. else
  437. {
  438. // Compressed sound start
  439. PlayLockless(sound->GetDecoderStream());
  440. sound_ = sound;
  441. return;
  442. }
  443. }
  444. // If sound pointer is null or if sound has no data, stop playback
  445. StopLockless();
  446. sound_.Reset();
  447. }
  448. void SoundSource::PlayLockless(const SharedPtr<SoundStream>& stream)
  449. {
  450. // Reset the time position in any case
  451. timePosition_ = 0.0f;
  452. if (stream)
  453. {
  454. // Setup the stream buffer
  455. unsigned sampleSize = stream->GetSampleSize();
  456. unsigned streamBufferSize = sampleSize * stream->GetIntFrequency() * STREAM_BUFFER_LENGTH / 1000;
  457. streamBuffer_ = new Sound(context_);
  458. streamBuffer_->SetSize(streamBufferSize);
  459. streamBuffer_->SetFormat(stream->GetIntFrequency(), stream->IsSixteenBit(), stream->IsStereo());
  460. streamBuffer_->SetLooped(true);
  461. soundStream_ = stream;
  462. unusedStreamSize_ = 0;
  463. position_ = streamBuffer_->GetStart();
  464. fractPosition_ = 0;
  465. sendFinishedEvent_ = true;
  466. return;
  467. }
  468. // If stream pointer is null, stop playback
  469. StopLockless();
  470. }
  471. void SoundSource::StopLockless()
  472. {
  473. position_ = nullptr;
  474. timePosition_ = 0.0f;
  475. // Free the sound stream and decode buffer if a stream was playing
  476. soundStream_.Reset();
  477. streamBuffer_.Reset();
  478. }
  479. void SoundSource::SetPlayPositionLockless(signed char* pos)
  480. {
  481. // Setting position on a stream is not supported
  482. if (!sound_ || soundStream_)
  483. return;
  484. signed char* start = sound_->GetStart();
  485. signed char* end = sound_->GetEnd();
  486. if (pos < start)
  487. pos = start;
  488. if (sound_->IsSixteenBit() && (pos - start) & 1u)
  489. ++pos;
  490. if (pos > end)
  491. pos = end;
  492. position_ = pos;
  493. timePosition_ = ((float)(int)(size_t)(pos - sound_->GetStart())) / (sound_->GetSampleSize() * sound_->GetFrequency());
  494. }
  495. void SoundSource::MixMonoToMono(Sound* sound, int* dest, unsigned samples, int mixRate)
  496. {
  497. float totalGain = masterGain_ * attenuation_ * gain_;
  498. auto vol = RoundToInt(256.0f * totalGain);
  499. if (!vol)
  500. {
  501. MixZeroVolume(sound, samples, mixRate);
  502. return;
  503. }
  504. float add = frequency_ / (float)mixRate;
  505. auto intAdd = (int)add;
  506. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  507. int fractPos = fractPosition_;
  508. if (sound->IsSixteenBit())
  509. {
  510. auto* pos = (short*)position_;
  511. auto* end = (short*)sound->GetEnd();
  512. auto* repeat = (short*)sound->GetRepeat();
  513. if (sound->IsLooped())
  514. {
  515. while (samples--)
  516. {
  517. *dest = *dest + (*pos * vol) / 256;
  518. ++dest;
  519. INC_POS_LOOPED();
  520. }
  521. position_ = (signed char*)pos;
  522. }
  523. else
  524. {
  525. while (samples--)
  526. {
  527. *dest = *dest + (*pos * vol) / 256;
  528. ++dest;
  529. INC_POS_ONESHOT();
  530. }
  531. position_ = (signed char*)pos;
  532. }
  533. }
  534. else
  535. {
  536. auto* pos = (signed char*)position_;
  537. signed char* end = sound->GetEnd();
  538. signed char* repeat = sound->GetRepeat();
  539. if (sound->IsLooped())
  540. {
  541. while (samples--)
  542. {
  543. *dest = *dest + *pos * vol;
  544. ++dest;
  545. INC_POS_LOOPED();
  546. }
  547. position_ = pos;
  548. }
  549. else
  550. {
  551. while (samples--)
  552. {
  553. *dest = *dest + *pos * vol;
  554. ++dest;
  555. INC_POS_ONESHOT();
  556. }
  557. position_ = pos;
  558. }
  559. }
  560. fractPosition_ = fractPos;
  561. }
  562. void SoundSource::MixMonoToStereo(Sound* sound, int* dest, unsigned samples, int mixRate)
  563. {
  564. float totalGain = masterGain_ * attenuation_ * gain_;
  565. auto leftVol = (int)((-panning_ + 1.0f) * (256.0f * totalGain + 0.5f));
  566. auto rightVol = (int)((panning_ + 1.0f) * (256.0f * totalGain + 0.5f));
  567. if (!leftVol && !rightVol)
  568. {
  569. MixZeroVolume(sound, samples, mixRate);
  570. return;
  571. }
  572. float add = frequency_ / (float)mixRate;
  573. auto intAdd = (int)add;
  574. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  575. int fractPos = fractPosition_;
  576. if (sound->IsSixteenBit())
  577. {
  578. auto* pos = (short*)position_;
  579. auto* end = (short*)sound->GetEnd();
  580. auto* repeat = (short*)sound->GetRepeat();
  581. if (sound->IsLooped())
  582. {
  583. while (samples--)
  584. {
  585. *dest = *dest + (*pos * leftVol) / 256;
  586. ++dest;
  587. *dest = *dest + (*pos * rightVol) / 256;
  588. ++dest;
  589. INC_POS_LOOPED();
  590. }
  591. position_ = (signed char*)pos;
  592. }
  593. else
  594. {
  595. while (samples--)
  596. {
  597. *dest = *dest + (*pos * leftVol) / 256;
  598. ++dest;
  599. *dest = *dest + (*pos * rightVol) / 256;
  600. ++dest;
  601. INC_POS_ONESHOT();
  602. }
  603. position_ = (signed char*)pos;
  604. }
  605. }
  606. else
  607. {
  608. auto* pos = (signed char*)position_;
  609. signed char* end = sound->GetEnd();
  610. signed char* repeat = sound->GetRepeat();
  611. if (sound->IsLooped())
  612. {
  613. while (samples--)
  614. {
  615. *dest = *dest + *pos * leftVol;
  616. ++dest;
  617. *dest = *dest + *pos * rightVol;
  618. ++dest;
  619. INC_POS_LOOPED();
  620. }
  621. position_ = pos;
  622. }
  623. else
  624. {
  625. while (samples--)
  626. {
  627. *dest = *dest + *pos * leftVol;
  628. ++dest;
  629. *dest = *dest + *pos * rightVol;
  630. ++dest;
  631. INC_POS_ONESHOT();
  632. }
  633. position_ = pos;
  634. }
  635. }
  636. fractPosition_ = fractPos;
  637. }
  638. void SoundSource::MixMonoToMonoIP(Sound* sound, int* dest, unsigned samples, int mixRate)
  639. {
  640. float totalGain = masterGain_ * attenuation_ * gain_;
  641. auto vol = RoundToInt(256.0f * totalGain);
  642. if (!vol)
  643. {
  644. MixZeroVolume(sound, samples, mixRate);
  645. return;
  646. }
  647. float add = frequency_ / (float)mixRate;
  648. auto intAdd = (int)add;
  649. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  650. int fractPos = fractPosition_;
  651. if (sound->IsSixteenBit())
  652. {
  653. auto* pos = (short*)position_;
  654. auto* end = (short*)sound->GetEnd();
  655. auto* repeat = (short*)sound->GetRepeat();
  656. if (sound->IsLooped())
  657. {
  658. while (samples--)
  659. {
  660. *dest = *dest + (GET_IP_SAMPLE() * vol) / 256;
  661. ++dest;
  662. INC_POS_LOOPED();
  663. }
  664. position_ = (signed char*)pos;
  665. }
  666. else
  667. {
  668. while (samples--)
  669. {
  670. *dest = *dest + (GET_IP_SAMPLE() * vol) / 256;
  671. ++dest;
  672. INC_POS_ONESHOT();
  673. }
  674. position_ = (signed char*)pos;
  675. }
  676. }
  677. else
  678. {
  679. auto* pos = (signed char*)position_;
  680. signed char* end = sound->GetEnd();
  681. signed char* repeat = sound->GetRepeat();
  682. if (sound->IsLooped())
  683. {
  684. while (samples--)
  685. {
  686. *dest = *dest + GET_IP_SAMPLE() * vol;
  687. ++dest;
  688. INC_POS_LOOPED();
  689. }
  690. position_ = pos;
  691. }
  692. else
  693. {
  694. while (samples--)
  695. {
  696. *dest = *dest + GET_IP_SAMPLE() * vol;
  697. ++dest;
  698. INC_POS_ONESHOT();
  699. }
  700. position_ = pos;
  701. }
  702. }
  703. fractPosition_ = fractPos;
  704. }
  705. void SoundSource::MixMonoToStereoIP(Sound* sound, int* dest, unsigned samples, int mixRate)
  706. {
  707. float totalGain = masterGain_ * attenuation_ * gain_;
  708. auto leftVol = (int)((-panning_ + 1.0f) * (256.0f * totalGain + 0.5f));
  709. auto rightVol = (int)((panning_ + 1.0f) * (256.0f * totalGain + 0.5f));
  710. if (!leftVol && !rightVol)
  711. {
  712. MixZeroVolume(sound, samples, mixRate);
  713. return;
  714. }
  715. float add = frequency_ / (float)mixRate;
  716. auto intAdd = (int)add;
  717. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  718. int fractPos = fractPosition_;
  719. if (sound->IsSixteenBit())
  720. {
  721. auto* pos = (short*)position_;
  722. auto* end = (short*)sound->GetEnd();
  723. auto* repeat = (short*)sound->GetRepeat();
  724. if (sound->IsLooped())
  725. {
  726. while (samples--)
  727. {
  728. int s = GET_IP_SAMPLE();
  729. *dest = *dest + (s * leftVol) / 256;
  730. ++dest;
  731. *dest = *dest + (s * rightVol) / 256;
  732. ++dest;
  733. INC_POS_LOOPED();
  734. }
  735. position_ = (signed char*)pos;
  736. }
  737. else
  738. {
  739. while (samples--)
  740. {
  741. int s = GET_IP_SAMPLE();
  742. *dest = *dest + (s * leftVol) / 256;
  743. ++dest;
  744. *dest = *dest + (s * rightVol) / 256;
  745. ++dest;
  746. INC_POS_ONESHOT();
  747. }
  748. position_ = (signed char*)pos;
  749. }
  750. }
  751. else
  752. {
  753. auto* pos = (signed char*)position_;
  754. signed char* end = sound->GetEnd();
  755. signed char* repeat = sound->GetRepeat();
  756. if (sound->IsLooped())
  757. {
  758. while (samples--)
  759. {
  760. int s = GET_IP_SAMPLE();
  761. *dest = *dest + s * leftVol;
  762. ++dest;
  763. *dest = *dest + s * rightVol;
  764. ++dest;
  765. INC_POS_LOOPED();
  766. }
  767. position_ = pos;
  768. }
  769. else
  770. {
  771. while (samples--)
  772. {
  773. int s = GET_IP_SAMPLE();
  774. *dest = *dest + s * leftVol;
  775. ++dest;
  776. *dest = *dest + s * rightVol;
  777. ++dest;
  778. INC_POS_ONESHOT();
  779. }
  780. position_ = pos;
  781. }
  782. }
  783. fractPosition_ = fractPos;
  784. }
  785. void SoundSource::MixStereoToMono(Sound* sound, int* dest, unsigned samples, int mixRate)
  786. {
  787. float totalGain = masterGain_ * attenuation_ * gain_;
  788. auto vol = RoundToInt(256.0f * totalGain);
  789. if (!vol)
  790. {
  791. MixZeroVolume(sound, samples, mixRate);
  792. return;
  793. }
  794. float add = frequency_ / (float)mixRate;
  795. auto intAdd = (int)add;
  796. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  797. int fractPos = fractPosition_;
  798. if (sound->IsSixteenBit())
  799. {
  800. auto* pos = (short*)position_;
  801. auto* end = (short*)sound->GetEnd();
  802. auto* repeat = (short*)sound->GetRepeat();
  803. if (sound->IsLooped())
  804. {
  805. while (samples--)
  806. {
  807. int s = ((int)pos[0] + (int)pos[1]) / 2;
  808. *dest = *dest + (s * vol) / 256;
  809. ++dest;
  810. INC_POS_STEREO_LOOPED();
  811. }
  812. position_ = (signed char*)pos;
  813. }
  814. else
  815. {
  816. while (samples--)
  817. {
  818. int s = ((int)pos[0] + (int)pos[1]) / 2;
  819. *dest = *dest + (s * vol) / 256;
  820. ++dest;
  821. INC_POS_STEREO_ONESHOT();
  822. }
  823. position_ = (signed char*)pos;
  824. }
  825. }
  826. else
  827. {
  828. auto* pos = (signed char*)position_;
  829. signed char* end = sound->GetEnd();
  830. signed char* repeat = sound->GetRepeat();
  831. if (sound->IsLooped())
  832. {
  833. while (samples--)
  834. {
  835. int s = ((int)pos[0] + (int)pos[1]) / 2;
  836. *dest = *dest + s * vol;
  837. ++dest;
  838. INC_POS_STEREO_LOOPED();
  839. }
  840. position_ = pos;
  841. }
  842. else
  843. {
  844. while (samples--)
  845. {
  846. int s = ((int)pos[0] + (int)pos[1]) / 2;
  847. *dest = *dest + s * vol;
  848. ++dest;
  849. INC_POS_STEREO_ONESHOT();
  850. }
  851. position_ = pos;
  852. }
  853. }
  854. fractPosition_ = fractPos;
  855. }
  856. void SoundSource::MixStereoToStereo(Sound* sound, int* dest, unsigned samples, int mixRate)
  857. {
  858. float totalGain = masterGain_ * attenuation_ * gain_;
  859. auto vol = RoundToInt(256.0f * totalGain);
  860. if (!vol)
  861. {
  862. MixZeroVolume(sound, samples, mixRate);
  863. return;
  864. }
  865. float add = frequency_ / (float)mixRate;
  866. auto intAdd = (int)add;
  867. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  868. int fractPos = fractPosition_;
  869. if (sound->IsSixteenBit())
  870. {
  871. auto* pos = (short*)position_;
  872. auto* end = (short*)sound->GetEnd();
  873. auto* repeat = (short*)sound->GetRepeat();
  874. if (sound->IsLooped())
  875. {
  876. while (samples--)
  877. {
  878. *dest = *dest + (pos[0] * vol) / 256;
  879. ++dest;
  880. *dest = *dest + (pos[1] * vol) / 256;
  881. ++dest;
  882. INC_POS_STEREO_LOOPED();
  883. }
  884. position_ = (signed char*)pos;
  885. }
  886. else
  887. {
  888. while (samples--)
  889. {
  890. *dest = *dest + (pos[0] * vol) / 256;
  891. ++dest;
  892. *dest = *dest + (pos[1] * vol) / 256;
  893. ++dest;
  894. INC_POS_STEREO_ONESHOT();
  895. }
  896. position_ = (signed char*)pos;
  897. }
  898. }
  899. else
  900. {
  901. auto* pos = (signed char*)position_;
  902. signed char* end = sound->GetEnd();
  903. signed char* repeat = sound->GetRepeat();
  904. if (sound->IsLooped())
  905. {
  906. while (samples--)
  907. {
  908. *dest = *dest + pos[0] * vol;
  909. ++dest;
  910. *dest = *dest + pos[1] * vol;
  911. ++dest;
  912. INC_POS_STEREO_LOOPED();
  913. }
  914. position_ = pos;
  915. }
  916. else
  917. {
  918. while (samples--)
  919. {
  920. *dest = *dest + pos[0] * vol;
  921. ++dest;
  922. *dest = *dest + pos[1] * vol;
  923. ++dest;
  924. INC_POS_STEREO_ONESHOT();
  925. }
  926. position_ = pos;
  927. }
  928. }
  929. fractPosition_ = fractPos;
  930. }
  931. void SoundSource::MixStereoToMonoIP(Sound* sound, int* dest, unsigned samples, int mixRate)
  932. {
  933. float totalGain = masterGain_ * attenuation_ * gain_;
  934. auto vol = RoundToInt(256.0f * totalGain);
  935. if (!vol)
  936. {
  937. MixZeroVolume(sound, samples, mixRate);
  938. return;
  939. }
  940. float add = frequency_ / (float)mixRate;
  941. auto intAdd = (int)add;
  942. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  943. int fractPos = fractPosition_;
  944. if (sound->IsSixteenBit())
  945. {
  946. auto* pos = (short*)position_;
  947. auto* end = (short*)sound->GetEnd();
  948. auto* repeat = (short*)sound->GetRepeat();
  949. if (sound->IsLooped())
  950. {
  951. while (samples--)
  952. {
  953. int s = (GET_IP_SAMPLE_LEFT() + GET_IP_SAMPLE_RIGHT()) / 2;
  954. *dest = *dest + (s * vol) / 256;
  955. ++dest;
  956. INC_POS_STEREO_LOOPED();
  957. }
  958. position_ = (signed char*)pos;
  959. }
  960. else
  961. {
  962. while (samples--)
  963. {
  964. int s = (GET_IP_SAMPLE_LEFT() + GET_IP_SAMPLE_RIGHT()) / 2;
  965. *dest = *dest + (s * vol) / 256;
  966. ++dest;
  967. INC_POS_STEREO_ONESHOT();
  968. }
  969. position_ = (signed char*)pos;
  970. }
  971. }
  972. else
  973. {
  974. auto* pos = (signed char*)position_;
  975. signed char* end = sound->GetEnd();
  976. signed char* repeat = sound->GetRepeat();
  977. if (sound->IsLooped())
  978. {
  979. while (samples--)
  980. {
  981. int s = (GET_IP_SAMPLE_LEFT() + GET_IP_SAMPLE_RIGHT()) / 2;
  982. *dest = *dest + s * vol;
  983. ++dest;
  984. INC_POS_STEREO_LOOPED();
  985. }
  986. position_ = pos;
  987. }
  988. else
  989. {
  990. while (samples--)
  991. {
  992. int s = (GET_IP_SAMPLE_LEFT() + GET_IP_SAMPLE_RIGHT()) / 2;
  993. *dest = *dest + s * vol;
  994. ++dest;
  995. INC_POS_STEREO_ONESHOT();
  996. }
  997. position_ = pos;
  998. }
  999. }
  1000. fractPosition_ = fractPos;
  1001. }
  1002. void SoundSource::MixStereoToStereoIP(Sound* sound, int* dest, unsigned samples, int mixRate)
  1003. {
  1004. float totalGain = masterGain_ * attenuation_ * gain_;
  1005. auto vol = RoundToInt(256.0f * totalGain);
  1006. if (!vol)
  1007. {
  1008. MixZeroVolume(sound, samples, mixRate);
  1009. return;
  1010. }
  1011. float add = frequency_ / (float)mixRate;
  1012. auto intAdd = (int)add;
  1013. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  1014. int fractPos = fractPosition_;
  1015. if (sound->IsSixteenBit())
  1016. {
  1017. auto* pos = (short*)position_;
  1018. auto* end = (short*)sound->GetEnd();
  1019. auto* repeat = (short*)sound->GetRepeat();
  1020. if (sound->IsLooped())
  1021. {
  1022. while (samples--)
  1023. {
  1024. *dest = *dest + (GET_IP_SAMPLE_LEFT() * vol) / 256;
  1025. ++dest;
  1026. *dest = *dest + (GET_IP_SAMPLE_RIGHT() * vol) / 256;
  1027. ++dest;
  1028. INC_POS_STEREO_LOOPED();
  1029. }
  1030. position_ = (signed char*)pos;
  1031. }
  1032. else
  1033. {
  1034. while (samples--)
  1035. {
  1036. *dest = *dest + (GET_IP_SAMPLE_LEFT() * vol) / 256;
  1037. ++dest;
  1038. *dest = *dest + (GET_IP_SAMPLE_RIGHT() * vol) / 256;
  1039. ++dest;
  1040. INC_POS_STEREO_ONESHOT();
  1041. }
  1042. position_ = (signed char*)pos;
  1043. }
  1044. }
  1045. else
  1046. {
  1047. auto* pos = (signed char*)position_;
  1048. signed char* end = sound->GetEnd();
  1049. signed char* repeat = sound->GetRepeat();
  1050. if (sound->IsLooped())
  1051. {
  1052. while (samples--)
  1053. {
  1054. *dest = *dest + GET_IP_SAMPLE_LEFT() * vol;
  1055. ++dest;
  1056. *dest = *dest + GET_IP_SAMPLE_RIGHT() * vol;
  1057. ++dest;
  1058. INC_POS_STEREO_LOOPED();
  1059. }
  1060. position_ = pos;
  1061. }
  1062. else
  1063. {
  1064. while (samples--)
  1065. {
  1066. *dest = *dest + GET_IP_SAMPLE_LEFT() * vol;
  1067. ++dest;
  1068. *dest = *dest + GET_IP_SAMPLE_RIGHT() * vol;
  1069. ++dest;
  1070. INC_POS_STEREO_ONESHOT();
  1071. }
  1072. position_ = pos;
  1073. }
  1074. }
  1075. fractPosition_ = fractPos;
  1076. }
  1077. void SoundSource::MixZeroVolume(Sound* sound, unsigned samples, int mixRate)
  1078. {
  1079. float add = frequency_ * (float)samples / (float)mixRate;
  1080. auto intAdd = (int)add;
  1081. auto fractAdd = (int)((add - floorf(add)) * 65536.0f);
  1082. unsigned sampleSize = sound->GetSampleSize();
  1083. fractPosition_ += fractAdd;
  1084. if (fractPosition_ > 65535)
  1085. {
  1086. fractPosition_ &= 65535;
  1087. position_ += sampleSize;
  1088. }
  1089. position_ += intAdd * sampleSize;
  1090. if (position_ > sound->GetEnd())
  1091. {
  1092. if (sound->IsLooped())
  1093. {
  1094. while (position_ >= sound->GetEnd())
  1095. {
  1096. position_ -= (sound->GetEnd() - sound->GetRepeat());
  1097. }
  1098. }
  1099. else
  1100. position_ = nullptr;
  1101. }
  1102. }
  1103. void SoundSource::MixNull(float timeStep)
  1104. {
  1105. if (!position_ || !sound_ || !IsEnabledEffective())
  1106. return;
  1107. // Advance only the time position
  1108. timePosition_ += timeStep * frequency_ / sound_->GetFrequency();
  1109. if (sound_->IsLooped())
  1110. {
  1111. // For simulated playback, simply reset the time position to zero when the sound loops
  1112. if (timePosition_ >= sound_->GetLength())
  1113. timePosition_ -= sound_->GetLength();
  1114. }
  1115. else
  1116. {
  1117. if (timePosition_ >= sound_->GetLength())
  1118. {
  1119. position_ = nullptr;
  1120. timePosition_ = 0.0f;
  1121. }
  1122. }
  1123. }
  1124. }