2
0

mjpeg_validate.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright 2012 The LibYuv Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "libyuv/mjpeg_decoder.h"
  11. #include <string.h> // For memchr.
  12. #ifdef __cplusplus
  13. namespace libyuv {
  14. extern "C" {
  15. #endif
  16. // Helper function to scan for EOI marker (0xff 0xd9).
  17. static LIBYUV_BOOL ScanEOI(const uint8_t* src_mjpg, size_t src_size_mjpg) {
  18. if (src_size_mjpg >= 2) {
  19. const uint8_t* end = src_mjpg + src_size_mjpg - 1;
  20. const uint8_t* it = src_mjpg;
  21. while (it < end) {
  22. // TODO(fbarchard): scan for 0xd9 instead.
  23. it = (const uint8_t*)(memchr(it, 0xff, end - it));
  24. if (it == NULL) {
  25. break;
  26. }
  27. if (it[1] == 0xd9) {
  28. return LIBYUV_TRUE; // Success: Valid jpeg.
  29. }
  30. ++it; // Skip over current 0xff.
  31. }
  32. }
  33. // ERROR: Invalid jpeg end code not found. Size src_size_mjpg
  34. return LIBYUV_FALSE;
  35. }
  36. // Helper function to validate the jpeg appears intact.
  37. LIBYUV_BOOL ValidateJpeg(const uint8_t* src_mjpg, size_t src_size_mjpg) {
  38. // Maximum size that ValidateJpeg will consider valid.
  39. const size_t kMaxJpegSize = 0x7fffffffull;
  40. const size_t kBackSearchSize = 1024;
  41. if (src_size_mjpg < 64 || src_size_mjpg > kMaxJpegSize || !src_mjpg) {
  42. // ERROR: Invalid jpeg size: src_size_mjpg
  43. return LIBYUV_FALSE;
  44. }
  45. // SOI marker
  46. if (src_mjpg[0] != 0xff || src_mjpg[1] != 0xd8 || src_mjpg[2] != 0xff) {
  47. // ERROR: Invalid jpeg initial start code
  48. return LIBYUV_FALSE;
  49. }
  50. // Look for the End Of Image (EOI) marker near the end of the buffer.
  51. if (src_size_mjpg > kBackSearchSize) {
  52. if (ScanEOI(src_mjpg + src_size_mjpg - kBackSearchSize, kBackSearchSize)) {
  53. return LIBYUV_TRUE; // Success: Valid jpeg.
  54. }
  55. // Reduce search size for forward search.
  56. src_size_mjpg = src_size_mjpg - kBackSearchSize + 1;
  57. }
  58. // Step over SOI marker and scan for EOI.
  59. return ScanEOI(src_mjpg + 2, src_size_mjpg - 2);
  60. }
  61. #ifdef __cplusplus
  62. } // extern "C"
  63. } // namespace libyuv
  64. #endif