Compare commits

1 Commits
Author SHA1 Message Date
sm ab9d45e3ea added mov command to test out mov metadata parsing 2016-12-10 16:42:45 -08:00
30 changed files with 1809 additions and 1369 deletions
-46
View File
@@ -1,46 +0,0 @@
# arrange
de-duplicate and arrange photos and movies into a content-addressed store,
with hardlinks by date.
out/content/ab/cdef….jpg one copy of each file, named by its sha256
out/date/2006/03/1143508767….jpg hardlinks to those, by capture time
Capture time comes from exif (jpeg, heic, camera raw), the QuickTime movie
header (mov, mp4, m4v, 3gp), or the file's mtime as a last resort.
## usage
go install mcquay.me/arrange/cmd/am@latest
# where's the media? per folder: images, raw, videos, videos over 1G
# (ripped movies stand out), sizes. Only stats files. Prints folder names.
am survey ~/Pictures
am survey -depth=2 ~/Pictures
# pick what to grab: -kinds is any of image,raw,video (default all), and
# -exclude skips matching file or folder names (repeatable)
am arr -n -kinds=image ~/Pictures /mnt/store
am arr -n -exclude=VIDEO_TS -exclude='*.vob' -exclude=DVDs ~/Pictures /mnt/store
# see what would happen; prints new/dup<TAB>src<TAB>content<TAB>date dir
am arr -n ~/Pictures /mnt/store > plan.tsv
# do it; nothing in the source is changed
am arr ~/Pictures /mnt/store
# re-hash the store: corrupt files, orphans, leftovers from crashed runs
am verify /mnt/store
# turn dated files that are copies rather than hardlinks back into links
am clean -n /mnt/store
am clean /mnt/store
# print the time and path am would use for some files
am meta a.jpg b.mov
`arr` ends with a summary of counts and sizes by extension and year. It
names no files, so it is safe to share.
Stores made before sha256 use md5 names; add to one with `-hash=md5`.
`verify` works out the hash from each name's length.
+81 -199
View File
@@ -2,14 +2,11 @@ package arrange
import ( import (
"crypto/md5" "crypto/md5"
"crypto/sha256"
"fmt" "fmt"
"hash"
"image/gif" "image/gif"
"image/jpeg" "image/jpeg"
"image/png" "image/png"
"io" "io"
"io/fs"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@@ -18,92 +15,22 @@ import (
"time" "time"
) )
// kind is how a file extension gets parsed. var exts map[string]bool
type kind int
const ( func init() {
kindJPEG kind = iota exts = map[string]bool{
kindPNG
kindGIF
kindStill // HEIC, TIFF, etc.: dated by exif, no decode check
kindRaw // camera RAW: like kindStill, but its own Class
kindQuickTime // mov/mp4 family: dated by the mvhd atom
kindVideo // everything else: dated by mtime
)
// Class is the coarse sort of media a file is, for choosing what to arrange.
type Class string
// The classes of media.
const (
Image Class = "image"
Raw Class = "raw"
Video Class = "video"
)
func (k kind) class() Class {
switch k {
case kindRaw:
return Raw
case kindQuickTime, kindVideo:
return Video
}
return Image
}
// ClassOf reports the Class of path by its extension, and whether it is
// media at all.
func ClassOf(path string) (Class, bool) {
k, ok := exts[strings.ToLower(filepath.Ext(path))]
return k.class(), ok
}
var exts = map[string]kind{
// images // images
".jpg": kindJPEG, ".jpg": true,
".jpeg": kindJPEG, ".jpeg": true,
".png": kindPNG, ".png": true,
".gif": kindGIF, ".gif": true,
".heic": kindStill,
".heif": kindStill,
".avif": kindStill,
".tif": kindStill,
".tiff": kindStill,
".dng": kindRaw,
".cr2": kindRaw,
".cr3": kindRaw,
".nef": kindRaw,
".arw": kindRaw,
// videos // videos
".mov": kindQuickTime, ".mov": true,
".mp4": kindQuickTime, ".mp4": true,
".m4v": kindQuickTime, ".m4v": true,
".3gp": kindQuickTime, ".avi": true,
".avi": kindVideo,
".mkv": kindVideo,
".mts": kindVideo,
".m2ts": kindVideo,
".mpg": kindVideo,
".mpeg": kindVideo,
".wmv": kindVideo,
".webm": kindVideo,
} }
// NewHash makes the hash used for content addresses. Stores built by older
// versions used md5; set this to md5.New to keep adding to one of those.
var NewHash func() hash.Hash = sha256.New
// HashByName returns the hash constructor matching the length of a hex
// content address, or nil if it is not one we know.
func HashByName(hexname string) func() hash.Hash {
switch len(hexname) {
case 2 * md5.Size:
return md5.New
case 2 * sha256.Size:
return sha256.New
}
return nil
} }
func mtime(path string) (time.Time, error) { func mtime(path string) (time.Time, error) {
@@ -129,61 +56,21 @@ func PrepOutput(root string) error {
return nil return nil
} }
// Filter narrows what Source sends. // Source returns sends all files that match known extensions.
type Filter struct {
// Classes to include; empty means all.
Classes map[Class]bool
// Exclude skips files and whole directories whose name matches any of
// these filepath.Match patterns, e.g. "VIDEO_TS" or "*.vob".
Exclude []string
}
func (f Filter) excluded(name string) bool {
for _, p := range f.Exclude {
if ok, _ := filepath.Match(p, name); ok {
return true
}
}
return false
}
func (f Filter) wants(c Class) bool {
return len(f.Classes) == 0 || f.Classes[c]
}
// Source sends all files that match known extensions. Unreadable paths are
// logged and skipped rather than ending the crawl.
func Source(root string) <-chan string { func Source(root string) <-chan string {
return SourceFiltered(root, Filter{})
}
// SourceFiltered is Source, sending only the files f lets through.
func SourceFiltered(root string, f Filter) <-chan string {
out := make(chan string) out := make(chan string)
go func() { go func() {
err := filepath.WalkDir( err := filepath.Walk(
root, root,
func(path string, d fs.DirEntry, err error) error { func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
if path == root {
return err return err
} }
log.Printf("skipping %q: %v", path, err) if info.IsDir() {
return nil return nil
} }
name := d.Name() ext := strings.ToLower(filepath.Ext(path))
if d.IsDir() { if _, ok := exts[ext]; ok {
// QNAP thumbnail caches
if name == ".@__thumb" || (path != root && f.excluded(name)) {
return filepath.SkipDir
}
return nil
}
// AppleDouble resource forks
if strings.HasPrefix(name, "._") || f.excluded(name) {
return nil
}
if c, ok := ClassOf(path); ok && f.wants(c) {
out <- path out <- path
} }
return nil return nil
@@ -205,7 +92,7 @@ func Parse(in <-chan string) <-chan Media {
out := make(chan Media) out := make(chan Media)
go func() { go func() {
for path := range in { for path := range in {
f, err := ParseFile(path) f, err := _parse(path)
if err != nil { if err != nil {
switch err.(type) { switch err.(type) {
case NotMedia: case NotMedia:
@@ -225,23 +112,19 @@ func Parse(in <-chan string) <-chan Media {
} }
// MissingLink detects if the values coming from medias is a duplicate file // MissingLink detects if the values coming from medias is a duplicate file
// rather than a hardlink to the content store. Files whose content is not in // rather than a hardlink to the content store.
// the store are reported on errs and never sent on, since there is nothing to
// link them to.
func MissingLink(medias <-chan Media, root string) (<-chan Media, <-chan error) { func MissingLink(medias <-chan Media, root string) (<-chan Media, <-chan error) {
out := make(chan Media) out := make(chan Media)
errs := make(chan error) errs := make(chan error)
go func() { go func() {
for m := range medias { for m := range medias {
d, err := os.Stat(m.Path) var d, c os.FileInfo
if err != nil { var err error
if d, err = os.Stat(m.Path); err != nil {
errs <- err errs <- err
continue
} }
c, err := os.Stat(m.Content(root)) if c, err = os.Stat(m.Content(root)); err != nil {
if err != nil { errs <- err
errs <- fmt.Errorf("%q has no content in store: %v", m.Path, err)
continue
} }
if !os.SameFile(d, c) { if !os.SameFile(d, c) {
out <- m out <- m
@@ -253,24 +136,6 @@ func MissingLink(medias <-chan Media, root string) (<-chan Media, <-chan error)
return out, errs return out, errs
} }
// Relink atomically replaces m.Path with a hardlink to its content in the
// store, so m.Path exists at every moment.
func Relink(m Media, root string) error {
content := m.Content(root)
if _, err := os.Stat(content); err != nil {
return fmt.Errorf("refusing to relink %q: %v", m.Path, err)
}
tmp := filepath.Join(filepath.Dir(m.Path), fmt.Sprintf(".arrange-%d-%s", os.Getpid(), filepath.Base(m.Path)))
if err := os.Link(content, tmp); err != nil {
return fmt.Errorf("couldn't link %q: %v", tmp, err)
}
if err := os.Rename(tmp, m.Path); err != nil {
os.Remove(tmp)
return fmt.Errorf("couldn't replace %q: %v", m.Path, err)
}
return nil
}
// Move calls Move on each Media on input chan. It is the first step in the // Move calls Move on each Media on input chan. It is the first step in the
// pipeline after fan-in. // pipeline after fan-in.
func Move(in <-chan Media, root string) <-chan error { func Move(in <-chan Media, root string) <-chan error {
@@ -284,15 +149,11 @@ func Move(in <-chan Media, root string) <-chan error {
return out return out
} }
// ParseFile extracts metadata from single file. func _parse(path string) (Media, error) {
func ParseFile(path string) (Media, error) {
ext := strings.ToLower(filepath.Ext(path)) ext := strings.ToLower(filepath.Ext(path))
var r Media var r Media
hash := md5.New()
k, ok := exts[ext] var t time.Time
if !ok {
return r, NotMedia{path}
}
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
@@ -300,43 +161,65 @@ func ParseFile(path string) (Media, error) {
} }
defer f.Close() defer f.Close()
// make sure it is what it says it is switch ext {
switch k { default:
case kindJPEG: return r, NotMedia{path}
_, err = jpeg.DecodeConfig(f) case ".jpg", ".jpeg":
case kindPNG: if _, err := jpeg.DecodeConfig(f); err != nil {
_, err = png.DecodeConfig(f)
case kindGIF:
_, err = gif.DecodeConfig(f)
}
if err != nil {
return r, NotMedia{path} return r, NotMedia{path}
} }
if _, err := f.Seek(0, 0); err != nil {
// try a few things for a time value, falling back to mtime
var t time.Time
switch k {
case kindJPEG, kindPNG, kindStill, kindRaw:
t = exifTime(f, k == kindJPEG)
case kindQuickTime:
if _, err := f.Seek(0, io.SeekStart); err == nil {
if qt, err := quickTimeCreated(f); err == nil {
t = qt
}
}
}
if t.IsZero() {
if t, err = mtime(path); err != nil {
return r, fmt.Errorf("unable to calculate reasonable time for media %q: %v", path, err)
}
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return r, fmt.Errorf("couldn't seek back in file: %v", err) return r, fmt.Errorf("couldn't seek back in file: %v", err)
} }
hash := NewHash()
n, err := io.Copy(hash, f) // try a few things for a time value
{
success := false
if t, err = parseExif(f); err == nil {
success = true
}
if !success {
t, err = mtime(path)
}
if err != nil { if err != nil {
return r, fmt.Errorf("unable to calculate reasonble time for jpg %q: %v", path, err)
}
}
case ".png":
if _, err := png.DecodeConfig(f); err != nil {
return r, NotMedia{path}
}
if _, err := f.Seek(0, 0); err != nil {
return r, fmt.Errorf("couldn't seek back in file: %v", err)
}
t, err = mtime(path)
if err != nil {
return r, fmt.Errorf("unable to calculate reasonble time for media %q: %v", path, err)
}
case ".gif":
if _, err := gif.DecodeConfig(f); err != nil {
return r, NotMedia{path}
}
if _, err := f.Seek(0, 0); err != nil {
return r, fmt.Errorf("couldn't seek back in file: %v", err)
}
t, err = mtime(path)
if err != nil {
return r, fmt.Errorf("unable to calculate reasonble time for media %q: %v", path, err)
}
case ".mov", ".mp4", ".m4v", ".avi":
t, err = mtime(path)
if err != nil {
return r, fmt.Errorf("unable to calculate reasonble time for media %q: %v", path, err)
}
}
if _, err := f.Seek(0, 0); err != nil {
return r, fmt.Errorf("couldn't seek back in file: %v", err)
}
if _, err := io.Copy(hash, f); err != nil {
return r, fmt.Errorf("problem calculating checksum on %q: %v", path, err) return r, fmt.Errorf("problem calculating checksum on %q: %v", path, err)
} }
r = Media{ r = Media{
@@ -344,7 +227,6 @@ func ParseFile(path string) (Media, error) {
Hash: fmt.Sprintf("%x", hash.Sum(nil)), Hash: fmt.Sprintf("%x", hash.Sum(nil)),
Extension: ext, Extension: ext,
Time: t, Time: t,
Size: n,
} }
return r, nil return r, nil
} }
+2 -13
View File
@@ -1,7 +1,6 @@
package arrange package arrange
import ( import (
"crypto/md5"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
@@ -10,16 +9,7 @@ import (
"time" "time"
) )
// useMD5 makes a test build an old-style md5 store, which these tests' fixed
// content paths and hashes assume.
func useMD5(t *testing.T) {
old := NewHash
NewHash = md5.New
t.Cleanup(func() { NewHash = old })
}
func TestFileMove(t *testing.T) { func TestFileMove(t *testing.T) {
useMD5(t)
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -93,7 +83,7 @@ func TestFileMove(t *testing.T) {
if err := os.Chtimes(test.path, test.ts, test.ts); err != nil { if err := os.Chtimes(test.path, test.ts, test.ts); err != nil {
t.Fatalf("chtime fail: %v", err) t.Fatalf("chtime fail: %v", err)
} }
m, err := ParseFile(test.path) m, err := _parse(test.path)
if err != nil { if err != nil {
t.Fatalf("problem parsing known good png: %v", err) t.Fatalf("problem parsing known good png: %v", err)
} }
@@ -141,7 +131,7 @@ func TestBadFiles(t *testing.T) {
}, },
} }
for _, test := range tests { for _, test := range tests {
_, err := ParseFile(test.path) _, err := _parse(test.path)
if err == nil { if err == nil {
t.Fatalf("should have had an error in parse of %q, got nil", test.path) t.Fatalf("should have had an error in parse of %q, got nil", test.path)
} }
@@ -149,7 +139,6 @@ func TestBadFiles(t *testing.T) {
} }
func TestMoveCollision(t *testing.T) { func TestMoveCollision(t *testing.T) {
useMD5(t)
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
+13 -35
View File
@@ -3,21 +3,17 @@ package main
import ( import (
"fmt" "fmt"
"log" "log"
"os"
"path/filepath"
"runtime" "runtime"
"mcquay.me/arrange" "mcquay.me/arrange"
) )
func arr(indir, outdir string, f arrange.Filter) error { func arr(indir, outdir string) error {
if !*dryRun {
if err := arrange.PrepOutput(outdir); err != nil { if err := arrange.PrepOutput(outdir); err != nil {
return fmt.Errorf("problem creating directory structure: %v", err) return fmt.Errorf("problem creating directory structure: %v", err)
} }
}
work := arrange.SourceFiltered(indir, f) work := arrange.Source(indir)
streams := []<-chan arrange.Media{} streams := []<-chan arrange.Media{}
workers := runtime.NumCPU() workers := runtime.NumCPU()
@@ -29,41 +25,23 @@ func arr(indir, outdir string, f arrange.Filter) error {
streams = append(streams, arrange.Parse(work)) streams = append(streams, arrange.Parse(work))
} }
st := newStats() st := stats{}
// in a dry run nothing lands in the store, so remember what would have for err := range arrange.Move(arrange.Merge(streams), outdir) {
seen := map[string]bool{} st.total++
for m := range arrange.Merge(streams) { if err != nil {
if *dryRun {
content := m.Content(outdir)
_, err := os.Stat(content)
dup := seen[m.Hash] || err == nil
seen[m.Hash] = true
action := "new"
if dup {
action = "dup"
}
date := filepath.Join(outdir, "date", fmt.Sprintf("%04d", m.Time.Year()), fmt.Sprintf("%02d", m.Time.Month()))
fmt.Printf("%s\t%s\t%s\t%s\n", action, m.Path, content, date)
st.add(m, dup)
continue
}
err := m.Move(outdir)
switch err.(type) { switch err.(type) {
case nil:
st.add(m, false)
case arrange.Dup: case arrange.Dup:
st.add(m, true) st.dupes++
default: default:
st.errors++
log.Printf("%+v", err) log.Printf("%+v", err)
} }
} else {
st.moved++
}
} }
verb := "moved" log.Printf("dupes: %+v", st.dupes)
if *dryRun { log.Printf("moved: %+v", st.moved)
verb = "would move" log.Printf("total: %+v", st.total)
}
st.write(os.Stderr, verb)
return nil return nil
} }
+8 -25
View File
@@ -1,7 +1,6 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
"os" "os"
@@ -33,41 +32,25 @@ func clean(dir string) error {
errs = append(errs, e) errs = append(errs, e)
} }
var problems int var err error
done := make(chan bool)
go func() { go func() {
for e := range eMerge(errs) { for e := range eMerge(errs) {
log.Printf("%+v", e) log.Printf("%+v", e)
problems++ err = fmt.Errorf("%v, %v", err, e)
} }
close(done)
}() }()
var relinked, failed int
for m := range arrange.Merge(streams) { for m := range arrange.Merge(streams) {
if *dryRun { log.Printf("%q > %q", m.Path, m.Content(dir))
fmt.Printf("relink\t%s\t%s\n", m.Path, m.Content(dir)) if err := os.Remove(m.Path); err != nil {
relinked++ log.Printf("%+v", err)
continue }
} if err := os.Link(m.Content(dir), m.Path); err != nil {
if err := arrange.Relink(m, dir); err != nil {
log.Printf("%+v", err) log.Printf("%+v", err)
failed++
continue
} }
relinked++
} }
<-done
verb := "relinked" return err
if *dryRun {
verb = "would relink"
}
log.Printf("%s: %d, failed: %d, problems: %d", verb, relinked, failed, problems)
if problems+failed > 0 {
return errors.New("some files could not be checked or relinked; see log")
}
return nil
} }
func eMerge(cs []<-chan error) <-chan error { func eMerge(cs []<-chan error) <-chan error {
+10 -97
View File
@@ -1,67 +1,23 @@
package main package main
import ( import (
"crypto/md5"
"crypto/sha256"
"flag" "flag"
"fmt" "fmt"
"log" "log"
"os" "os"
"path/filepath"
"strings"
"mcquay.me/arrange"
) )
const usage = "am <arr|survey|clean|verify|meta> [flags]" const usage = "am <arr|clean|help> [flags]"
const arrUsage = "am arr [-h|-n|-kinds=image,raw,video|-exclude=PATTERN...|-hash=sha256|md5|-cores=N] <in> <out>" const arrUsage = "am arr [-h|-cores=N] <in> <out>"
const surveyUsage = "am survey [-h|-depth=N|-kinds=...|-exclude=PATTERN...] <directory>" const cleanUsage = "am clean [-h|-cores=N] <directory>"
const cleanUsage = "am clean [-h|-n|-cores=N] <directory>"
const verifyUsage = "am verify [-h|-cores=N] <directory>" type stats struct {
const metaUsage = "am meta [-h|-cores=N] <file0> <file1> ... <fileN>" total int
dupes int
moved int
}
var cores = flag.Int("cores", 0, "how many threads to use") var cores = flag.Int("cores", 0, "how many threads to use")
var dryRun = flag.Bool("n", false, "dry run: print the plan as tab-separated lines, change nothing")
var hashName = flag.String("hash", "sha256", "content-address hash: sha256, or md5 to add to a store built by older versions")
var kinds = flag.String("kinds", "image,raw,video", "comma-separated kinds of media to include: image, raw, video")
var depth = flag.Int("depth", 1, "survey: how many directory levels to group by")
var excludes patterns
func init() {
flag.Var(&excludes, "exclude", "skip files and directories whose name matches this glob (repeatable), e.g. VIDEO_TS or '*.vob'")
}
// patterns collects a repeated flag.
type patterns []string
func (p *patterns) String() string { return strings.Join(*p, ",") }
func (p *patterns) Set(v string) error {
if _, err := filepath.Match(v, ""); err != nil {
return fmt.Errorf("bad pattern %q: %v", v, err)
}
*p = append(*p, v)
return nil
}
// filter builds the arrange.Filter from the -kinds and -exclude flags.
func filter() (arrange.Filter, error) {
f := arrange.Filter{Classes: map[arrange.Class]bool{}, Exclude: excludes}
for _, k := range strings.Split(*kinds, ",") {
c := arrange.Class(strings.TrimSpace(k))
switch c {
case arrange.Image, arrange.Raw, arrange.Video:
f.Classes[c] = true
case "":
default:
return f, fmt.Errorf("unknown kind %q (known: image, raw, video)", k)
}
}
if len(f.Classes) == 0 {
return f, fmt.Errorf("-kinds selects nothing")
}
return f, nil
}
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
@@ -74,22 +30,6 @@ func main() {
flag.Parse() flag.Parse()
log.SetFlags(log.Lshortfile) log.SetFlags(log.Lshortfile)
switch *hashName {
case "sha256":
arrange.NewHash = sha256.New
case "md5":
arrange.NewHash = md5.New
default:
fmt.Fprintf(os.Stderr, "unsupported hash %q (supported: sha256, md5)\n", *hashName)
os.Exit(1)
}
f, err := filter()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
switch sub { switch sub {
case "ar", "arr", "arrange": case "ar", "arr", "arrange":
args := flag.Args() args := flag.Args()
@@ -98,20 +38,10 @@ func main() {
os.Exit(1) os.Exit(1)
} }
in, out := args[0], args[1] in, out := args[0], args[1]
if err := arr(in, out, f); err != nil { if err := arr(in, out); err != nil {
fmt.Fprintf(os.Stderr, "problem arranging media: %v\n", err) fmt.Fprintf(os.Stderr, "problem arranging media: %v\n", err)
os.Exit(1) os.Exit(1)
} }
case "s", "survey":
args := flag.Args()
if len(args) != 1 {
fmt.Fprintf(os.Stderr, "%s\n", surveyUsage)
os.Exit(1)
}
if err := survey(args[0], f); err != nil {
fmt.Fprintf(os.Stderr, "problem surveying: %v\n", err)
os.Exit(1)
}
case "c", "cl", "clean": case "c", "cl", "clean":
args := flag.Args() args := flag.Args()
if len(args) != 1 { if len(args) != 1 {
@@ -123,23 +53,6 @@ func main() {
fmt.Fprintf(os.Stderr, "problem cleaning: %v\n", err) fmt.Fprintf(os.Stderr, "problem cleaning: %v\n", err)
os.Exit(1) os.Exit(1)
} }
case "v", "verify":
args := flag.Args()
if len(args) != 1 {
fmt.Fprintf(os.Stderr, "%s\n", verifyUsage)
os.Exit(1)
}
if err := verify(args[0]); err != nil {
fmt.Fprintf(os.Stderr, "problem verifying: %v\n", err)
os.Exit(1)
}
case "m", "meta":
args := flag.Args()
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "%s\n", metaUsage)
os.Exit(1)
}
meta(args)
default: default:
fmt.Fprintf(os.Stderr, "%s\n", usage) fmt.Fprintf(os.Stderr, "%s\n", usage)
os.Exit(1) os.Exit(1)
-42
View File
@@ -1,42 +0,0 @@
package main
import (
"fmt"
"log"
"runtime"
"sync"
"mcquay.me/arrange"
)
func meta(files []string) {
workers := runtime.NumCPU()
if *cores != 0 {
workers = *cores
}
fc := make(chan arrange.Media)
go func() {
wg := &sync.WaitGroup{}
s := make(chan bool, workers)
for _, f := range files {
wg.Add(1)
go func(pth string) {
s <- true
pf, err := arrange.ParseFile(pth)
if err != nil {
log.Printf("%+v", err)
} else {
fc <- pf
}
<-s
wg.Done()
}(f)
}
wg.Wait()
close(fc)
}()
for f := range fc {
fmt.Printf("%+v: %v\n", f.Time, f.Path)
}
}
-105
View File
@@ -1,105 +0,0 @@
package main
import (
"fmt"
"io"
"sort"
"strings"
"text/tabwriter"
"mcquay.me/arrange"
)
// stats tallies a run without recording any file names, so the summary is
// safe to share.
type stats struct {
total int
dupes int
moved int
errors int
bytes int64
ext map[string]*tally
year map[int]*tally
}
type tally struct {
files, dupes int
bytes int64
}
func newStats() *stats {
return &stats{ext: map[string]*tally{}, year: map[int]*tally{}}
}
func (s *stats) add(m arrange.Media, dup bool) {
s.total++
s.bytes += m.Size
e := s.ext[m.Extension]
if e == nil {
e = &tally{}
s.ext[m.Extension] = e
}
y := s.year[m.Time.Year()]
if y == nil {
y = &tally{}
s.year[m.Time.Year()] = y
}
e.files++
e.bytes += m.Size
y.files++
y.bytes += m.Size
if dup {
s.dupes++
e.dupes++
y.dupes++
} else {
s.moved++
}
}
func (s *stats) write(w io.Writer, verb string) {
fmt.Fprintf(w, "total: %d files, %s\n", s.total, human(s.bytes))
fmt.Fprintf(w, "%s: %d\n", verb, s.moved)
fmt.Fprintf(w, "dupes: %d\n", s.dupes)
fmt.Fprintf(w, "errors: %d\n", s.errors)
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', tabwriter.AlignRight)
fmt.Fprintln(tw, "\text\tfiles\tdupes\tsize\t")
exts := make([]string, 0, len(s.ext))
for k := range s.ext {
exts = append(exts, k)
}
sort.Strings(exts)
for _, k := range exts {
t := s.ext[k]
fmt.Fprintf(tw, "\t%s\t%d\t%d\t%s\t\n", strings.TrimPrefix(k, "."), t.files, t.dupes, human(t.bytes))
}
tw.Flush()
tw = tabwriter.NewWriter(w, 0, 0, 2, ' ', tabwriter.AlignRight)
fmt.Fprintln(tw, "\tyear\tfiles\tdupes\tsize\t")
years := make([]int, 0, len(s.year))
for k := range s.year {
years = append(years, k)
}
sort.Ints(years)
for _, k := range years {
t := s.year[k]
fmt.Fprintf(tw, "\t%d\t%d\t%d\t%s\t\n", k, t.files, t.dupes, human(t.bytes))
}
tw.Flush()
}
func human(n int64) string {
const unit = 1024
if n < unit {
return fmt.Sprintf("%dB", n)
}
div, exp := int64(unit), 0
for m := n / unit; m >= unit; m /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f%ciB", float64(n)/float64(div), "KMGTPE"[exp])
}
-89
View File
@@ -1,89 +0,0 @@
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
"mcquay.me/arrange"
)
// bigVideo is the size past which a video is more likely a ripped movie than
// a home video.
const bigVideo = 1 << 30
type group struct {
dir string
images, raws, videos int
big int
bytes, videoBytes int64
}
// survey tallies media under dir by directory, *depth levels down, so ripped
// movies and other things to keep out of a store stand out. It only stats
// files, and prints directory names, so its output is for the person running
// it.
func survey(dir string, f arrange.Filter) error {
if _, err := os.Stat(dir); err != nil {
return err
}
groups := map[string]*group{}
for path := range arrange.SourceFiltered(dir, f) {
fi, err := os.Stat(path)
if err != nil {
log.Printf("%v", err)
continue
}
key := groupKey(dir, path, *depth)
g := groups[key]
if g == nil {
g = &group{dir: key}
groups[key] = g
}
g.bytes += fi.Size()
c, _ := arrange.ClassOf(path)
switch c {
case arrange.Image:
g.images++
case arrange.Raw:
g.raws++
case arrange.Video:
g.videos++
g.videoBytes += fi.Size()
if fi.Size() >= bigVideo {
g.big++
}
}
}
gs := make([]*group, 0, len(groups))
for _, g := range groups {
gs = append(gs, g)
}
sort.Slice(gs, func(i, j int) bool { return gs[i].bytes > gs[j].bytes })
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.AlignRight)
fmt.Fprintln(tw, "size\timages\traw\tvideos\tvideos>1G\tvideo size\t\tdir")
for _, g := range gs {
fmt.Fprintf(tw, "%s\t%d\t%d\t%d\t%d\t%s\t\t%s\n",
human(g.bytes), g.images, g.raws, g.videos, g.big, human(g.videoBytes), g.dir)
}
return tw.Flush()
}
// groupKey is the directory of path relative to root, cut to depth levels.
func groupKey(root, path string, depth int) string {
rel, err := filepath.Rel(root, filepath.Dir(path))
if err != nil || rel == "." {
return "."
}
parts := strings.Split(rel, string(filepath.Separator))
if depth > 0 && len(parts) > depth {
parts = parts[:depth]
}
return filepath.Join(parts...)
}
-37
View File
@@ -1,37 +0,0 @@
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"mcquay.me/arrange"
)
// verify rehashes the content store. It only reads.
func verify(dir string) error {
if _, err := os.Stat(filepath.Join(dir, "content")); err != nil {
return fmt.Errorf("couldn't find 'content' dir in %q: %v", dir, err)
}
workers := runtime.NumCPU()
if *cores != 0 {
workers = *cores
}
counts := map[string]int{}
problems, checked := arrange.Verify(dir, workers)
for p := range problems {
counts[p.Kind]++
log.Printf("%v", p)
}
log.Printf("checked: %d, corrupt: %d, orphan: %d, stale: %d, errors: %d",
checked(), counts["corrupt"], counts["orphan"], counts["stale"], counts["error"])
if counts["corrupt"]+counts["error"] > 0 {
return fmt.Errorf("store has problems")
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"fmt"
"os"
"mcquay.me/mov"
)
const usage = "usage: mov <.mov file>"
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "%v\n", usage)
os.Exit(1)
}
for _, path := range os.Args[1:] {
f, err := os.Open(path)
if err != nil {
f.Close()
fmt.Fprintf(os.Stderr, "%v\n", err)
continue
}
s, _ := f.Stat()
c, cerr := mov.Created(f)
f.Seek(0, 0)
m, merr := mov.Created(f)
f.Close()
if cerr != nil || merr != nil {
fmt.Fprintf(os.Stderr, "failed to find time: %v, %v\n", cerr, merr)
continue
}
fmt.Printf("%s: from stat: %+v\n", path, s.ModTime())
fmt.Printf("%s: created on: %+v\n", path, c)
fmt.Printf("%s: modified on: %+v\n\n", path, m)
}
}
-12
View File
@@ -1,12 +0,0 @@
module mcquay.me/arrange
go 1.27.0
require github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
require (
github.com/evanoberholster/imagemeta v1.1.0 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/tinylib/msgp v1.6.3 // indirect
)
-10
View File
@@ -1,10 +0,0 @@
github.com/evanoberholster/imagemeta v1.1.0 h1:0iBtgVxLORZTZAlKxRcNodBmjMfHCSFwUh8Asmi83oI=
github.com/evanoberholster/imagemeta v1.1.0/go.mod h1:nmf6le+qSyoRAXgp2psPbtfkxcEgf/AZGgai9pnN8d0=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/tinylib/msgp v1.6.3 h1:bCSxiTz386UTgyT1i0MSCvdbWjVW+8sG3PjkGsZQt4s=
github.com/tinylib/msgp v1.6.3/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
-45
View File
@@ -3,53 +3,11 @@ package arrange
import ( import (
"fmt" "fmt"
"io" "io"
"log/slog"
"time" "time"
"github.com/evanoberholster/imagemeta"
"github.com/rwcarlsen/goexif/exif" "github.com/rwcarlsen/goexif/exif"
) )
func init() {
imagemeta.SetLogger(io.Discard, slog.LevelError)
}
// exifTime returns the capture time recorded in f, or the zero time if it
// can't find a believable one.
//
// imagemeta handles HEIC and camera RAW; goexif is kept as a fallback for
// jpegs because it copes with some damaged exif that imagemeta rejects.
func exifTime(f io.ReadSeeker, jpeg bool) time.Time {
if _, err := f.Seek(0, io.SeekStart); err != nil {
return time.Time{}
}
if e, err := imagemeta.Decode(f); err == nil {
if t := e.SelectedDate(); plausible(t) {
// exif dates without an offset are camera wall-clock time,
// which imagemeta labels UTC; read them as local like goexif.
if t.Location() == time.UTC {
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)
}
return t
}
}
if !jpeg {
return time.Time{}
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return time.Time{}
}
if t, err := parseExif(f); err == nil && plausible(t) {
return t
}
return time.Time{}
}
// plausible rejects zero and placeholder dates (e.g. "0000:00:00 00:00:00").
func plausible(t time.Time) bool {
return !t.IsZero() && t.Year() >= 1900
}
func parseExif(f io.Reader) (time.Time, error) { func parseExif(f io.Reader) (time.Time, error) {
ti := time.Time{} ti := time.Time{}
x, err := exif.Decode(f) x, err := exif.Decode(f)
@@ -58,9 +16,6 @@ func parseExif(f io.Reader) (time.Time, error) {
return ti, err return ti, err
} }
} }
if x == nil {
return ti, fmt.Errorf("no exif: %v", err)
}
tm, err := x.DateTime() tm, err := x.DateTime()
if err != nil { if err != nil {
return ti, fmt.Errorf("no datetime in an ostensibly valid exif %v", err) return ti, fmt.Errorf("no datetime in an ostensibly valid exif %v", err)
+23 -55
View File
@@ -1,10 +1,8 @@
package arrange package arrange
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
@@ -16,27 +14,35 @@ type Media struct {
Hash string Hash string
Extension string Extension string
Time time.Time Time time.Time
Size int64
} }
// Move is called to push Media into its final destination, by content address // Move is called to push Media into its final destination, by content address
// and by date. // and by date.
//
// The content file is written under a temporary name, checked against m.Hash,
// synced, and only then linked into place, so an interrupted run never leaves
// a truncated file in the store looking like a dup.
func (m Media) Move(root string) error { func (m Media) Move(root string) error {
f, err := os.Open(m.Path)
if err != nil {
return fmt.Errorf("problem opening file %q: %v", m.Path, err)
}
defer f.Close()
content := m.Content(root) content := m.Content(root)
if _, err := os.Stat(content); !os.IsNotExist(err) { if _, err := os.Stat(content); !os.IsNotExist(err) {
return Dup{content} return Dup{content}
} }
if err := m.store(content); err != nil { out, err := os.Create(content)
if errors.Is(err, fs.ErrExist) { if err != nil {
return Dup{content} return fmt.Errorf("could not create output file: %v", err)
} }
return err defer out.Close()
if _, err := io.Copy(out, f); err != nil {
return fmt.Errorf("trouble copying file: %v", err)
}
if err := os.Chtimes(content, time.Now(), m.Time); err != nil {
return fmt.Errorf("couldn't chtimes for %q: %v", content, err)
} }
year := fmt.Sprintf("%04d", m.Time.Year()) year := fmt.Sprintf("%04d", m.Time.Year())
@@ -50,54 +56,16 @@ func (m Media) Move(root string) error {
date := filepath.Join(root, "date", year, month, ts) date := filepath.Join(root, "date", year, month, ts)
name := date + m.Extension name := date + m.Extension
for i := 0; i < 10000; i++ { for i := 0; i < 10000; i++ {
err := os.Link(content, name) if _, err := os.Stat(name); os.IsNotExist(err) {
if !errors.Is(err, fs.ErrExist) { break
return err
} }
name = fmt.Sprintf("%s_%04d%s", date, i, m.Extension) name = fmt.Sprintf("%s_%04d%s", date, i, m.Extension)
} }
return fmt.Errorf("too many files at %q", date)
}
// store copies m.Path to content via a verified temporary file. // TODO: or maybe symlinking? (issue #2)
func (m Media) store(content string) error { // rel := filepath.Join("..", "..", "..", "content", j.hash[:2], j.hash[2:]+m.Extension)
f, err := os.Open(m.Path) // return os.Symlink(rel, name)
if err != nil { return os.Link(content, name)
return fmt.Errorf("problem opening file %q: %v", m.Path, err)
}
defer f.Close()
tmp, err := os.CreateTemp(filepath.Dir(content), ".tmp-")
if err != nil {
return fmt.Errorf("could not create output file: %v", err)
}
defer os.Remove(tmp.Name())
hash := NewHash()
if _, err := io.Copy(io.MultiWriter(tmp, hash), f); err != nil {
tmp.Close()
return fmt.Errorf("trouble copying file: %v", err)
}
if got := fmt.Sprintf("%x", hash.Sum(nil)); got != m.Hash {
tmp.Close()
return fmt.Errorf("%q changed while arranging: hashed %s, copied %s", m.Path, m.Hash, got)
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return fmt.Errorf("couldn't sync %q: %v", tmp.Name(), err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("couldn't close %q: %v", tmp.Name(), err)
}
if err := os.Chmod(tmp.Name(), 0644); err != nil {
return fmt.Errorf("couldn't chmod %q: %v", tmp.Name(), err)
}
if err := os.Chtimes(tmp.Name(), time.Now(), m.Time); err != nil {
return fmt.Errorf("couldn't chtimes for %q: %v", tmp.Name(), err)
}
// link, not rename: it fails rather than clobbers if content appeared
// in the meantime.
return os.Link(tmp.Name(), content)
} }
// Content returns the content-address path starting at root. // Content returns the content-address path starting at root.
-92
View File
@@ -1,92 +0,0 @@
package arrange
import (
"encoding/binary"
"errors"
"fmt"
"io"
"time"
)
// epoch1904 is where QuickTime/MP4 timestamps count from.
var epoch1904 = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC)
var errNoAtom = errors.New("atom not found")
// quickTimeCreated reads the creation time from the movie header (moov/mvhd)
// of a QuickTime or ISO-BMFF (mp4, m4v, 3gp) file.
func quickTimeCreated(r io.ReadSeeker) (time.Time, error) {
end, err := r.Seek(0, io.SeekEnd)
if err != nil {
return time.Time{}, err
}
moov, moovEnd, err := findAtom(r, 0, end, "moov")
if err != nil {
return time.Time{}, err
}
mvhd, _, err := findAtom(r, moov, moovEnd, "mvhd")
if err != nil {
return time.Time{}, err
}
if _, err := r.Seek(mvhd, io.SeekStart); err != nil {
return time.Time{}, err
}
// version(1) flags(3) creation_time(4 or 8)
var hdr [12]byte
if _, err := io.ReadFull(r, hdr[:]); err != nil {
return time.Time{}, fmt.Errorf("short mvhd: %v", err)
}
var secs uint64
switch hdr[0] {
case 0:
secs = uint64(binary.BigEndian.Uint32(hdr[4:8]))
case 1:
secs = binary.BigEndian.Uint64(hdr[4:12])
default:
return time.Time{}, fmt.Errorf("unknown mvhd version %d", hdr[0])
}
if secs == 0 {
return time.Time{}, errors.New("mvhd has no creation time")
}
t := epoch1904.Add(time.Duration(secs) * time.Second)
if !plausible(t) || t.After(time.Now().Add(24*time.Hour)) {
return time.Time{}, fmt.Errorf("implausible mvhd creation time %v", t)
}
return t, nil
}
// findAtom scans the sibling atoms in [start, end) for one named typ, and
// returns the offsets of its payload.
func findAtom(r io.ReadSeeker, start, end int64, typ string) (int64, int64, error) {
for off := start; off+8 <= end; {
if _, err := r.Seek(off, io.SeekStart); err != nil {
return 0, 0, err
}
var hdr [16]byte
if _, err := io.ReadFull(r, hdr[:8]); err != nil {
return 0, 0, err
}
size := int64(binary.BigEndian.Uint32(hdr[:4]))
name := string(hdr[4:8])
body := off + 8
switch size {
case 0: // runs to the end of the container
size = end - off
case 1: // 64-bit size follows the name
if _, err := io.ReadFull(r, hdr[8:16]); err != nil {
return 0, 0, err
}
size = int64(binary.BigEndian.Uint64(hdr[8:16]))
body += 8
}
if size < body-off || off+size > end {
return 0, 0, fmt.Errorf("bad size %d for atom %q at %d", size, name, off)
}
if name == typ {
return body, off + size, nil
}
off += size
}
return 0, 0, errNoAtom
}
-333
View File
@@ -1,333 +0,0 @@
package arrange
import (
"bytes"
"encoding/binary"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// atom builds a QuickTime atom with a 32-bit size.
func atom(typ string, body ...[]byte) []byte {
b := bytes.Join(body, nil)
out := make([]byte, 8, 8+len(b))
binary.BigEndian.PutUint32(out, uint32(8+len(b)))
copy(out[4:], typ)
return append(out, b...)
}
// mvhd builds a movie header body of the given version with creation time t.
func mvhd(version byte, t time.Time) []byte {
secs := uint64(t.Sub(epoch1904) / time.Second)
if version == 0 {
b := make([]byte, 100)
binary.BigEndian.PutUint32(b[4:], uint32(secs))
return b
}
b := make([]byte, 112)
b[0] = 1
binary.BigEndian.PutUint64(b[4:], secs)
return b
}
func TestQuickTimeCreated(t *testing.T) {
when := time.Date(2019, 7, 4, 20, 15, 0, 0, time.UTC)
// 64-bit size atom: size field 1, then the real size
big := make([]byte, 16+4)
binary.BigEndian.PutUint32(big, 1)
copy(big[4:], "free")
binary.BigEndian.PutUint64(big[8:], uint64(len(big)))
tests := []struct {
name string
file []byte
want time.Time
ok bool
}{
{"v0", bytes.Join([][]byte{atom("ftyp", []byte("qt ")), atom("moov", atom("mvhd", mvhd(0, when)))}, nil), when, true},
{"v1", bytes.Join([][]byte{atom("ftyp", []byte("isom")), atom("mdat", make([]byte, 64)), atom("moov", atom("trak"), atom("mvhd", mvhd(1, when)))}, nil), when, true},
{"largesize", bytes.Join([][]byte{big, atom("moov", atom("mvhd", mvhd(0, when)))}, nil), when, true},
{"zero time", atom("moov", atom("mvhd", mvhd(0, epoch1904))), time.Time{}, false},
{"no moov", atom("ftyp", []byte("isom")), time.Time{}, false},
{"garbage", []byte("a\n"), time.Time{}, false},
{"lying size", append(atom("moov", atom("mvhd", mvhd(0, when)))[:4], []byte("moov")...), time.Time{}, false},
}
for _, test := range tests {
got, err := quickTimeCreated(bytes.NewReader(test.file))
if (err == nil) != test.ok {
t.Errorf("%s: err = %v, want ok=%v", test.name, err, test.ok)
continue
}
if test.ok && !got.Equal(test.want) {
t.Errorf("%s: got %v, want %v", test.name, got, test.want)
}
}
}
func TestParseQuickTimeDate(t *testing.T) {
when := time.Date(2019, 7, 4, 20, 15, 0, 0, time.UTC)
p := filepath.Join(t.TempDir(), "clip.MP4")
if err := os.WriteFile(p, atom("moov", atom("mvhd", mvhd(0, when))), 0644); err != nil {
t.Fatal(err)
}
m, err := ParseFile(p)
if err != nil {
t.Fatal(err)
}
if !m.Time.Equal(when) {
t.Errorf("got %v, want %v from mvhd", m.Time, when)
}
if m.Extension != ".mp4" {
t.Errorf("extension %q, want .mp4", m.Extension)
}
}
func TestParseHEIC(t *testing.T) {
m, err := ParseFile(filepath.Join("testdata", "exif.heic"))
if err != nil {
t.Fatal(err)
}
want := time.Date(2006, 3, 27, 17, 19, 27, 0, time.Local)
if !m.Time.Equal(want) {
t.Errorf("got %v, want %v", m.Time, want)
}
if len(m.Hash) != 64 {
t.Errorf("hash %q isn't sha256", m.Hash)
}
}
func TestSourceSkips(t *testing.T) {
root := t.TempDir()
for _, p := range []string{
"keep.jpg",
"sub/KEEP.HEIC",
"._resource-fork.jpg",
".@__thumb/thumb.jpg",
"notes.txt",
} {
full := filepath.Join(root, p)
if err := os.MkdirAll(filepath.Dir(full), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(full, nil, 0644); err != nil {
t.Fatal(err)
}
}
unreadable := filepath.Join(root, "locked")
if err := os.Mkdir(unreadable, 0); err != nil {
t.Fatal(err)
}
defer os.Chmod(unreadable, 0755)
var got []string
for p := range Source(root) {
rel, _ := filepath.Rel(root, p)
got = append(got, rel)
}
if want := "keep.jpg sub/KEEP.HEIC"; strings.Join(got, " ") != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestSourceFiltered(t *testing.T) {
root := t.TempDir()
for _, p := range []string{
"pics/a.jpg",
"pics/b.NEF",
"pics/clip.mov",
"rips/Movie/VIDEO_TS/VTS_01_1.mp4",
"rips/film.mkv",
"rips/cover.jpg",
} {
full := filepath.Join(root, p)
if err := os.MkdirAll(filepath.Dir(full), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(full, nil, 0644); err != nil {
t.Fatal(err)
}
}
tests := []struct {
name string
f Filter
want string
}{
{"everything", Filter{}, "pics/a.jpg pics/b.NEF pics/clip.mov rips/Movie/VIDEO_TS/VTS_01_1.mp4 rips/cover.jpg rips/film.mkv"},
{"images", Filter{Classes: map[Class]bool{Image: true}}, "pics/a.jpg rips/cover.jpg"},
{"no video", Filter{Classes: map[Class]bool{Image: true, Raw: true}}, "pics/a.jpg pics/b.NEF rips/cover.jpg"},
{"exclude dir", Filter{Exclude: []string{"VIDEO_TS"}}, "pics/a.jpg pics/b.NEF pics/clip.mov rips/cover.jpg rips/film.mkv"},
{"exclude glob", Filter{Exclude: []string{"*.mkv", "rip*"}}, "pics/a.jpg pics/b.NEF pics/clip.mov"},
{"root not excluded", Filter{Exclude: []string{filepath.Base(root)}}, "pics/a.jpg pics/b.NEF pics/clip.mov rips/Movie/VIDEO_TS/VTS_01_1.mp4 rips/cover.jpg rips/film.mkv"},
}
for _, test := range tests {
var got []string
for p := range SourceFiltered(root, test.f) {
rel, _ := filepath.Rel(root, p)
got = append(got, rel)
}
if g := strings.Join(got, " "); g != test.want {
t.Errorf("%s:\n got %s\nwant %s", test.name, g, test.want)
}
}
}
// arranged returns a store with one file arranged into it, and that Media.
func arranged(t *testing.T) (string, Media) {
t.Helper()
root := t.TempDir()
if err := PrepOutput(root); err != nil {
t.Fatal(err)
}
m, err := ParseFile(filepath.Join("testdata", "lenna.png"))
if err != nil {
t.Fatal(err)
}
if err := m.Move(root); err != nil {
t.Fatal(err)
}
return root, m
}
func dated(t *testing.T, root string) []string {
t.Helper()
var out []string
for p := range Source(filepath.Join(root, "date")) {
out = append(out, p)
}
return out
}
// The old clean deleted date files whose content was missing from the store,
// then failed to relink them, losing the file.
func TestCleanKeepsFilesMissingFromStore(t *testing.T) {
root, m := arranged(t)
d := dated(t, root)
if len(d) != 1 {
t.Fatalf("expected one dated file, got %v", d)
}
if err := os.Remove(m.Content(root)); err != nil {
t.Fatal(err)
}
pm, err := ParseFile(d[0])
if err != nil {
t.Fatal(err)
}
in := make(chan Media, 1)
in <- pm
close(in)
out, errs := MissingLink(in, root)
var nerr int
go func() {
for range errs {
nerr++
}
}()
for m := range out {
t.Errorf("MissingLink sent %q on for relinking with no content", m.Path)
}
if err := Relink(pm, root); err == nil {
t.Error("Relink should refuse when content is missing")
}
if _, err := os.Stat(d[0]); err != nil {
t.Errorf("dated file is gone: %v", err)
}
}
func TestRelinkReplacesCopy(t *testing.T) {
root, m := arranged(t)
d := dated(t, root)[0]
// break the hardlink: replace the dated file with an identical copy
b, err := os.ReadFile(d)
if err != nil {
t.Fatal(err)
}
if err := os.Remove(d); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(d, b, 0644); err != nil {
t.Fatal(err)
}
pm, err := ParseFile(d)
if err != nil {
t.Fatal(err)
}
if err := Relink(pm, root); err != nil {
t.Fatal(err)
}
a, _ := os.Stat(d)
c, _ := os.Stat(m.Content(root))
if !os.SameFile(a, c) {
t.Error("dated file isn't a hardlink to content after Relink")
}
if left, _ := filepath.Glob(filepath.Join(filepath.Dir(d), ".arrange-*")); len(left) > 0 {
t.Errorf("temp files left behind: %v", left)
}
}
func TestMoveVerifiesHash(t *testing.T) {
root := t.TempDir()
if err := PrepOutput(root); err != nil {
t.Fatal(err)
}
m, err := ParseFile(filepath.Join("testdata", "lenna.png"))
if err != nil {
t.Fatal(err)
}
// as if the file changed between hashing and copying
m.Hash = strings.Repeat("ab", 32)
if err := m.Move(root); err == nil {
t.Fatal("Move should fail when the copy doesn't match the hash")
}
left, _ := filepath.Glob(filepath.Join(root, "content", "ab", "*"))
hidden, _ := filepath.Glob(filepath.Join(root, "content", "ab", ".*"))
if len(left)+len(hidden) > 0 {
t.Errorf("store not clean after failed move: %v %v", left, hidden)
}
if err := m.Move(root); err == nil {
t.Fatal("a second try should fail too, not be called a dup")
}
}
func TestVerify(t *testing.T) {
root, m := arranged(t)
problems := func() map[string]int {
out := map[string]int{}
ps, checked := Verify(root, 2)
for p := range ps {
out[p.Kind]++
}
out["checked"] = checked()
return out
}
if got := problems(); got["checked"] != 1 || len(got) != 1 {
t.Fatalf("healthy store: %v", got)
}
// orphan: content nothing links to
for _, d := range dated(t, root) {
os.Remove(d)
}
// stale: a temp file from a crashed run
os.WriteFile(filepath.Join(root, "content", "00", ".tmp-123"), []byte("x"), 0644)
if got := problems(); got["orphan"] != 1 || got["stale"] != 1 {
t.Errorf("want one orphan and one stale, got %v", got)
}
// corrupt: bytes no longer match the name
if err := os.WriteFile(m.Content(root), []byte("bitrot"), 0644); err != nil {
t.Fatal(err)
}
if got := problems(); got["corrupt"] != 1 {
t.Errorf("want one corrupt, got %v", got)
}
}
-5
View File
@@ -10,8 +10,3 @@ https://en.wikipedia.org/w/index.php?curid=20658476
By No machine-readable author provided. Webber assumed (based on copyright By No machine-readable author provided. Webber assumed (based on copyright
claims). [Public domain], via Wikimedia Commons claims). [Public domain], via Wikimedia Commons
# exif.heic
exif-decode-error.jpg converted with `sips -s format heic -s formatOptions 10`;
keeps its 2006-03-27 EXIF date.
BIN
View File
Binary file not shown.
+24
View File
@@ -0,0 +1,24 @@
Copyright (c) 2012, Robert Carlsen & Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+4
View File
@@ -0,0 +1,4 @@
To regenerate the regression test data, run `go generate` inside the exif
package directory and commit the changes to *regress_expected_test.go*.
+619
View File
@@ -0,0 +1,619 @@
// Package exif implements decoding of EXIF data as defined in the EXIF 2.2
// specification (http://www.exif.org/Exif2-2.PDF).
package exif
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"strconv"
"strings"
"time"
"github.com/rwcarlsen/goexif/tiff"
)
const (
jpeg_APP1 = 0xE1
exifPointer = 0x8769
gpsPointer = 0x8825
interopPointer = 0xA005
)
// A decodeError is returned when the image cannot be decoded as a tiff image.
type decodeError struct {
cause error
}
func (de decodeError) Error() string {
return fmt.Sprintf("exif: decode failed (%v) ", de.cause.Error())
}
// IsShortReadTagValueError identifies a ErrShortReadTagValue error.
func IsShortReadTagValueError(err error) bool {
de, ok := err.(decodeError)
if ok {
return de.cause == tiff.ErrShortReadTagValue
}
return false
}
// A TagNotPresentError is returned when the requested field is not
// present in the EXIF.
type TagNotPresentError FieldName
func (tag TagNotPresentError) Error() string {
return fmt.Sprintf("exif: tag %q is not present", string(tag))
}
func IsTagNotPresentError(err error) bool {
_, ok := err.(TagNotPresentError)
return ok
}
// Parser allows the registration of custom parsing and field loading
// in the Decode function.
type Parser interface {
// Parse should read data from x and insert parsed fields into x via
// LoadTags.
Parse(x *Exif) error
}
var parsers []Parser
func init() {
RegisterParsers(&parser{})
}
// RegisterParsers registers one or more parsers to be automatically called
// when decoding EXIF data via the Decode function.
func RegisterParsers(ps ...Parser) {
parsers = append(parsers, ps...)
}
type parser struct{}
type tiffErrors map[tiffError]string
func (te tiffErrors) Error() string {
var allErrors []string
for k, v := range te {
allErrors = append(allErrors, fmt.Sprintf("%s: %v\n", stagePrefix[k], v))
}
return strings.Join(allErrors, "\n")
}
// IsCriticalError, given the error returned by Decode, reports whether the
// returned *Exif may contain usable information.
func IsCriticalError(err error) bool {
_, ok := err.(tiffErrors)
return !ok
}
// IsExifError reports whether the error happened while decoding the EXIF
// sub-IFD.
func IsExifError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isExif := te[loadExif]
return isExif
}
return false
}
// IsGPSError reports whether the error happened while decoding the GPS sub-IFD.
func IsGPSError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isGPS := te[loadExif]
return isGPS
}
return false
}
// IsInteroperabilityError reports whether the error happened while decoding the
// Interoperability sub-IFD.
func IsInteroperabilityError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isInterop := te[loadInteroperability]
return isInterop
}
return false
}
type tiffError int
const (
loadExif tiffError = iota
loadGPS
loadInteroperability
)
var stagePrefix = map[tiffError]string{
loadExif: "loading EXIF sub-IFD",
loadGPS: "loading GPS sub-IFD",
loadInteroperability: "loading Interoperability sub-IFD",
}
// Parse reads data from the tiff data in x and populates the tags
// in x. If parsing a sub-IFD fails, the error is recorded and
// parsing continues with the remaining sub-IFDs.
func (p *parser) Parse(x *Exif) error {
x.LoadTags(x.Tiff.Dirs[0], exifFields, false)
// thumbnails
if len(x.Tiff.Dirs) >= 2 {
x.LoadTags(x.Tiff.Dirs[1], thumbnailFields, false)
}
te := make(tiffErrors)
// recurse into exif, gps, and interop sub-IFDs
if err := loadSubDir(x, ExifIFDPointer, exifFields); err != nil {
te[loadExif] = err.Error()
}
if err := loadSubDir(x, GPSInfoIFDPointer, gpsFields); err != nil {
te[loadGPS] = err.Error()
}
if err := loadSubDir(x, InteroperabilityIFDPointer, interopFields); err != nil {
te[loadInteroperability] = err.Error()
}
if len(te) > 0 {
return te
}
return nil
}
func loadSubDir(x *Exif, ptr FieldName, fieldMap map[uint16]FieldName) error {
r := bytes.NewReader(x.Raw)
tag, err := x.Get(ptr)
if err != nil {
return nil
}
offset, err := tag.Int64(0)
if err != nil {
return nil
}
_, err = r.Seek(offset, 0)
if err != nil {
return fmt.Errorf("exif: seek to sub-IFD %s failed: %v", ptr, err)
}
subDir, _, err := tiff.DecodeDir(r, x.Tiff.Order)
if err != nil {
return fmt.Errorf("exif: sub-IFD %s decode failed: %v", ptr, err)
}
x.LoadTags(subDir, fieldMap, false)
return nil
}
// Exif provides access to decoded EXIF metadata fields and values.
type Exif struct {
Tiff *tiff.Tiff
main map[FieldName]*tiff.Tag
Raw []byte
}
// Decode parses EXIF-encoded data from r and returns a queryable Exif
// object. After the exif data section is called and the tiff structure
// decoded, each registered parser is called (in order of registration). If
// one parser returns an error, decoding terminates and the remaining
// parsers are not called.
// The error can be inspected with functions such as IsCriticalError to
// determine whether the returned object might still be usable.
func Decode(r io.Reader) (*Exif, error) {
// EXIF data in JPEG is stored in the APP1 marker. EXIF data uses the TIFF
// format to store data.
// If we're parsing a TIFF image, we don't need to strip away any data.
// If we're parsing a JPEG image, we need to strip away the JPEG APP1
// marker and also the EXIF header.
header := make([]byte, 4)
n, err := r.Read(header)
if err != nil {
return nil, err
}
if n < len(header) {
return nil, errors.New("exif: short read on header")
}
var isTiff bool
switch string(header) {
case "II*\x00":
// TIFF - Little endian (Intel)
isTiff = true
case "MM\x00*":
// TIFF - Big endian (Motorola)
isTiff = true
default:
// Not TIFF, assume JPEG
}
// Put the header bytes back into the reader.
r = io.MultiReader(bytes.NewReader(header), r)
var (
er *bytes.Reader
tif *tiff.Tiff
)
if isTiff {
// Functions below need the IFDs from the TIFF data to be stored in a
// *bytes.Reader. We use TeeReader to get a copy of the bytes as a
// side-effect of tiff.Decode() doing its work.
b := &bytes.Buffer{}
tr := io.TeeReader(r, b)
tif, err = tiff.Decode(tr)
er = bytes.NewReader(b.Bytes())
} else {
// Locate the JPEG APP1 header.
var sec *appSec
sec, err = newAppSec(jpeg_APP1, r)
if err != nil {
return nil, err
}
// Strip away EXIF header.
er, err = sec.exifReader()
if err != nil {
return nil, err
}
tif, err = tiff.Decode(er)
}
if err != nil {
return nil, decodeError{cause: err}
}
er.Seek(0, 0)
raw, err := ioutil.ReadAll(er)
if err != nil {
return nil, decodeError{cause: err}
}
// build an exif structure from the tiff
x := &Exif{
main: map[FieldName]*tiff.Tag{},
Tiff: tif,
Raw: raw,
}
for i, p := range parsers {
if err := p.Parse(x); err != nil {
if _, ok := err.(tiffErrors); ok {
return x, err
}
// This should never happen, as Parse always returns a tiffError
// for now, but that could change.
return x, fmt.Errorf("exif: parser %v failed (%v)", i, err)
}
}
return x, nil
}
// LoadTags loads tags into the available fields from the tiff Directory
// using the given tagid-fieldname mapping. Used to load makernote and
// other meta-data. If showMissing is true, tags in d that are not in the
// fieldMap will be loaded with the FieldName UnknownPrefix followed by the
// tag ID (in hex format).
func (x *Exif) LoadTags(d *tiff.Dir, fieldMap map[uint16]FieldName, showMissing bool) {
for _, tag := range d.Tags {
name := fieldMap[tag.Id]
if name == "" {
if !showMissing {
continue
}
name = FieldName(fmt.Sprintf("%v%x", UnknownPrefix, tag.Id))
}
x.main[name] = tag
}
}
// Get retrieves the EXIF tag for the given field name.
//
// If the tag is not known or not present, an error is returned. If the
// tag name is known, the error will be a TagNotPresentError.
func (x *Exif) Get(name FieldName) (*tiff.Tag, error) {
if tg, ok := x.main[name]; ok {
return tg, nil
}
return nil, TagNotPresentError(name)
}
// Walker is the interface used to traverse all fields of an Exif object.
type Walker interface {
// Walk is called for each non-nil EXIF field. Returning a non-nil
// error aborts the walk/traversal.
Walk(name FieldName, tag *tiff.Tag) error
}
// Walk calls the Walk method of w with the name and tag for every non-nil
// EXIF field. If w aborts the walk with an error, that error is returned.
func (x *Exif) Walk(w Walker) error {
for name, tag := range x.main {
if err := w.Walk(name, tag); err != nil {
return err
}
}
return nil
}
// DateTime returns the EXIF's "DateTimeOriginal" field, which
// is the creation time of the photo. If not found, it tries
// the "DateTime" (which is meant as the modtime) instead.
// The error will be TagNotPresentErr if none of those tags
// were found, or a generic error if the tag value was
// not a string, or the error returned by time.Parse.
//
// If the EXIF lacks timezone information or GPS time, the returned
// time's Location will be time.Local.
func (x *Exif) DateTime() (time.Time, error) {
var dt time.Time
tag, err := x.Get(DateTimeOriginal)
if err != nil {
tag, err = x.Get(DateTime)
if err != nil {
return dt, err
}
}
if tag.Format() != tiff.StringVal {
return dt, errors.New("DateTime[Original] not in string format")
}
exifTimeLayout := "2006:01:02 15:04:05"
dateStr := strings.TrimRight(string(tag.Val), "\x00")
// TODO(bradfitz,mpl): look for timezone offset, GPS time, etc.
// For now, just always return the time.Local timezone.
return time.ParseInLocation(exifTimeLayout, dateStr, time.Local)
}
func ratFloat(num, dem int64) float64 {
return float64(num) / float64(dem)
}
// Tries to parse a Geo degrees value from a string as it was found in some
// EXIF data.
// Supported formats so far:
// - "52,00000,50,00000,34,01180" ==> 52 deg 50'34.0118"
// Probably due to locale the comma is used as decimal mark as well as the
// separator of three floats (degrees, minutes, seconds)
// http://en.wikipedia.org/wiki/Decimal_mark#Hindu.E2.80.93Arabic_numeral_system
// - "52.0,50.0,34.01180" ==> 52deg50'34.0118"
// - "52,50,34.01180" ==> 52deg50'34.0118"
func parseTagDegreesString(s string) (float64, error) {
const unparsableErrorFmt = "Unknown coordinate format: %s"
isSplitRune := func(c rune) bool {
return c == ',' || c == ';'
}
parts := strings.FieldsFunc(s, isSplitRune)
var degrees, minutes, seconds float64
var err error
switch len(parts) {
case 6:
degrees, err = strconv.ParseFloat(parts[0]+"."+parts[1], 64)
if err != nil {
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
minutes, err = strconv.ParseFloat(parts[2]+"."+parts[3], 64)
if err != nil {
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
minutes = math.Copysign(minutes, degrees)
seconds, err = strconv.ParseFloat(parts[4]+"."+parts[5], 64)
if err != nil {
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
seconds = math.Copysign(seconds, degrees)
case 3:
degrees, err = strconv.ParseFloat(parts[0], 64)
if err != nil {
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
minutes, err = strconv.ParseFloat(parts[1], 64)
if err != nil {
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
minutes = math.Copysign(minutes, degrees)
seconds, err = strconv.ParseFloat(parts[2], 64)
if err != nil {
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
seconds = math.Copysign(seconds, degrees)
default:
return 0.0, fmt.Errorf(unparsableErrorFmt, s)
}
return degrees + minutes/60.0 + seconds/3600.0, nil
}
func parse3Rat2(tag *tiff.Tag) ([3]float64, error) {
v := [3]float64{}
for i := range v {
num, den, err := tag.Rat2(i)
if err != nil {
return v, err
}
v[i] = ratFloat(num, den)
if tag.Count < uint32(i+2) {
break
}
}
return v, nil
}
func tagDegrees(tag *tiff.Tag) (float64, error) {
switch tag.Format() {
case tiff.RatVal:
// The usual case, according to the Exif spec
// (http://www.kodak.com/global/plugins/acrobat/en/service/digCam/exifStandard2.pdf,
// sec 4.6.6, p. 52 et seq.)
v, err := parse3Rat2(tag)
if err != nil {
return 0.0, err
}
return v[0] + v[1]/60 + v[2]/3600.0, nil
case tiff.StringVal:
// Encountered this weird case with a panorama picture taken with a HTC phone
s, err := tag.StringVal()
if err != nil {
return 0.0, err
}
return parseTagDegreesString(s)
default:
// don't know how to parse value, give up
return 0.0, fmt.Errorf("Malformed EXIF Tag Degrees")
}
}
// LatLong returns the latitude and longitude of the photo and
// whether it was present.
func (x *Exif) LatLong() (lat, long float64, err error) {
// All calls of x.Get might return an TagNotPresentError
longTag, err := x.Get(FieldName("GPSLongitude"))
if err != nil {
return
}
ewTag, err := x.Get(FieldName("GPSLongitudeRef"))
if err != nil {
return
}
latTag, err := x.Get(FieldName("GPSLatitude"))
if err != nil {
return
}
nsTag, err := x.Get(FieldName("GPSLatitudeRef"))
if err != nil {
return
}
if long, err = tagDegrees(longTag); err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
if lat, err = tagDegrees(latTag); err != nil {
return 0, 0, fmt.Errorf("Cannot parse latitude: %v", err)
}
ew, err := ewTag.StringVal()
if err == nil && ew == "W" {
long *= -1.0
} else if err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
ns, err := nsTag.StringVal()
if err == nil && ns == "S" {
lat *= -1.0
} else if err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
return lat, long, nil
}
// String returns a pretty text representation of the decoded exif data.
func (x *Exif) String() string {
var buf bytes.Buffer
for name, tag := range x.main {
fmt.Fprintf(&buf, "%s: %s\n", name, tag)
}
return buf.String()
}
// JpegThumbnail returns the jpeg thumbnail if it exists. If it doesn't exist,
// TagNotPresentError will be returned
func (x *Exif) JpegThumbnail() ([]byte, error) {
offset, err := x.Get(ThumbJPEGInterchangeFormat)
if err != nil {
return nil, err
}
start, err := offset.Int(0)
if err != nil {
return nil, err
}
length, err := x.Get(ThumbJPEGInterchangeFormatLength)
if err != nil {
return nil, err
}
l, err := length.Int(0)
if err != nil {
return nil, err
}
return x.Raw[start : start+l], nil
}
// MarshalJson implements the encoding/json.Marshaler interface providing output of
// all EXIF fields present (names and values).
func (x Exif) MarshalJSON() ([]byte, error) {
return json.Marshal(x.main)
}
type appSec struct {
marker byte
data []byte
}
// newAppSec finds marker in r and returns the corresponding application data
// section.
func newAppSec(marker byte, r io.Reader) (*appSec, error) {
br := bufio.NewReader(r)
app := &appSec{marker: marker}
var dataLen int
// seek to marker
for dataLen == 0 {
if _, err := br.ReadBytes(0xFF); err != nil {
return nil, err
}
c, err := br.ReadByte()
if err != nil {
return nil, err
} else if c != marker {
continue
}
dataLenBytes := make([]byte, 2)
for k,_ := range dataLenBytes {
c, err := br.ReadByte()
if err != nil {
return nil, err
}
dataLenBytes[k] = c
}
dataLen = int(binary.BigEndian.Uint16(dataLenBytes)) - 2
}
// read section data
nread := 0
for nread < dataLen {
s := make([]byte, dataLen-nread)
n, err := br.Read(s)
nread += n
if err != nil && nread < dataLen {
return nil, err
}
app.data = append(app.data, s[:n]...)
}
return app, nil
}
// reader returns a reader on this appSec.
func (app *appSec) reader() *bytes.Reader {
return bytes.NewReader(app.data)
}
// exifReader returns a reader on this appSec with the read cursor advanced to
// the start of the exif's tiff encoded portion.
func (app *appSec) exifReader() (*bytes.Reader, error) {
if len(app.data) < 6 {
return nil, errors.New("exif: failed to find exif intro marker")
}
// read/check for exif special mark
exif := app.data[:6]
if !bytes.Equal(exif, append([]byte("Exif"), 0x00, 0x00)) {
return nil, errors.New("exif: failed to find exif intro marker")
}
return bytes.NewReader(app.data[6:]), nil
}
+293
View File
@@ -0,0 +1,293 @@
package exif
type FieldName string
// UnknownPrefix is used as the first part of field names for decoded tags for
// which there is no known/supported EXIF field.
const UnknownPrefix = "UnknownTag_"
// Primary EXIF fields
const (
ImageWidth FieldName = "ImageWidth"
ImageLength = "ImageLength" // Image height called Length by EXIF spec
BitsPerSample = "BitsPerSample"
Compression = "Compression"
PhotometricInterpretation = "PhotometricInterpretation"
Orientation = "Orientation"
SamplesPerPixel = "SamplesPerPixel"
PlanarConfiguration = "PlanarConfiguration"
YCbCrSubSampling = "YCbCrSubSampling"
YCbCrPositioning = "YCbCrPositioning"
XResolution = "XResolution"
YResolution = "YResolution"
ResolutionUnit = "ResolutionUnit"
DateTime = "DateTime"
ImageDescription = "ImageDescription"
Make = "Make"
Model = "Model"
Software = "Software"
Artist = "Artist"
Copyright = "Copyright"
ExifIFDPointer = "ExifIFDPointer"
GPSInfoIFDPointer = "GPSInfoIFDPointer"
InteroperabilityIFDPointer = "InteroperabilityIFDPointer"
ExifVersion = "ExifVersion"
FlashpixVersion = "FlashpixVersion"
ColorSpace = "ColorSpace"
ComponentsConfiguration = "ComponentsConfiguration"
CompressedBitsPerPixel = "CompressedBitsPerPixel"
PixelXDimension = "PixelXDimension"
PixelYDimension = "PixelYDimension"
MakerNote = "MakerNote"
UserComment = "UserComment"
RelatedSoundFile = "RelatedSoundFile"
DateTimeOriginal = "DateTimeOriginal"
DateTimeDigitized = "DateTimeDigitized"
SubSecTime = "SubSecTime"
SubSecTimeOriginal = "SubSecTimeOriginal"
SubSecTimeDigitized = "SubSecTimeDigitized"
ImageUniqueID = "ImageUniqueID"
ExposureTime = "ExposureTime"
FNumber = "FNumber"
ExposureProgram = "ExposureProgram"
SpectralSensitivity = "SpectralSensitivity"
ISOSpeedRatings = "ISOSpeedRatings"
OECF = "OECF"
ShutterSpeedValue = "ShutterSpeedValue"
ApertureValue = "ApertureValue"
BrightnessValue = "BrightnessValue"
ExposureBiasValue = "ExposureBiasValue"
MaxApertureValue = "MaxApertureValue"
SubjectDistance = "SubjectDistance"
MeteringMode = "MeteringMode"
LightSource = "LightSource"
Flash = "Flash"
FocalLength = "FocalLength"
SubjectArea = "SubjectArea"
FlashEnergy = "FlashEnergy"
SpatialFrequencyResponse = "SpatialFrequencyResponse"
FocalPlaneXResolution = "FocalPlaneXResolution"
FocalPlaneYResolution = "FocalPlaneYResolution"
FocalPlaneResolutionUnit = "FocalPlaneResolutionUnit"
SubjectLocation = "SubjectLocation"
ExposureIndex = "ExposureIndex"
SensingMethod = "SensingMethod"
FileSource = "FileSource"
SceneType = "SceneType"
CFAPattern = "CFAPattern"
CustomRendered = "CustomRendered"
ExposureMode = "ExposureMode"
WhiteBalance = "WhiteBalance"
DigitalZoomRatio = "DigitalZoomRatio"
FocalLengthIn35mmFilm = "FocalLengthIn35mmFilm"
SceneCaptureType = "SceneCaptureType"
GainControl = "GainControl"
Contrast = "Contrast"
Saturation = "Saturation"
Sharpness = "Sharpness"
DeviceSettingDescription = "DeviceSettingDescription"
SubjectDistanceRange = "SubjectDistanceRange"
LensMake = "LensMake"
LensModel = "LensModel"
)
// thumbnail fields
const (
ThumbJPEGInterchangeFormat = "ThumbJPEGInterchangeFormat" // offset to thumb jpeg SOI
ThumbJPEGInterchangeFormatLength = "ThumbJPEGInterchangeFormatLength" // byte length of thumb
)
// GPS fields
const (
GPSVersionID FieldName = "GPSVersionID"
GPSLatitudeRef = "GPSLatitudeRef"
GPSLatitude = "GPSLatitude"
GPSLongitudeRef = "GPSLongitudeRef"
GPSLongitude = "GPSLongitude"
GPSAltitudeRef = "GPSAltitudeRef"
GPSAltitude = "GPSAltitude"
GPSTimeStamp = "GPSTimeStamp"
GPSSatelites = "GPSSatelites"
GPSStatus = "GPSStatus"
GPSMeasureMode = "GPSMeasureMode"
GPSDOP = "GPSDOP"
GPSSpeedRef = "GPSSpeedRef"
GPSSpeed = "GPSSpeed"
GPSTrackRef = "GPSTrackRef"
GPSTrack = "GPSTrack"
GPSImgDirectionRef = "GPSImgDirectionRef"
GPSImgDirection = "GPSImgDirection"
GPSMapDatum = "GPSMapDatum"
GPSDestLatitudeRef = "GPSDestLatitudeRef"
GPSDestLatitude = "GPSDestLatitude"
GPSDestLongitudeRef = "GPSDestLongitudeRef"
GPSDestLongitude = "GPSDestLongitude"
GPSDestBearingRef = "GPSDestBearingRef"
GPSDestBearing = "GPSDestBearing"
GPSDestDistanceRef = "GPSDestDistanceRef"
GPSDestDistance = "GPSDestDistance"
GPSProcessingMethod = "GPSProcessingMethod"
GPSAreaInformation = "GPSAreaInformation"
GPSDateStamp = "GPSDateStamp"
GPSDifferential = "GPSDifferential"
)
// interoperability fields
const (
InteroperabilityIndex FieldName = "InteroperabilityIndex"
)
var exifFields = map[uint16]FieldName{
/////////////////////////////////////
////////// IFD 0 ////////////////////
/////////////////////////////////////
// image data structure for the thumbnail
0x0100: ImageWidth,
0x0101: ImageLength,
0x0102: BitsPerSample,
0x0103: Compression,
0x0106: PhotometricInterpretation,
0x0112: Orientation,
0x0115: SamplesPerPixel,
0x011C: PlanarConfiguration,
0x0212: YCbCrSubSampling,
0x0213: YCbCrPositioning,
0x011A: XResolution,
0x011B: YResolution,
0x0128: ResolutionUnit,
// Other tags
0x0132: DateTime,
0x010E: ImageDescription,
0x010F: Make,
0x0110: Model,
0x0131: Software,
0x013B: Artist,
0x8298: Copyright,
// private tags
exifPointer: ExifIFDPointer,
/////////////////////////////////////
////////// Exif sub IFD /////////////
/////////////////////////////////////
gpsPointer: GPSInfoIFDPointer,
interopPointer: InteroperabilityIFDPointer,
0x9000: ExifVersion,
0xA000: FlashpixVersion,
0xA001: ColorSpace,
0x9101: ComponentsConfiguration,
0x9102: CompressedBitsPerPixel,
0xA002: PixelXDimension,
0xA003: PixelYDimension,
0x927C: MakerNote,
0x9286: UserComment,
0xA004: RelatedSoundFile,
0x9003: DateTimeOriginal,
0x9004: DateTimeDigitized,
0x9290: SubSecTime,
0x9291: SubSecTimeOriginal,
0x9292: SubSecTimeDigitized,
0xA420: ImageUniqueID,
// picture conditions
0x829A: ExposureTime,
0x829D: FNumber,
0x8822: ExposureProgram,
0x8824: SpectralSensitivity,
0x8827: ISOSpeedRatings,
0x8828: OECF,
0x9201: ShutterSpeedValue,
0x9202: ApertureValue,
0x9203: BrightnessValue,
0x9204: ExposureBiasValue,
0x9205: MaxApertureValue,
0x9206: SubjectDistance,
0x9207: MeteringMode,
0x9208: LightSource,
0x9209: Flash,
0x920A: FocalLength,
0x9214: SubjectArea,
0xA20B: FlashEnergy,
0xA20C: SpatialFrequencyResponse,
0xA20E: FocalPlaneXResolution,
0xA20F: FocalPlaneYResolution,
0xA210: FocalPlaneResolutionUnit,
0xA214: SubjectLocation,
0xA215: ExposureIndex,
0xA217: SensingMethod,
0xA300: FileSource,
0xA301: SceneType,
0xA302: CFAPattern,
0xA401: CustomRendered,
0xA402: ExposureMode,
0xA403: WhiteBalance,
0xA404: DigitalZoomRatio,
0xA405: FocalLengthIn35mmFilm,
0xA406: SceneCaptureType,
0xA407: GainControl,
0xA408: Contrast,
0xA409: Saturation,
0xA40A: Sharpness,
0xA40B: DeviceSettingDescription,
0xA40C: SubjectDistanceRange,
0xA433: LensMake,
0xA434: LensModel,
}
var gpsFields = map[uint16]FieldName{
/////////////////////////////////////
//// GPS sub-IFD ////////////////////
/////////////////////////////////////
0x0: GPSVersionID,
0x1: GPSLatitudeRef,
0x2: GPSLatitude,
0x3: GPSLongitudeRef,
0x4: GPSLongitude,
0x5: GPSAltitudeRef,
0x6: GPSAltitude,
0x7: GPSTimeStamp,
0x8: GPSSatelites,
0x9: GPSStatus,
0xA: GPSMeasureMode,
0xB: GPSDOP,
0xC: GPSSpeedRef,
0xD: GPSSpeed,
0xE: GPSTrackRef,
0xF: GPSTrack,
0x10: GPSImgDirectionRef,
0x11: GPSImgDirection,
0x12: GPSMapDatum,
0x13: GPSDestLatitudeRef,
0x14: GPSDestLatitude,
0x15: GPSDestLongitudeRef,
0x16: GPSDestLongitude,
0x17: GPSDestBearingRef,
0x18: GPSDestBearing,
0x19: GPSDestDistanceRef,
0x1A: GPSDestDistance,
0x1B: GPSProcessingMethod,
0x1C: GPSAreaInformation,
0x1D: GPSDateStamp,
0x1E: GPSDifferential,
}
var interopFields = map[uint16]FieldName{
/////////////////////////////////////
//// Interoperability sub-IFD ///////
/////////////////////////////////////
0x1: InteroperabilityIndex,
}
var thumbnailFields = map[uint16]FieldName{
0x0201: ThumbJPEGInterchangeFormat,
0x0202: ThumbJPEGInterchangeFormatLength,
}
+79
View File
@@ -0,0 +1,79 @@
// +build ignore
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/rwcarlsen/goexif/exif"
"github.com/rwcarlsen/goexif/tiff"
)
func main() {
flag.Parse()
fname := flag.Arg(0)
dst, err := os.Create(fname)
if err != nil {
log.Fatal(err)
}
defer dst.Close()
dir, err := os.Open("samples")
if err != nil {
log.Fatal(err)
}
defer dir.Close()
names, err := dir.Readdirnames(0)
if err != nil {
log.Fatal(err)
}
for i, name := range names {
names[i] = filepath.Join("samples", name)
}
makeExpected(names, dst)
}
func makeExpected(files []string, w io.Writer) {
fmt.Fprintf(w, "package exif\n\n")
fmt.Fprintf(w, "var regressExpected = map[string]map[FieldName]string{\n")
for _, name := range files {
f, err := os.Open(name)
if err != nil {
continue
}
x, err := exif.Decode(f)
if err != nil {
f.Close()
continue
}
fmt.Fprintf(w, "\"%v\": map[FieldName]string{\n", filepath.Base(name))
x.Walk(&regresswalk{w})
fmt.Fprintf(w, "},\n")
f.Close()
}
fmt.Fprintf(w, "}")
}
type regresswalk struct {
wr io.Writer
}
func (w *regresswalk) Walk(name exif.FieldName, tag *tiff.Tag) error {
if strings.HasPrefix(string(name), exif.UnknownPrefix) {
fmt.Fprintf(w.wr, "\"%v\": `%v`,\n", name, tag.String())
} else {
fmt.Fprintf(w.wr, "%v: `%v`,\n", name, tag.String())
}
return nil
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.
+438
View File
@@ -0,0 +1,438 @@
package tiff
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
"strings"
"unicode"
"unicode/utf8"
)
// Format specifies the Go type equivalent used to represent the basic
// tiff data types.
type Format int
const (
IntVal Format = iota
FloatVal
RatVal
StringVal
UndefVal
OtherVal
)
var ErrShortReadTagValue = errors.New("tiff: short read of tag value")
var formatNames = map[Format]string{
IntVal: "int",
FloatVal: "float",
RatVal: "rational",
StringVal: "string",
UndefVal: "undefined",
OtherVal: "other",
}
// DataType represents the basic tiff tag data types.
type DataType uint16
const (
DTByte DataType = 1
DTAscii = 2
DTShort = 3
DTLong = 4
DTRational = 5
DTSByte = 6
DTUndefined = 7
DTSShort = 8
DTSLong = 9
DTSRational = 10
DTFloat = 11
DTDouble = 12
)
var typeNames = map[DataType]string{
DTByte: "byte",
DTAscii: "ascii",
DTShort: "short",
DTLong: "long",
DTRational: "rational",
DTSByte: "signed byte",
DTUndefined: "undefined",
DTSShort: "signed short",
DTSLong: "signed long",
DTSRational: "signed rational",
DTFloat: "float",
DTDouble: "double",
}
// typeSize specifies the size in bytes of each type.
var typeSize = map[DataType]uint32{
DTByte: 1,
DTAscii: 1,
DTShort: 2,
DTLong: 4,
DTRational: 8,
DTSByte: 1,
DTUndefined: 1,
DTSShort: 2,
DTSLong: 4,
DTSRational: 8,
DTFloat: 4,
DTDouble: 8,
}
// Tag reflects the parsed content of a tiff IFD tag.
type Tag struct {
// Id is the 2-byte tiff tag identifier.
Id uint16
// Type is an integer (1 through 12) indicating the tag value's data type.
Type DataType
// Count is the number of type Type stored in the tag's value (i.e. the
// tag's value is an array of type Type and length Count).
Count uint32
// Val holds the bytes that represent the tag's value.
Val []byte
// ValOffset holds byte offset of the tag value w.r.t. the beginning of the
// reader it was decoded from. Zero if the tag value fit inside the offset
// field.
ValOffset uint32
order binary.ByteOrder
intVals []int64
floatVals []float64
ratVals [][]int64
strVal string
format Format
}
// DecodeTag parses a tiff-encoded IFD tag from r and returns a Tag object. The
// first read from r should be the first byte of the tag. ReadAt offsets should
// generally be relative to the beginning of the tiff structure (not relative
// to the beginning of the tag).
func DecodeTag(r ReadAtReader, order binary.ByteOrder) (*Tag, error) {
t := new(Tag)
t.order = order
err := binary.Read(r, order, &t.Id)
if err != nil {
return nil, errors.New("tiff: tag id read failed: " + err.Error())
}
err = binary.Read(r, order, &t.Type)
if err != nil {
return nil, errors.New("tiff: tag type read failed: " + err.Error())
}
err = binary.Read(r, order, &t.Count)
if err != nil {
return nil, errors.New("tiff: tag component count read failed: " + err.Error())
}
// There seems to be a relatively common corrupt tag which has a Count of
// MaxUint32. This is probably not a valid value, so return early.
if t.Count == 1<<32-1 {
return t, errors.New("invalid Count offset in tag")
}
valLen := typeSize[t.Type] * t.Count
if valLen == 0 {
return t, errors.New("zero length tag value")
}
if valLen > 4 {
binary.Read(r, order, &t.ValOffset)
// Use a bytes.Buffer so we don't allocate a huge slice if the tag
// is corrupt.
var buff bytes.Buffer
sr := io.NewSectionReader(r, int64(t.ValOffset), int64(valLen))
n, err := io.Copy(&buff, sr)
if err != nil {
return t, errors.New("tiff: tag value read failed: " + err.Error())
} else if n != int64(valLen) {
return t, ErrShortReadTagValue
}
t.Val = buff.Bytes()
} else {
val := make([]byte, valLen)
if _, err = io.ReadFull(r, val); err != nil {
return t, errors.New("tiff: tag offset read failed: " + err.Error())
}
// ignore padding.
if _, err = io.ReadFull(r, make([]byte, 4-valLen)); err != nil {
return t, errors.New("tiff: tag offset read failed: " + err.Error())
}
t.Val = val
}
return t, t.convertVals()
}
func (t *Tag) convertVals() error {
r := bytes.NewReader(t.Val)
switch t.Type {
case DTAscii:
if len(t.Val) > 0 {
t.strVal = string(t.Val[:len(t.Val)-1]) // ignore the last byte (NULL).
}
case DTByte:
var v uint8
t.intVals = make([]int64, int(t.Count))
for i := range t.intVals {
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.intVals[i] = int64(v)
}
case DTShort:
var v uint16
t.intVals = make([]int64, int(t.Count))
for i := range t.intVals {
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.intVals[i] = int64(v)
}
case DTLong:
var v uint32
t.intVals = make([]int64, int(t.Count))
for i := range t.intVals {
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.intVals[i] = int64(v)
}
case DTSByte:
var v int8
t.intVals = make([]int64, int(t.Count))
for i := range t.intVals {
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.intVals[i] = int64(v)
}
case DTSShort:
var v int16
t.intVals = make([]int64, int(t.Count))
for i := range t.intVals {
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.intVals[i] = int64(v)
}
case DTSLong:
var v int32
t.intVals = make([]int64, int(t.Count))
for i := range t.intVals {
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.intVals[i] = int64(v)
}
case DTRational:
t.ratVals = make([][]int64, int(t.Count))
for i := range t.ratVals {
var n, d uint32
err := binary.Read(r, t.order, &n)
if err != nil {
return err
}
err = binary.Read(r, t.order, &d)
if err != nil {
return err
}
t.ratVals[i] = []int64{int64(n), int64(d)}
}
case DTSRational:
t.ratVals = make([][]int64, int(t.Count))
for i := range t.ratVals {
var n, d int32
err := binary.Read(r, t.order, &n)
if err != nil {
return err
}
err = binary.Read(r, t.order, &d)
if err != nil {
return err
}
t.ratVals[i] = []int64{int64(n), int64(d)}
}
case DTFloat: // float32
t.floatVals = make([]float64, int(t.Count))
for i := range t.floatVals {
var v float32
err := binary.Read(r, t.order, &v)
if err != nil {
return err
}
t.floatVals[i] = float64(v)
}
case DTDouble:
t.floatVals = make([]float64, int(t.Count))
for i := range t.floatVals {
var u float64
err := binary.Read(r, t.order, &u)
if err != nil {
return err
}
t.floatVals[i] = u
}
}
switch t.Type {
case DTByte, DTShort, DTLong, DTSByte, DTSShort, DTSLong:
t.format = IntVal
case DTRational, DTSRational:
t.format = RatVal
case DTFloat, DTDouble:
t.format = FloatVal
case DTAscii:
t.format = StringVal
case DTUndefined:
t.format = UndefVal
default:
t.format = OtherVal
}
return nil
}
// Format returns a value indicating which method can be called to retrieve the
// tag's value properly typed (e.g. integer, rational, etc.).
func (t *Tag) Format() Format { return t.format }
func (t *Tag) typeErr(to Format) error {
return &wrongFmtErr{typeNames[t.Type], formatNames[to]}
}
// Rat returns the tag's i'th value as a rational number. It returns a nil and
// an error if this tag's Format is not RatVal. It panics for zero deminators
// or if i is out of range.
func (t *Tag) Rat(i int) (*big.Rat, error) {
n, d, err := t.Rat2(i)
if err != nil {
return nil, err
}
return big.NewRat(n, d), nil
}
// Rat2 returns the tag's i'th value as a rational number represented by a
// numerator-denominator pair. It returns an error if the tag's Format is not
// RatVal. It panics if i is out of range.
func (t *Tag) Rat2(i int) (num, den int64, err error) {
if t.format != RatVal {
return 0, 0, t.typeErr(RatVal)
}
return t.ratVals[i][0], t.ratVals[i][1], nil
}
// Int64 returns the tag's i'th value as an integer. It returns an error if the
// tag's Format is not IntVal. It panics if i is out of range.
func (t *Tag) Int64(i int) (int64, error) {
if t.format != IntVal {
return 0, t.typeErr(IntVal)
}
return t.intVals[i], nil
}
// Int returns the tag's i'th value as an integer. It returns an error if the
// tag's Format is not IntVal. It panics if i is out of range.
func (t *Tag) Int(i int) (int, error) {
if t.format != IntVal {
return 0, t.typeErr(IntVal)
}
return int(t.intVals[i]), nil
}
// Float returns the tag's i'th value as a float. It returns an error if the
// tag's Format is not IntVal. It panics if i is out of range.
func (t *Tag) Float(i int) (float64, error) {
if t.format != FloatVal {
return 0, t.typeErr(FloatVal)
}
return t.floatVals[i], nil
}
// StringVal returns the tag's value as a string. It returns an error if the
// tag's Format is not StringVal. It panics if i is out of range.
func (t *Tag) StringVal() (string, error) {
if t.format != StringVal {
return "", t.typeErr(StringVal)
}
return t.strVal, nil
}
// String returns a nicely formatted version of the tag.
func (t *Tag) String() string {
data, err := t.MarshalJSON()
if err != nil {
return "ERROR: " + err.Error()
}
if t.Count == 1 {
return strings.Trim(fmt.Sprintf("%s", data), "[]")
}
return fmt.Sprintf("%s", data)
}
func (t *Tag) MarshalJSON() ([]byte, error) {
switch t.format {
case StringVal, UndefVal:
return nullString(t.Val), nil
case OtherVal:
return []byte(fmt.Sprintf("unknown tag type '%v'", t.Type)), nil
}
rv := []string{}
for i := 0; i < int(t.Count); i++ {
switch t.format {
case RatVal:
n, d, _ := t.Rat2(i)
rv = append(rv, fmt.Sprintf(`"%v/%v"`, n, d))
case FloatVal:
v, _ := t.Float(i)
rv = append(rv, fmt.Sprintf("%v", v))
case IntVal:
v, _ := t.Int(i)
rv = append(rv, fmt.Sprintf("%v", v))
}
}
return []byte(fmt.Sprintf(`[%s]`, strings.Join(rv, ","))), nil
}
func nullString(in []byte) []byte {
rv := bytes.Buffer{}
rv.WriteByte('"')
for _, b := range in {
if unicode.IsPrint(rune(b)) {
rv.WriteByte(b)
}
}
rv.WriteByte('"')
rvb := rv.Bytes()
if utf8.Valid(rvb) {
return rvb
}
return []byte(`""`)
}
type wrongFmtErr struct {
From, To string
}
func (e *wrongFmtErr) Error() string {
return fmt.Sprintf("cannot convert tag type '%v' into '%v'", e.From, e.To)
}
+153
View File
@@ -0,0 +1,153 @@
// Package tiff implements TIFF decoding as defined in TIFF 6.0 specification at
// http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
package tiff
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
)
// ReadAtReader is used when decoding Tiff tags and directories
type ReadAtReader interface {
io.Reader
io.ReaderAt
}
// Tiff provides access to a decoded tiff data structure.
type Tiff struct {
// Dirs is an ordered slice of the tiff's Image File Directories (IFDs).
// The IFD at index 0 is IFD0.
Dirs []*Dir
// The tiff's byte-encoding (i.e. big/little endian).
Order binary.ByteOrder
}
// Decode parses tiff-encoded data from r and returns a Tiff struct that
// reflects the structure and content of the tiff data. The first read from r
// should be the first byte of the tiff-encoded data and not necessarily the
// first byte of an os.File object.
func Decode(r io.Reader) (*Tiff, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.New("tiff: could not read data")
}
buf := bytes.NewReader(data)
t := new(Tiff)
// read byte order
bo := make([]byte, 2)
if _, err = io.ReadFull(buf, bo); err != nil {
return nil, errors.New("tiff: could not read tiff byte order")
}
if string(bo) == "II" {
t.Order = binary.LittleEndian
} else if string(bo) == "MM" {
t.Order = binary.BigEndian
} else {
return nil, errors.New("tiff: could not read tiff byte order")
}
// check for special tiff marker
var sp int16
err = binary.Read(buf, t.Order, &sp)
if err != nil || 42 != sp {
return nil, errors.New("tiff: could not find special tiff marker")
}
// load offset to first IFD
var offset int32
err = binary.Read(buf, t.Order, &offset)
if err != nil {
return nil, errors.New("tiff: could not read offset to first IFD")
}
// load IFD's
var d *Dir
prev := offset
for offset != 0 {
// seek to offset
_, err := buf.Seek(int64(offset), 0)
if err != nil {
return nil, errors.New("tiff: seek to IFD failed")
}
if buf.Len() == 0 {
return nil, errors.New("tiff: seek offset after EOF")
}
// load the dir
d, offset, err = DecodeDir(buf, t.Order)
if err != nil {
return nil, err
}
if offset == prev {
return nil, errors.New("tiff: recursive IFD")
}
prev = offset
t.Dirs = append(t.Dirs, d)
}
return t, nil
}
func (tf *Tiff) String() string {
var buf bytes.Buffer
fmt.Fprint(&buf, "Tiff{")
for _, d := range tf.Dirs {
fmt.Fprintf(&buf, "%s, ", d.String())
}
fmt.Fprintf(&buf, "}")
return buf.String()
}
// Dir provides access to the parsed content of a tiff Image File Directory (IFD).
type Dir struct {
Tags []*Tag
}
// DecodeDir parses a tiff-encoded IFD from r and returns a Dir object. offset
// is the offset to the next IFD. The first read from r should be at the first
// byte of the IFD. ReadAt offsets should generally be relative to the
// beginning of the tiff structure (not relative to the beginning of the IFD).
func DecodeDir(r ReadAtReader, order binary.ByteOrder) (d *Dir, offset int32, err error) {
d = new(Dir)
// get num of tags in ifd
var nTags int16
err = binary.Read(r, order, &nTags)
if err != nil {
return nil, 0, errors.New("tiff: failed to read IFD tag count: " + err.Error())
}
// load tags
for n := 0; n < int(nTags); n++ {
t, err := DecodeTag(r, order)
if err != nil {
return nil, 0, err
}
d.Tags = append(d.Tags, t)
}
// get offset to next ifd
err = binary.Read(r, order, &offset)
if err != nil {
return nil, 0, errors.New("tiff: falied to read offset to next IFD: " + err.Error())
}
return d, offset, nil
}
func (d *Dir) String() string {
s := "Dir{"
for _, t := range d.Tags {
s += t.String() + ", "
}
return s + "}"
}
+19
View File
@@ -0,0 +1,19 @@
{
"comment": "",
"ignore": "test",
"package": [
{
"checksumSHA1": "Q68FxXX04PtPDIG7C1RlSDhx/ko=",
"path": "github.com/rwcarlsen/goexif/exif",
"revision": "709fab3d192d7c62f86043caff1e7e3fb0f42bd8",
"revisionTime": "2015-05-20T14:06:47Z"
},
{
"checksumSHA1": "0+tTLlssYWyGuq+vQs4IiPIXJW4=",
"path": "github.com/rwcarlsen/goexif/tiff",
"revision": "709fab3d192d7c62f86043caff1e7e3fb0f42bd8",
"revisionTime": "2015-05-20T14:06:47Z"
}
],
"rootPath": "mcquay.me/arrange"
}
-123
View File
@@ -1,123 +0,0 @@
package arrange
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
)
// Problem is something Verify found wrong with a file in the content store.
type Problem struct {
Path string
Kind string // "corrupt", "orphan", "stale", or "error"
Err error
}
func (p Problem) Error() string {
if p.Err != nil {
return fmt.Sprintf("%s: %q: %v", p.Kind, p.Path, p.Err)
}
return fmt.Sprintf("%s: %q", p.Kind, p.Path)
}
// Verify rehashes every file in root's content store with workers goroutines
// and reports any whose hash doesn't match its name (corrupt), that nothing in
// the date tree links to (orphan), or that a crashed run left behind (stale).
// It only reads. The returned func reports how many files were checked once
// the channel is drained.
func Verify(root string, workers int) (<-chan Problem, func() int) {
paths := make(chan string)
out := make(chan Problem)
var checked int
var mu sync.Mutex
go func() {
err := filepath.WalkDir(filepath.Join(root, "content"), func(path string, d fs.DirEntry, err error) error {
if err != nil {
out <- Problem{Path: path, Kind: "error", Err: err}
return nil
}
if d.IsDir() {
return nil
}
if strings.HasPrefix(d.Name(), ".tmp-") {
out <- Problem{Path: path, Kind: "stale"}
return nil
}
paths <- path
return nil
})
if err != nil {
out <- Problem{Path: root, Kind: "error", Err: err}
}
close(paths)
}()
var wg sync.WaitGroup
wg.Add(workers)
for w := 0; w < workers; w++ {
go func() {
defer wg.Done()
for path := range paths {
if p, ok := verifyFile(path); !ok {
out <- p
}
mu.Lock()
checked++
mu.Unlock()
}
}()
}
go func() {
wg.Wait()
close(out)
}()
return out, func() int {
mu.Lock()
defer mu.Unlock()
return checked
}
}
// verifyFile checks one content file; ok is false if p describes a problem.
func verifyFile(path string) (p Problem, ok bool) {
p.Path = path
base := filepath.Base(path)
hexname := filepath.Base(filepath.Dir(path)) + strings.TrimSuffix(base, filepath.Ext(base))
newHash := HashByName(hexname)
if newHash == nil {
p.Kind, p.Err = "error", fmt.Errorf("not a content address")
return p, false
}
f, err := os.Open(path)
if err != nil {
p.Kind, p.Err = "error", err
return p, false
}
defer f.Close()
h := newHash()
if _, err := io.Copy(h, f); err != nil {
p.Kind, p.Err = "error", err
return p, false
}
if got := fmt.Sprintf("%x", h.Sum(nil)); got != hexname {
p.Kind, p.Err = "corrupt", fmt.Errorf("contents hash to %s", got)
return p, false
}
if fi, err := f.Stat(); err == nil {
if st, ok := fi.Sys().(*syscall.Stat_t); ok && st.Nlink < 2 {
p.Kind = "orphan"
return p, false
}
}
return p, true
}