h264fileparser.cpp 2.5 KB

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