BufferedSoundStream.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Audio/BufferedSoundStream.h"
  5. #include "../DebugNew.h"
  6. namespace Urho3D
  7. {
  8. BufferedSoundStream::BufferedSoundStream() :
  9. position_(0)
  10. {
  11. }
  12. BufferedSoundStream::~BufferedSoundStream() = default;
  13. unsigned BufferedSoundStream::GetData(signed char* dest, unsigned numBytes)
  14. {
  15. MutexLock lock(bufferMutex_);
  16. unsigned outBytes = 0;
  17. while (numBytes && buffers_.Size())
  18. {
  19. // Copy as much from the front buffer as possible, then discard it and move to the next
  20. List<Pair<SharedArrayPtr<signed char>, unsigned>>::Iterator front = buffers_.Begin();
  21. unsigned copySize = front->second_ - position_;
  22. if (copySize > numBytes)
  23. copySize = numBytes;
  24. memcpy(dest, front->first_.Get() + position_, copySize);
  25. position_ += copySize;
  26. if (position_ >= front->second_)
  27. {
  28. buffers_.PopFront();
  29. position_ = 0;
  30. }
  31. dest += copySize;
  32. outBytes += copySize;
  33. numBytes -= copySize;
  34. }
  35. return outBytes;
  36. }
  37. void BufferedSoundStream::AddData(void* data, unsigned numBytes)
  38. {
  39. if (data && numBytes)
  40. {
  41. MutexLock lock(bufferMutex_);
  42. SharedArrayPtr<signed char> newBuffer(new signed char[numBytes]);
  43. memcpy(newBuffer.Get(), data, numBytes);
  44. buffers_.Push(MakePair(newBuffer, numBytes));
  45. }
  46. }
  47. void BufferedSoundStream::AddData(const SharedArrayPtr<signed char>& data, unsigned numBytes)
  48. {
  49. if (data && numBytes)
  50. {
  51. MutexLock lock(bufferMutex_);
  52. buffers_.Push(MakePair(data, numBytes));
  53. }
  54. }
  55. void BufferedSoundStream::AddData(const SharedArrayPtr<signed short>& data, unsigned numBytes)
  56. {
  57. if (data && numBytes)
  58. {
  59. MutexLock lock(bufferMutex_);
  60. buffers_.Push(MakePair(ReinterpretCast<signed char>(data), numBytes));
  61. }
  62. }
  63. void BufferedSoundStream::Clear()
  64. {
  65. MutexLock lock(bufferMutex_);
  66. buffers_.Clear();
  67. position_ = 0;
  68. }
  69. unsigned BufferedSoundStream::GetBufferNumBytes() const
  70. {
  71. MutexLock lock(bufferMutex_);
  72. unsigned ret = 0;
  73. for (List<Pair<SharedArrayPtr<signed char>, unsigned>>::ConstIterator i = buffers_.Begin(); i != buffers_.End(); ++i)
  74. ret += i->second_;
  75. // Subtract amount of sound data played from the front buffer
  76. ret -= position_;
  77. return ret;
  78. }
  79. float BufferedSoundStream::GetBufferLength() const
  80. {
  81. return (float)GetBufferNumBytes() / (GetFrequency() * (float)GetSampleSize());
  82. }
  83. }