generated from bep/golibtemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmetadecoder_iptc.go
417 lines (356 loc) · 8.8 KB
/
metadecoder_iptc.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Copyright 2024 Bjørn Erik Pedersen
// SPDX-License-Identifier: MIT
package imagemeta
import (
_ "embed" // needed for the embedded IPTC fields JSON
"encoding/binary"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/charmap"
)
// Source: https://exiftool.org/TagNames/IPTC.html
//
//go:embed metadecoder_iptc_fields.json
var ipctTagsJSON []byte
var (
iptcRecordFields = map[uint8]map[uint8]iptcField{}
iptcRerordNames = map[uint8]string{
1: "IPTCEnvelope",
2: "IPTCApplication",
3: "IPTCNewsPhoto",
7: "IPTCPreObjectData",
8: "IPTCObjectData",
9: "IPTCPostObjectData",
240: "IPTCFotoStation",
}
)
const (
ipcCodedCharacterSet = 90
iptcMetaDataBlockID = 0x0404
)
type vcIPTC struct {
//*vc
}
func (c *vcIPTC) convertDateString(ctx valueConverterContext, v any) any {
s := toString(v)
// 20211020 => 2021:10:20
if len(s) == 8 {
return fmt.Sprintf("%s:%s:%s", s[:4], s[4:6], s[6:])
}
// 2015-01-22 => 2015:01:22
if len(s) == 10 {
return fmt.Sprintf("%s:%s:%s", s[:4], s[5:7], s[8:])
}
return s
}
func (c *vcIPTC) convertTime(ctx valueConverterContext, v any) any {
s := toString(v)
// 111116 => 11:11:16
if len(s) == 6 {
return fmt.Sprintf("%s:%s:%s", s[:2], s[2:4], s[4:])
}
// 130444+1000 => 13:04:44+10:00
if len(s) == 11 {
return fmt.Sprintf("%s:%s:%s%s:%s", s[:2], s[2:4], s[4:6], s[6:9], s[9:])
}
return s
}
var (
iptcConverters = &vcIPTC{}
iptcValueConverterMap = map[string]valueConverter{
"DateCreated": iptcConverters.convertDateString,
"DateSent": iptcConverters.convertDateString,
"DigitalCreationDate": iptcConverters.convertDateString,
"DigitalCreationTime": iptcConverters.convertTime,
"TimeSent": iptcConverters.convertTime,
"TimeCreated": func(ctx valueConverterContext, v any) any {
s := toString(v)
if len(s) == 11 {
// 210101+0000 => 21:01:01+00:00
return fmt.Sprintf("%s:%s:%s%s:%s", s[:2], s[2:4], s[4:7], s[7:9], s[9:])
}
if len(s) == 6 {
// 124633 => 12:46:33
return fmt.Sprintf("%s:%s:%s", s[:2], s[2:4], s[4:])
}
return s
},
"ProgramVersion": func(ctx valueConverterContext, v any) any {
s := toString(v)
s = strings.TrimSuffix(s, ".0")
return s
},
"CodedCharacterSet": func(ctx valueConverterContext, v any) any {
b := v.([]byte)
s := resolveCodedCharacterSet(b)
if s == "" {
return characterSetUTF8
}
return s
},
}
)
func newMetaDecoderIPTC(r io.Reader, opts Options) *metaDecoderIPTC {
s := newStreamReader(r, binary.BigEndian)
return &metaDecoderIPTC{
streamReader: s,
iso88591CharsetDecoder: charmap.ISO8859_1.NewDecoder(),
valueConverterContext: valueConverterContext{
s: s,
warnfFunc: opts.Warnf,
},
opts: opts,
}
}
type iptcField struct {
Record uint8 `json:"record"`
RecordName string `json:"record_name"`
ID uint8 `json:"id"`
Name string `json:"name"`
Format string `json:"format"`
Repeatable bool `json:"repeatable"`
Notes string `json:"notes"`
}
type metaDecoderIPTC struct {
*streamReader
charset string
iso88591CharsetDecoder *encoding.Decoder
valueConverterContext valueConverterContext
opts Options
}
// Decode decodes the IPTC records delimited by 0x1C.
func (e *metaDecoderIPTC) decodeRecords() (err error) {
stringSlices := make(map[TagInfo][]string)
for {
var marker uint8
if err := binary.Read(e.r, e.byteOrder, &marker); err != nil {
if err == io.EOF {
break
}
return err
}
if marker != 0x1C {
break
}
if err := e.decodeRecord(stringSlices); err != nil {
return err
}
}
if err := e.handlestringSlices(stringSlices); err != nil {
return err
}
return nil
}
func (e *metaDecoderIPTC) handlestringSlices(m map[TagInfo][]string) error {
if len(m) == 0 {
return nil
}
for ti, values := range m {
if len(values) == 0 || len(values) > 1 {
ti.Value = values
} else {
ti.Value = values[0]
}
if err := e.opts.HandleTag(ti); err != nil {
return err
}
}
return nil
}
// decodeBlocks decodes the IPTC data from segments separated by 8BIM.
// This assumes a reader that starts out at 8BIM (no headers)
func (e *metaDecoderIPTC) decodeBlocks() (err error) {
stringSlices := make(map[TagInfo][]string)
decodeBlock := func() error {
blockType := e.readBytesVolatile(4)
if string(blockType) != "8BIM" {
return errStop
}
identifier := e.read2()
isNotMeta := identifier != iptcMetaDataBlockID
nameLength := e.read1()
if nameLength == 0 {
nameLength = 2
} else if nameLength%2 == 1 {
nameLength++
}
e.skip(int64(nameLength - 1))
dataSize := e.read4()
if isNotMeta {
e.skip(int64(dataSize))
return nil
}
if dataSize%2 != 0 {
defer func() {
// Skip padding byte.
e.skip(1)
}()
}
for {
marker := e.read1()
if e.isEOF || marker != 0x1C {
return errStop
}
if err := e.decodeRecord(stringSlices); err != nil {
return err
}
}
}
for {
if err := decodeBlock(); err != nil {
if err == errStop {
break
}
return err
}
}
if err := e.handlestringSlices(stringSlices); err != nil {
return err
}
return nil
}
func (e *metaDecoderIPTC) decodeRecord(stringSlices map[TagInfo][]string) error {
recordType := e.read1()
datasetNumber := e.read1()
recordSize := e.read2()
recordDef, ok := getIptcRecordFieldDef(recordType, datasetNumber)
if !ok {
// Assume a non repeatable string.
recordDef = iptcField{
Name: fmt.Sprintf("%s%d", UnknownPrefix, datasetNumber),
RecordName: "IPTCUnknownRecord",
Format: "string",
Repeatable: false,
}
}
ti := TagInfo{
Source: IPTC,
Tag: recordDef.Name,
Namespace: recordDef.RecordName,
}
if !e.opts.ShouldHandleTag(ti) {
e.skip(int64(recordSize))
return nil
}
var v any
switch recordDef.Format {
case "string":
v = e.readBytesVolatile(int(recordSize))
if e.charset == "" || e.charset == characterSetISO88591 {
v, _ = e.iso88591CharsetDecoder.Bytes(v.([]byte))
}
case "uint32":
v = e.read4()
case "short":
v = e.read2()
case "byte":
v = e.read1()
default:
panic(fmt.Errorf("unsupported format %q", recordDef.Format))
}
if convert, found := iptcValueConverterMap[recordDef.Name]; found {
e.valueConverterContext.tagName = recordDef.Name
v = convert(e.valueConverterContext, v)
}
if recordType == 1 && datasetNumber == ipcCodedCharacterSet {
e.charset = v.(string)
}
if b, ok := v.([]byte); ok {
v = strings.TrimSpace(string(trimBytesNulls(b)))
}
if recordDef.Repeatable {
stringSlices[ti] = append(stringSlices[ti], toString(v))
} else {
ti.Value = v
if err := e.opts.HandleTag(ti); err != nil {
return err
}
}
return nil
}
func getIptcRecordFieldDef(record, id uint8) (iptcField, bool) {
recordFields, ok := iptcRecordFields[record]
if !ok {
return iptcField{}, false
}
field, ok := recordFields[id]
return field, ok
}
func getIptcRecordName(record uint8) string {
name, ok := iptcRerordNames[record]
if !ok {
return fmt.Sprintf("IPTCUnknownRecord%d", record)
}
return name
}
func init() {
var fields []map[string]any
if err := json.Unmarshal(ipctTagsJSON, &fields); err != nil {
panic(err)
}
toUint8 := func(v any) uint8 {
s := v.(string)
i, err := strconv.Atoi(s)
if err != nil {
return 0
}
return uint8(i)
}
toString := func(v any) string {
if v == nil {
return ""
}
return v.(string)
}
for _, fieldv := range fields {
id := toUint8(fieldv["id"])
record := toUint8(fieldv["record"])
recordFields, ok := iptcRecordFields[record]
if !ok {
recordFields = map[uint8]iptcField{}
iptcRecordFields[record] = recordFields
}
recordFields[id] = iptcField{
Record: record,
RecordName: getIptcRecordName(record),
ID: id,
Name: toString(fieldv["name"]),
Format: toString(fieldv["format"]),
Notes: toString(fieldv["notes"]),
Repeatable: fieldv["repeatable"] == "true",
}
}
}
const (
characterSetUTF8 = "UTF-8"
characterSetISO88591 = "ISO-8859-1"
)
// resolveCodedCharacterSet resolves the coded character set from the IPTC data
// to be either UTF-8 or ISO-8859-1 or an empty string if it cannot be resolved.
func resolveCodedCharacterSet(b []byte) string {
const (
esc = 0x1B
percent = 0x25
latinCapitalG = 0x47
dot = 0x2E
latinCapitalA = 0x41
minus = 0x2D
)
if len(b) > 2 && b[0] == esc && b[1] == percent && b[2] == latinCapitalG {
return characterSetUTF8
}
if len(b) > 2 && b[0] == esc && b[1] == dot && b[2] == latinCapitalA {
return characterSetISO88591
}
if len(b) > 3 && b[0] == esc && (b[1] == dot || b[2] == dot || b[3] == dot) && b[4] == latinCapitalA {
return characterSetISO88591
}
if len(b) > 2 && b[0] == esc && b[1] == minus && b[2] == latinCapitalA {
return characterSetISO88591
}
return ""
}