1#include "dng_jpeg_memory_source.h"
2
3#if qDNGUseLibJPEG
4
5#include "dng_safe_arithmetic.h"
6
7namespace {
8
9void InitSource(j_decompress_ptr cinfo) {
10  // No initialization necessary.
11}
12
13boolean FillInputBuffer(j_decompress_ptr cinfo) {
14  // We already filled the buffer with all of the data when the source was
15  // initialized, so we can't get any more data.
16  ERREXIT(cinfo, JERR_INPUT_EOF);
17  return FALSE;
18}
19
20void SkipInputData(j_decompress_ptr cinfo, long num_bytes) {
21  if (num_bytes > 0) {
22    // Convert num_bytes to a size_t.
23    // We've established that num_bytes is positive, to it's safe to cast it
24    // to an unsigned long.
25    size_t num_bytes_as_size_t = 0;
26    try {
27      ConvertUnsigned(static_cast<unsigned long>(num_bytes),
28                      &num_bytes_as_size_t);
29    } catch (const dng_exception &e) {
30      ERREXIT(cinfo, JERR_INPUT_EOF);
31      return;
32    }
33
34    jpeg_source_mgr *source_manager =
35        reinterpret_cast<jpeg_source_mgr *>(cinfo->src);
36
37    // Advance the current position by the given number of bytes.
38    if (num_bytes_as_size_t <= source_manager->bytes_in_buffer) {
39      source_manager->bytes_in_buffer -= num_bytes_as_size_t;
40      source_manager->next_input_byte += num_bytes_as_size_t;
41    } else {
42      // Tried to read beyond the end of the buffer.
43      ERREXIT(cinfo, JERR_INPUT_EOF);
44      return;
45    }
46  }
47}
48
49boolean ResyncToRestart(j_decompress_ptr cinfo, int desired) {
50  // Can't resync.
51  return FALSE;
52}
53
54void TermSource(j_decompress_ptr cinfo) {
55  // No termination necessary.
56}
57
58}  // namespace
59
60jpeg_source_mgr CreateJpegMemorySource(const uint8 *buffer, size_t size) {
61  jpeg_source_mgr source;
62
63  source.next_input_byte = reinterpret_cast<const JOCTET *>(buffer);
64  source.bytes_in_buffer = size;
65
66  // Initialize function pointers.
67  source.init_source = InitSource;
68  source.fill_input_buffer = FillInputBuffer;
69  source.skip_input_data = SkipInputData;
70  source.resync_to_restart = ResyncToRestart;
71  source.term_source = TermSource;
72
73  return source;
74}
75
76#endif  // qDNGUseLibJPEG
77