obs-nal.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <lain@obsproject.com>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "obs-nal.h"
  15. /* NOTE: I noticed that FFmpeg does some unusual special handling of certain
  16. * scenarios that I was unaware of, so instead of just searching for {0, 0, 1}
  17. * we'll just use the code from FFmpeg - http://www.ffmpeg.org/ */
  18. static const uint8_t *ff_avc_find_startcode_internal(const uint8_t *p, const uint8_t *end)
  19. {
  20. const uint8_t *a = p + 4 - ((intptr_t)p & 3);
  21. for (end -= 3; p < a && p < end; p++) {
  22. if (p[0] == 0 && p[1] == 0 && p[2] == 1)
  23. return p;
  24. }
  25. for (end -= 3; p < end; p += 4) {
  26. uint32_t x = *(const uint32_t *)p;
  27. if ((x - 0x01010101) & (~x) & 0x80808080) {
  28. if (p[1] == 0) {
  29. if (p[0] == 0 && p[2] == 1)
  30. return p;
  31. if (p[2] == 0 && p[3] == 1)
  32. return p + 1;
  33. }
  34. if (p[3] == 0) {
  35. if (p[2] == 0 && p[4] == 1)
  36. return p + 2;
  37. if (p[4] == 0 && p[5] == 1)
  38. return p + 3;
  39. }
  40. }
  41. }
  42. for (end += 3; p < end; p++) {
  43. if (p[0] == 0 && p[1] == 0 && p[2] == 1)
  44. return p;
  45. }
  46. return end + 3;
  47. }
  48. const uint8_t *obs_nal_find_startcode(const uint8_t *p, const uint8_t *end)
  49. {
  50. const uint8_t *out = ff_avc_find_startcode_internal(p, end);
  51. if (p < out && out < end && !out[-1])
  52. out--;
  53. return out;
  54. }