2
0

MP3Container.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include "MP3Container.h"
  2. #include <cstring> // for memmove
  3. #include "StreamInfo.h" // for BitWidth, BitWidth::BW_16, SampleRate, Sampl...
  4. #include "mp3dec.h" // for MP3FindSyncWord
  5. using namespace bell;
  6. MP3Container::MP3Container(std::istream& istr) : bell::AudioContainer(istr) {}
  7. bool MP3Container::fillBuffer() {
  8. if (this->bytesInBuffer < MP3_MAX_FRAME_SIZE * 2) {
  9. this->istr.read((char*)buffer.data() + bytesInBuffer,
  10. buffer.size() - bytesInBuffer);
  11. this->bytesInBuffer += istr.gcount();
  12. }
  13. return this->bytesInBuffer >= MP3_MAX_FRAME_SIZE * 2;
  14. }
  15. std::byte* MP3Container::readSample(uint32_t& len) {
  16. if (!this->fillBuffer()) {
  17. len = 0;
  18. return nullptr;
  19. }
  20. // Align the data if previous read was offseted
  21. if (toConsume > 0 && toConsume <= bytesInBuffer) {
  22. memmove(buffer.data(), buffer.data() + toConsume,
  23. buffer.size() - toConsume);
  24. bytesInBuffer = bytesInBuffer - toConsume;
  25. toConsume = 0;
  26. }
  27. int startOffset =
  28. MP3FindSyncWord((uint8_t*)this->buffer.data(), bytesInBuffer);
  29. if (startOffset < 0) {
  30. // Discard word
  31. toConsume = MP3_MAX_FRAME_SIZE;
  32. return nullptr;
  33. }
  34. len = bytesInBuffer - startOffset;
  35. return this->buffer.data() + startOffset;
  36. }
  37. void MP3Container::parseSetupData() {
  38. channels = 2;
  39. sampleRate = bell::SampleRate::SR_44100;
  40. bitWidth = bell::BitWidth::BW_16;
  41. }