File: id3pic.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2026 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath id3pic.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bufio"
  36     "encoding/binary"
  37     "errors"
  38     "io"
  39     "os"
  40 )
  41 
  42 const info = `
  43 id3pic [options...] [file...]
  44 
  45 Extract picture/thumbnail bytes from ID3/MP3 metadata, if available.
  46 
  47 All (optional) leading options start with either single or double-dash:
  48 
  49     -h          show this help message
  50     -help       show this help message
  51 `
  52 
  53 // errNoMoreOutput is a dummy error whose message is ignored, and which
  54 // causes the app to quit immediately and successfully
  55 var errNoMoreOutput = errors.New(`no more output`)
  56 
  57 // errNoThumb is a generic error to handle lack of thumbnails, in case no
  58 // picture-metadata-starters are found at all
  59 var errNoThumb = errors.New(`no thumbnail data found`)
  60 
  61 // errInvalidPIC is a generic error for invalid PIC-format pics
  62 var errInvalidPIC = errors.New(`invalid PIC-format embedded thumbnail`)
  63 
  64 func main() {
  65     if len(os.Args) > 1 {
  66         switch os.Args[1] {
  67         case `-h`, `--h`, `-help`, `--help`:
  68             os.Stdout.WriteString(info[1:])
  69             return
  70         }
  71     }
  72 
  73     if len(os.Args) > 2 {
  74         showError(`can only handle 1 file`)
  75         os.Exit(1)
  76     }
  77 
  78     name := `-`
  79     if len(os.Args) > 1 {
  80         name = os.Args[1]
  81     }
  82 
  83     if err := run(os.Stdout, name); isActualError(err) {
  84         showError(err.Error())
  85         os.Exit(1)
  86     }
  87 }
  88 
  89 func showError(msg string) {
  90     os.Stderr.WriteString(msg)
  91     os.Stderr.WriteString("\n")
  92 }
  93 
  94 func run(w io.Writer, name string) error {
  95     if name == `-` {
  96         return id3pic(w, bufio.NewReader(os.Stdin))
  97     }
  98 
  99     f, err := os.Open(name)
 100     if err != nil {
 101         return errors.New(`can't read from file named "` + name + `"`)
 102     }
 103     defer f.Close()
 104 
 105     return id3pic(w, bufio.NewReader(f))
 106 }
 107 
 108 // isActualError is to figure out whether not to ignore an error, and thus
 109 // show it as an error message
 110 func isActualError(err error) bool {
 111     return err != nil && err != io.EOF && err != errNoMoreOutput
 112 }
 113 
 114 func match(r *bufio.Reader, what []byte) bool {
 115     for _, v := range what {
 116         b, err := r.ReadByte()
 117         if b != v || err != nil {
 118             return false
 119         }
 120     }
 121     return true
 122 }
 123 
 124 func id3pic(w io.Writer, r *bufio.Reader) error {
 125     // match the ID3 mark
 126     for {
 127         b, err := r.ReadByte()
 128         if err == io.EOF {
 129             return errNoThumb
 130         }
 131         if err != nil {
 132             return err
 133         }
 134 
 135         if b == 'I' && match(r, []byte{'D', '3'}) {
 136             break
 137         }
 138     }
 139 
 140     for {
 141         b, err := r.ReadByte()
 142         if err == io.EOF {
 143             return errNoThumb
 144         }
 145         if err != nil {
 146             return err
 147         }
 148 
 149         // handle APIC-type chunks
 150         if b == 'A' && match(r, []byte{'P', 'I', 'C'}) {
 151             return handleAPIC(w, r)
 152         }
 153     }
 154 }
 155 
 156 func handleAPIC(w io.Writer, r *bufio.Reader) error {
 157     // section-size seems stored as 4 big-endian bytes
 158     var size uint32
 159     err := binary.Read(r, binary.BigEndian, &size)
 160     if err != nil {
 161         return err
 162     }
 163 
 164     n, err := skipThumbnailTypeAPIC(r)
 165     if err != nil {
 166         return err
 167     }
 168 
 169     _, err = io.Copy(w, io.LimitReader(r, int64(int(size)-n)))
 170     return err
 171 }
 172 
 173 func skipThumbnailTypeAPIC(r *bufio.Reader) (skipped int, err error) {
 174     m, err := r.Discard(2)
 175     if err != nil || m != 2 {
 176         return -1, errors.New(`failed to sync APIC flags`)
 177     }
 178     skipped += m
 179 
 180     m, err = r.Discard(1)
 181     if err != nil || m != 1 {
 182         return -1, errors.New(`failed to sync APIC text-encoding`)
 183     }
 184     skipped += m
 185 
 186     junk, err := r.ReadSlice(0)
 187     if err != nil {
 188         return -1, errors.New(`failed to sync to APIC thumbnail MIME-type`)
 189     }
 190     skipped += len(junk)
 191 
 192     m, err = r.Discard(1)
 193     if err != nil || m != 1 {
 194         return -1, errors.New(`failed to sync APIC picture type`)
 195     }
 196     skipped += m
 197 
 198     junk, err = r.ReadSlice(0)
 199     if err != nil {
 200         return -1, errors.New(`failed to sync to APIC thumbnail description`)
 201     }
 202     skipped += len(junk)
 203 
 204     return skipped, nil
 205 }