fileparser.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * libdatachannel streamer example
  3. * Copyright (c) 2020 Filip Klembara (in2core)
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License
  7. * as published by the Free Software Foundation; either version 2
  8. * of the License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "fileparser.hpp"
  19. #include <fstream>
  20. using namespace std;
  21. FileParser::FileParser(string directory, string extension, uint32_t samplesPerSecond, bool loop): sampleDuration_us(1000 * 1000 / samplesPerSecond), StreamSource() {
  22. this->directory = directory;
  23. this->extension = extension;
  24. this->loop = loop;
  25. }
  26. void FileParser::start() {
  27. sampleTime_us = -sampleDuration_us;
  28. loadNextSample();
  29. }
  30. void FileParser::stop() {
  31. StreamSource::stop();
  32. counter = -1;
  33. }
  34. void FileParser::loadNextSample() {
  35. string frame_id = to_string(++counter);
  36. string url = directory + "/sample-" + frame_id + extension;
  37. ifstream source(url, ios_base::binary);
  38. if (!source) {
  39. if (loop && counter > 0) {
  40. loopTimestampOffset = sampleTime_us;
  41. counter = -1;
  42. loadNextSample();
  43. return;
  44. }
  45. sample = {};
  46. return;
  47. }
  48. vector<uint8_t> fileContents((std::istreambuf_iterator<char>(source)), std::istreambuf_iterator<char>());
  49. sample = *reinterpret_cast<vector<byte> *>(&fileContents);
  50. sampleTime_us += sampleDuration_us;
  51. }