summaryrefslogtreecommitdiff
path: root/transcode_album.sh
blob: d1ad1aaa09f1ca22434f8e6c798994a886cd95fd (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/bin/bash
# Transcode FLAC album to Opus, preserving metadata
# Usage: ./transcode_album.sh <source_dir> [--delete-source]
#
# Converts all FLAC files to Opus 128kbps (transparent quality, ~10x smaller)
# Preserves all metadata tags and album art

set -e

SOURCE_DIR="$1"
DELETE_SOURCE=false
BITRATE="128k"
GROUP="mediaserver"

if [[ "$2" == "--delete-source" ]]; then
    DELETE_SOURCE=true
fi

if [[ -z "$SOURCE_DIR" ]] || [[ ! -d "$SOURCE_DIR" ]]; then
    echo "Usage: $0 <source_directory> [--delete-source]"
    exit 1
fi

# Count FLAC files
flac_count=$(find "$SOURCE_DIR" -maxdepth 1 -iname "*.flac" | wc -l)
if [[ $flac_count -eq 0 ]]; then
    echo "No FLAC files found in $SOURCE_DIR"
    exit 0
fi

echo "Transcoding $flac_count FLAC files to Opus ($BITRATE)..."
echo "Source: $SOURCE_DIR"

converted=0
failed=0

# Process each FLAC file
find "$SOURCE_DIR" -maxdepth 1 -iname "*.flac" | while read -r flac_file; do
    filename=$(basename "$flac_file")
    opus_file="${flac_file%.flac}.opus"
    opus_file="${opus_file%.FLAC}.opus"
    
    echo "  Converting: $filename"
    
    if ffmpeg -hide_banner -loglevel warning -i "$flac_file" \
        -c:a libopus -b:a "$BITRATE" -vbr on \
        -map_metadata 0 \
        -y "$opus_file" 2>&1; then
        
        # Preserve original timestamp
        touch -r "$flac_file" "$opus_file"
        
        # Fix permissions
        chgrp "$GROUP" "$opus_file" 2>/dev/null || true
        chmod 664 "$opus_file" 2>/dev/null || true
        
        if $DELETE_SOURCE; then
            rm "$flac_file"
            echo "    ✓ Converted and removed FLAC"
        else
            echo "    ✓ Converted (FLAC kept)"
        fi
        ((converted++)) || true
    else
        echo "    ✗ Failed to convert"
        ((failed++)) || true
    fi
done

# Also convert any MP3s that are suspiciously large (>15MB per file avg)
# Actually, skip this - MP3s are already compressed

# Handle cover art - keep it
# ffmpeg should copy embedded art automatically for opus

echo ""
echo "Done! Converted $converted files."
if $DELETE_SOURCE; then
    # Calculate space saved
    echo "FLAC files deleted to save space."
fi