mjpeg_validate.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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* sample, size_t sample_size) {
  18. if (sample_size >= 2) {
  19. const uint8* end = sample + sample_size - 1;
  20. const uint8* it = sample;
  21. while (it < end) {
  22. // TODO(fbarchard): scan for 0xd9 instead.
  23. it = static_cast<const uint8 *>(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 sample_size
  34. return LIBYUV_FALSE;
  35. }
  36. // Helper function to validate the jpeg appears intact.
  37. LIBYUV_BOOL ValidateJpeg(const uint8* sample, size_t sample_size) {
  38. // Maximum size that ValidateJpeg will consider valid.
  39. const size_t kMaxJpegSize = 0x7fffffffull;
  40. const size_t kBackSearchSize = 1024;
  41. if (sample_size < 64 || sample_size > kMaxJpegSize || !sample) {
  42. // ERROR: Invalid jpeg size: sample_size
  43. return LIBYUV_FALSE;
  44. }
  45. if (sample[0] != 0xff || sample[1] != 0xd8) { // SOI marker
  46. // ERROR: Invalid jpeg initial start code
  47. return LIBYUV_FALSE;
  48. }
  49. // Look for the End Of Image (EOI) marker near the end of the buffer.
  50. if (sample_size > kBackSearchSize) {
  51. if (ScanEOI(sample + sample_size - kBackSearchSize, kBackSearchSize)) {
  52. return LIBYUV_TRUE; // Success: Valid jpeg.
  53. }
  54. // Reduce search size for forward search.
  55. sample_size = sample_size - kBackSearchSize + 1;
  56. }
  57. // Step over SOI marker and scan for EOI.
  58. return ScanEOI(sample + 2, sample_size - 2);
  59. }
  60. #ifdef __cplusplus
  61. } // extern "C"
  62. } // namespace libyuv
  63. #endif