-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
98 lines (80 loc) · 2.08 KB
/
decoder.go
File metadata and controls
98 lines (80 loc) · 2.08 KB
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
package xmp
import (
"encoding/binary"
"encoding/xml"
"io/ioutil"
"net/http"
"strconv"
)
func Read(path string) (*Profile, error) {
var p *Profile
xmp := Xmpmeta{}
b, err := ioutil.ReadFile(path)
if err == nil {
err = decode(b, &xmp)
p = &xmp.RDF.Description.Profile
return p, err
}
resp, err := http.Get(path)
if err != nil {
return p, err
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err == nil {
err = decode(b, &xmp)
p = &xmp.RDF.Description.Profile
return p, err
}
return p, err
}
// Refer to https://developers.google.com/speed/webp/docs/riff_container
func decode(b []byte, v *Xmpmeta) error {
chunkOffset := 0
chunkID := string(b[chunkOffset : chunkOffset+4])
if chunkID != "RIFF" {
return InvalidRIFF
}
if string(b[chunkOffset+8:chunkOffset+12]) != "WEBP" {
return InvalidWEBP
}
containerSize := 12
chunkOffset = chunkOffset + containerSize
chunkID = string(b[chunkOffset : chunkOffset+4])
if chunkID != "VP8X" {
return VP8XNotFound
}
containerSize = int(binary.LittleEndian.Uint32(b[chunkOffset+4:chunkOffset+8])) + 8
metadata := b[chunkOffset+8]
xmpFlag := metadata & 0x4
if xmpFlag != 4 {
return XMPNotFound
}
chunkOffset = chunkOffset + containerSize
chunkID = string(b[chunkOffset : chunkOffset+4])
containerSize = int(binary.LittleEndian.Uint32(b[chunkOffset+4:chunkOffset+8])) + 8
for chunkOffset < len(b) && chunkID != "XMP " {
chunkOffset = chunkOffset + containerSize
chunkID = string(b[chunkOffset : chunkOffset+4])
containerSize = int(binary.LittleEndian.Uint32(b[chunkOffset+4:chunkOffset+8])) + 8
}
if chunkID != "XMP " {
return XMPNotFound
}
content := b[chunkOffset+8 : chunkOffset+containerSize+8]
err := xml.Unmarshal(content, v)
if err != nil {
return err
}
escapedName, err := strconv.Unquote(v.RDF.Description.Profile.Name)
if err != nil {
return err
}
v.RDF.Description.Profile.Name = escapedName
escapedLocation, err := strconv.Unquote(v.RDF.Description.Profile.Location)
if err != nil {
return err
}
v.RDF.Description.Profile.Location = escapedLocation
return err
}