h264fileparser.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. #include <cstring>
  13. #ifdef _WIN32
  14. #include <winsock2.h>
  15. #else
  16. #include <arpa/inet.h>
  17. #endif
  18. using namespace std;
  19. H264FileParser::H264FileParser(string directory, uint32_t fps, bool loop): FileParser(directory, ".h264", fps, loop) { }
  20. void H264FileParser::loadNextSample() {
  21. FileParser::loadNextSample();
  22. size_t i = 0;
  23. while (i < sample.size()) {
  24. assert(i + 4 < sample.size());
  25. auto lengthPtr = (uint32_t *) (sample.data() + i);
  26. uint32_t length;
  27. std::memcpy(&length, lengthPtr, sizeof(uint32_t));
  28. length = ntohl(length);
  29. auto naluStartIndex = i + 4;
  30. auto naluEndIndex = naluStartIndex + length;
  31. assert(naluEndIndex <= sample.size());
  32. auto header = reinterpret_cast<rtc::NalUnitHeader *>(sample.data() + naluStartIndex);
  33. auto type = header->unitType();
  34. switch (type) {
  35. case 7:
  36. previousUnitType7 = {sample.begin() + i, sample.begin() + naluEndIndex};
  37. break;
  38. case 8:
  39. previousUnitType8 = {sample.begin() + i, sample.begin() + naluEndIndex};;
  40. break;
  41. case 5:
  42. previousUnitType5 = {sample.begin() + i, sample.begin() + naluEndIndex};;
  43. break;
  44. }
  45. i = naluEndIndex;
  46. }
  47. }
  48. vector<std::byte> H264FileParser::initialNALUS() {
  49. vector<std::byte> units{};
  50. if (previousUnitType7.has_value()) {
  51. auto nalu = previousUnitType7.value();
  52. units.insert(units.end(), nalu.begin(), nalu.end());
  53. }
  54. if (previousUnitType8.has_value()) {
  55. auto nalu = previousUnitType8.value();
  56. units.insert(units.end(), nalu.begin(), nalu.end());
  57. }
  58. if (previousUnitType5.has_value()) {
  59. auto nalu = previousUnitType5.value();
  60. units.insert(units.end(), nalu.begin(), nalu.end());
  61. }
  62. return units;
  63. }