3 # Copyright © 2019 Nick Bowler
5 # Generate thumbnails for cover art retrieved from MPD.
7 # License GPLv3+: GNU General Public License version 3 or any later version.
8 # This is free software: you are free to change and redistribute it.
9 # There is NO WARRANTY, to the extent permitted by law.
11 : "${XDG_CACHE_HOME=$HOME/.cache}"
12 : "${THUMBNAILDIR=$XDG_CACHE_HOME/mpdthumb}"
14 # Try to find mpdexec...
17 */*) self=$PWD/${0#./} ;;
18 *) self=`command -v $0` ;;
22 if command -v "$owndir/mpdexec.pl" >/dev/null; then
23 : "${MPDEXEC=$owndir/mpdexec.pl}"
24 elif command -v mpdexec.pl >/dev/null; then
25 : "${MPDEXEC=mpdexec.pl}"
27 : "${MPDEXEC=mpdexec}"
30 if command -v gm >/dev/null; then
31 : "${CONVERT=gm convert}"
33 : "${CONVERT=convert}"
41 if test ${lastarg:+y}; then
47 --size=*) size=${arg#--size=} ;;
49 --size) lastarg=$arg ;;
51 -*) printf '%s: unrecognized argument: %s\n' "$0" "$arg" 1>&2; exit 1 ;;
52 *) set x "$@" "$arg"; shift
58 w=${size%x*} h=${size#*x}
59 if expr "$w$h" : '[0-9][0-9]*$' >/dev/null; then :; else
60 printf '%s: invalid --size setting: %s\n' "$0" "$size" 1>&2
65 printf 'usage: %s [options] file [file ...]\n' "$0" 1>&2
70 exec 3>"$tmp" 4<"$tmp"
74 exec 5>"$tmp" 6<"$tmp"
79 shift; set x "$@" "$arg"; shift
81 printf '%s\n' "$arg" | sed '/[ \\"]/ {
85 s/.*/albumart & 2147483647/' >&3;
88 <&4 $MPDEXEC --ignore-errors >&5 2>&1 || exit
89 while read a b <&6; do
92 ACK) echo; shift || exit; continue ;;
96 # We combine the filename and the size to compute the cache key and
97 # hope this suffices to detect stale entries. Unfortunately MPD does
98 # not currently give us the modified date which would be more useful...
99 file=$1; shift || exit
100 cache_id=`printf 'MPD:%s:%s' "$file" "$b" | md5sum`
101 cache_id=${cache_id:+${cache_id%% *}_$size.png}
103 if test ! -f "$THUMBNAILDIR/$cache_id"; then
104 if test ! -f "$THUMBNAILDIR/CACHEDIR.TAG"; then
105 mkdir -p "$THUMBNAILDIR"
106 { cat >"$THUMBNAILDIR/CACHEDIR.TAG~" || exit; } <<'EOF'
107 Signature: 8a477f597d28d172789f06886806bc55
109 mv -f "$THUMBNAILDIR/CACHEDIR.TAG~" "$THUMBNAILDIR/CACHEDIR.TAG"
112 # Not cached, retrieve the entire image
113 $MPDEXEC --binary --download albumart "$file" >&3 || exit
114 <&4 $CONVERT -scale "$size" - "$THUMBNAILDIR/tmp.$cache_id" ||
115 { rc=$? rm -f "$THUMBNAILDIR/tmp.$cache_id"; exit $rc; }
116 mv -f "$THUMBNAILDIR/tmp.$cache_id" "$THUMBNAILDIR/$cache_id"
119 printf '%s\n' "$THUMBNAILDIR/$cache_id"