h264fileparser.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * libdatachannel streamer example
  3. * Copyright (c) 2020 Filip Klembara (in2core)
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  8. */
  9. #include "h264fileparser.hpp"
  10. #include "rtc/rtc.hpp"
  11. #include <fstream>
  12. #ifdef _WIN32
  13. #include <winsock2.h>
  14. #else
  15. #include <arpa/inet.h>
  16. #endif
  17. using namespace std;
  18. H264FileParser::H264FileParser(string directory, uint32_t fps, bool loop): FileParser(directory, ".h264", fps, loop) { }
  19. void H264FileParser::loadNextSample() {
  20. FileParser::loadNextSample();
  21. size_t i = 0;
  22. while (i < sample.size()) {
  23. assert(i + 4 < sample.size());
  24. auto lengthPtr = (uint32_t *) (sample.data() + i);
  25. uint32_t length = ntohl(*lengthPtr);
  26. auto naluStartIndex = i + 4;
  27. auto naluEndIndex = naluStartIndex + length;
  28. assert(naluEndIndex <= sample.size());
  29. auto header = reinterpret_cast<rtc::NalUnitHeader *>(sample.data() + naluStartIndex);
  30. auto type = header->unitType();
  31. switch (type) {
  32. case 7:
  33. previousUnitType7 = {sample.begin() + i, sample.begin() + naluEndIndex};
  34. break;
  35. case 8:
  36. previousUnitType8 = {sample.begin() + i, sample.begin() + naluEndIndex};;
  37. break;
  38. case 5:
  39. previousUnitType5 = {sample.begin() + i, sample.begin() + naluEndIndex};;
  40. break;
  41. }
  42. i = naluEndIndex;
  43. }
  44. }
  45. vector<std::byte> H264FileParser::initialNALUS() {
  46. vector<std::byte> units{};
  47. if (previousUnitType7.has_value()) {
  48. auto nalu = previousUnitType7.value();
  49. units.insert(units.end(), nalu.begin(), nalu.end());
  50. }
  51. if (previousUnitType8.has_value()) {
  52. auto nalu = previousUnitType8.value();
  53. units.insert(units.end(), nalu.begin(), nalu.end());
  54. }
  55. if (previousUnitType5.has_value()) {
  56. auto nalu = previousUnitType5.value();
  57. units.insert(units.end(), nalu.begin(), nalu.end());
  58. }
  59. return units;
  60. }