mjpeg_validate.cc 2.25 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/*
 *  Copyright 2012 The LibYuv Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS. All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "libyuv/mjpeg_decoder.h"

13 14
#include <string.h>  // For memchr.

15
#ifdef __cplusplus
16
namespace libyuv {
17 18
extern "C" {
#endif
19

20
// Helper function to scan for EOI marker (0xff 0xd9).
21 22 23 24
static LIBYUV_BOOL ScanEOI(const uint8_t* src_mjpg, size_t src_size_mjpg) {
  if (src_size_mjpg >= 2) {
    const uint8_t* end = src_mjpg + src_size_mjpg - 1;
    const uint8_t* it = src_mjpg;
25 26
    while (it < end) {
      // TODO(fbarchard): scan for 0xd9 instead.
Frank Barchard's avatar
Frank Barchard committed
27
      it = (const uint8_t*)(memchr(it, 0xff, end - it));
28 29 30 31 32 33 34
      if (it == NULL) {
        break;
      }
      if (it[1] == 0xd9) {
        return LIBYUV_TRUE;  // Success: Valid jpeg.
      }
      ++it;  // Skip over current 0xff.
35 36
    }
  }
37
  // ERROR: Invalid jpeg end code not found. Size src_size_mjpg
38 39 40
  return LIBYUV_FALSE;
}

41
// Helper function to validate the jpeg appears intact.
42
LIBYUV_BOOL ValidateJpeg(const uint8_t* src_mjpg, size_t src_size_mjpg) {
43 44
  // Maximum size that ValidateJpeg will consider valid.
  const size_t kMaxJpegSize = 0x7fffffffull;
45
  const size_t kBackSearchSize = 1024;
46 47
  if (src_size_mjpg < 64 || src_size_mjpg > kMaxJpegSize || !src_mjpg) {
    // ERROR: Invalid jpeg size: src_size_mjpg
48
    return LIBYUV_FALSE;
49
  }
50 51
  // SOI marker
  if (src_mjpg[0] != 0xff || src_mjpg[1] != 0xd8 || src_mjpg[2] != 0xff) {
52
    // ERROR: Invalid jpeg initial start code
53
    return LIBYUV_FALSE;
54
  }
55 56

  // Look for the End Of Image (EOI) marker near the end of the buffer.
57 58
  if (src_size_mjpg > kBackSearchSize) {
    if (ScanEOI(src_mjpg + src_size_mjpg - kBackSearchSize, kBackSearchSize)) {
59 60 61
      return LIBYUV_TRUE;  // Success: Valid jpeg.
    }
    // Reduce search size for forward search.
62
    src_size_mjpg = src_size_mjpg - kBackSearchSize + 1;
63
  }
64
  // Step over SOI marker and scan for EOI.
65
  return ScanEOI(src_mjpg + 2, src_size_mjpg - 2);
66 67
}

68 69
#ifdef __cplusplus
}  // extern "C"
70
}  // namespace libyuv
71
#endif