File: id3pic.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2025 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.Stderr.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("\x1b[31m")
  91     os.Stderr.WriteString(msg)
  92     os.Stderr.WriteString("\x1b[0m\n")
  93 }
  94 
  95 func run(w io.Writer, name string) error {
  96     if name == `-` {
  97         return id3pic(w, bufio.NewReader(os.Stdin))
  98     }
  99 
 100     f, err := os.Open(name)
 101     if err != nil {
 102         return errors.New(`can't read from file named "` + name + `"`)
 103     }
 104     defer f.Close()
 105 
 106     return id3pic(w, bufio.NewReader(f))
 107 }
 108 
 109 // isActualError is to figure out whether not to ignore an error, and thus
 110 // show it as an error message
 111 func isActualError(err error) bool {
 112     return err != nil && err != io.EOF && err != errNoMoreOutput
 113 }
 114 
 115 func match(r *bufio.Reader, what []byte) bool {
 116     for _, v := range what {
 117         b, err := r.ReadByte()
 118         if b != v || err != nil {
 119             return false
 120         }
 121     }
 122     return true
 123 }
 124 
 125 func id3pic(w io.Writer, r *bufio.Reader) error {
 126     // match the ID3 mark
 127     for {
 128         b, err := r.ReadByte()
 129         if err == io.EOF {
 130             return errNoThumb
 131         }
 132         if err != nil {
 133             return err
 134         }
 135 
 136         if b == 'I' && match(r, []byte{'D', '3'}) {
 137             break
 138         }
 139     }
 140 
 141     for {
 142         b, err := r.ReadByte()
 143         if err == io.EOF {
 144             return errNoThumb
 145         }
 146         if err != nil {
 147             return err
 148         }
 149 
 150         // handle APIC-type chunks
 151         if b == 'A' && match(r, []byte{'P', 'I', 'C'}) {
 152             return handleAPIC(w, r)
 153         }
 154     }
 155 }
 156 
 157 func handleAPIC(w io.Writer, r *bufio.Reader) error {
 158     // section-size seems stored as 4 big-endian bytes
 159     var size uint32
 160     err := binary.Read(r, binary.BigEndian, &size)
 161     if err != nil {
 162         return err
 163     }
 164 
 165     n, err := skipThumbnailTypeAPIC(r)
 166     if err != nil {
 167         return err
 168     }
 169 
 170     _, err = io.Copy(w, io.LimitReader(r, int64(int(size)-n)))
 171     return err
 172 }
 173 
 174 func skipThumbnailTypeAPIC(r *bufio.Reader) (skipped int, err error) {
 175     m, err := r.Discard(2)
 176     if err != nil || m != 2 {
 177         return -1, errors.New(`failed to sync APIC flags`)
 178     }
 179     skipped += m
 180 
 181     m, err = r.Discard(1)
 182     if err != nil || m != 1 {
 183         return -1, errors.New(`failed to sync APIC text-encoding`)
 184     }
 185     skipped += m
 186 
 187     junk, err := r.ReadSlice(0)
 188     if err != nil {
 189         return -1, errors.New(`failed to sync to APIC thumbnail MIME-type`)
 190     }
 191     skipped += len(junk)
 192 
 193     m, err = r.Discard(1)
 194     if err != nil || m != 1 {
 195         return -1, errors.New(`failed to sync APIC picture type`)
 196     }
 197     skipped += m
 198 
 199     junk, err = r.ReadSlice(0)
 200     if err != nil {
 201         return -1, errors.New(`failed to sync to APIC thumbnail description`)
 202     }
 203     skipped += len(junk)
 204 
 205     return skipped, nil
 206 }