h264fileparser.cpp 2.5 KB

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