aboutsummaryrefslogtreecommitdiff
path: root/music/export.sh
blob: 6f537931e19aa63058fdb1e4e59a5fe50e68390c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/bin/sh

set -eu -o pipefail

# I use this script to export my flac collection to a portable device,
# which happens to require smaller embedded album art.

MUSIC_DIR="/nfs/media/music/flac"
ARTSIZE=${ARTSIZE:-320}

sanitize(){
  echo "$1" | tr -Cd 'A-Za-z0-9 _-'
}

if [ $# -ne 1 ]; then
  echo 'usage: export.sh DST' 1>&2
  exit 1
fi
DEST_DIR="$1"

find "$MUSIC_DIR" -iname '*.flac' -type f -print | while read -r file; do
  track=$(exiftool -s3 -TrackNumber "$file")
  title=$(exiftool -s3 -Title "$file")
  album=$(exiftool -s3 -Album "$file")
  artist=$(exiftool -s3 -AlbumArtist "$file")
  artist=${artist:-$(exiftool -s3 -Artist "$file")}

  if [ -z "$artist" ]; then
    echo "$file has no artist metadata, skipping" 1>&2
    continue
  fi

  if [ -z "$album" ]; then
    echo "$file has no album metadata, skipping" 1>&2
    continue
  fi

  if [ -z "$title" ]; then
    echo "$file has no title metadata, skipping" 1>&2
    continue
  fi

  if [ -z "$track" ]; then
    echo "$file has no track metadata, skipping" 1>&2
    continue
  fi

  subpath="$(sanitize "$artist")/$(sanitize "$album")"
  basename="$(printf '%03d' "$(expr "$track" + 0)") $(sanitize "$title")"

  mkdir -p "${DEST_DIR}/${subpath}"

  if [ ! -e "${DEST_DIR}/${subpath}/${basename}.flac" ]; then
    echo "$artist / $album / $title"
    ffmpeg -n -nostdin -loglevel error -i "$file" -map 0:a:0 -map 0:v:0 -filter:v "scale=w=${ARTSIZE}:h=${ARTSIZE},format=yuvj420p" -c:v mjpeg -c:a copy "${DEST_DIR}/${subpath}/${basename}.flac"
  fi
done