1
0

GaplessRingBuffer.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "GaplessRingBuffer.h"
  2. #include <bfc/platform/types.h>
  3. #include <bfc/error.h>
  4. #include <algorithm>
  5. GaplessRingBuffer::GaplessRingBuffer()
  6. {
  7. pregapBytes = 0;
  8. frameBytes = 0;
  9. postgapBytes = 0;
  10. currentPregapBytes = 0;
  11. }
  12. GaplessRingBuffer::~GaplessRingBuffer()
  13. {
  14. }
  15. int GaplessRingBuffer::Initialize(size_t samples, size_t bps, size_t channels, size_t pregap, size_t postgap)
  16. {
  17. this->frameBytes = channels * bps / 8;
  18. this->currentPregapBytes = this->pregapBytes = pregap * frameBytes;
  19. this->postgapBytes = postgap * frameBytes;
  20. ring_buffer.reserve(samples * frameBytes + pregapBytes);
  21. return NErr_Success;
  22. }
  23. bool GaplessRingBuffer::Empty() const
  24. {
  25. return (ring_buffer.size() <= pregapBytes);
  26. }
  27. size_t GaplessRingBuffer::Read(void *destination, size_t destination_bytes)
  28. {
  29. // make sure we've filled enough of the buffer to satisfy the postgap
  30. if (Empty()) {
  31. return 0;
  32. }
  33. // don't read into postgap area
  34. size_t remaining = ring_buffer.size() - postgapBytes;
  35. destination_bytes = min(remaining, destination_bytes);
  36. return ring_buffer.read(destination, destination_bytes);
  37. }
  38. size_t GaplessRingBuffer::Write(const void *input, size_t input_bytes)
  39. {
  40. // cut pregap if necessary
  41. if (currentPregapBytes) {
  42. size_t cut = min(input_bytes, currentPregapBytes);
  43. currentPregapBytes -= cut;
  44. input_bytes -= cut;
  45. input = (const uint8_t *)input + cut;
  46. }
  47. return ring_buffer.write(input, input_bytes);
  48. }
  49. void GaplessRingBuffer::Reset()
  50. {
  51. currentPregapBytes = pregapBytes;
  52. ring_buffer.clear();
  53. }