1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
// Copyright (c) the JPEG XL 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.
#include "lib/jxl/exif.h"
namespace jxl {
constexpr uint16_t kExifOrientationTag = 274;
// Checks if a blob looks like Exif, and if so, sets bigendian
// according to the tiff endianness
bool IsExif(const std::vector<uint8_t>& exif, bool* bigendian) {
if (exif.size() < 12) return false; // not enough bytes for a valid exif blob
const uint8_t* t = exif.data();
if (LoadLE32(t) == 0x2A004D4D) {
*bigendian = true;
return true;
} else if (LoadLE32(t) == 0x002A4949) {
*bigendian = false;
return true;
}
return false; // not a valid tiff header
}
// Finds the position of an Exif tag, or 0 if it is not found
size_t FindExifTagPosition(const std::vector<uint8_t>& exif, uint16_t tagname) {
bool bigendian;
if (!IsExif(exif, &bigendian)) return 0;
const uint8_t* t = exif.data() + 4;
uint32_t offset = (bigendian ? LoadBE32(t) : LoadLE32(t));
if (exif.size() < 12 + offset + 2 || offset < 8) return 0;
t += offset - 4;
uint16_t nb_tags = (bigendian ? LoadBE16(t) : LoadLE16(t));
t += 2;
while (nb_tags > 0) {
if (t + 12 >= exif.data() + exif.size()) return 0;
uint16_t tag = (bigendian ? LoadBE16(t) : LoadLE16(t));
t += 2;
if (tag == tagname) return static_cast<size_t>(t - exif.data());
t += 10;
nb_tags--;
}
return 0;
}
// TODO (jon): tag 1 can be used to represent Adobe RGB 1998 if it has value
// "R03"
// TODO (jon): set intrinsic dimensions according to
// https://discourse.wicg.io/t/proposal-exif-image-resolution-auto-and-from-image/4326/24
void InterpretExif(const std::vector<uint8_t>& exif, CodecMetadata* metadata) {
bool bigendian;
if (!IsExif(exif, &bigendian)) return;
size_t o_pos = FindExifTagPosition(exif, kExifOrientationTag);
if (o_pos) {
const uint8_t* t = exif.data() + o_pos;
uint16_t type = (bigendian ? LoadBE16(t) : LoadLE16(t));
t += 2;
uint32_t count = (bigendian ? LoadBE32(t) : LoadLE32(t));
t += 4;
uint16_t value = (bigendian ? LoadBE16(t) : LoadLE16(t));
t += 4;
if (type == 3 && count == 1 && value >= 1 && value <= 8) {
metadata->m.orientation = value;
}
}
}
void ResetExifOrientation(std::vector<uint8_t>& exif) {
bool bigendian;
if (!IsExif(exif, &bigendian)) return;
size_t o_pos = FindExifTagPosition(exif, kExifOrientationTag);
if (o_pos) {
uint8_t* t = exif.data() + o_pos;
uint16_t type = (bigendian ? LoadBE16(t) : LoadLE16(t));
t += 2;
uint32_t count = (bigendian ? LoadBE32(t) : LoadLE32(t));
t += 4;
if (type == 3 && count == 1) {
if (bigendian)
StoreBE16(1, t);
else
StoreLE16(1, t);
}
}
}
} // namespace jxl
|