All pastes #1500300 Raw Edit

split2flac.sh

public text v1 · immutable
#1500300 ·published 2009-07-19 17:47 UTC
rendered paste body
#!/bin/sh
# Copyright (c) 2009 Serge "ftrvxmtrx" Ziryukin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CONFIG="${HOME}/.split2flac"
TMPCUE="${HOME}/.split2flac_sheet.cue"
TMPPIC="${HOME}/.split2flac_cover.jpg"

NOSUBDIRS=0
NORENAME=0
NOPIC=0
PIC_SIZE="192x192"

# load settings
eval `cat "${CONFIG}" 2>/dev/null`
DRY=0
SAVE=0
unset PIC
unset FILE
unset CUE

HELP="Usage: split2flac.sh [OPTIONS] FILE
         -o DIRECTORY * - set output directory
         -cue FILE      - use file as a cue sheet
         -c FILE      * - use file as a cover image
         -nc          * - do not set any cover images
         -cs WxH      * - set cover image size (current is ${PIC_SIZE})
         -d           * - create artist/album subdirs
         -nd          * - do not create any subdirs
         -r           * - rename tracks to include title
         -nr          * - do not rename tracks (numbers only, e.g. '01.flac')
         -p             - dry run
         -s             - save configuration to \"${CONFIG}\"
         -h             - print this message
         -H             - print README

* - option has effect on configuration if -s option passed.
NOTE: '-c some_file.jpg -s' only allows cover images, it doesn't set a default one."

README="split2flac.sh splits one big APE/FLAC/WV file to FLAC tracks with tagging and renaming.
    It's better to pass '-p' option to see what will happen when actually splitting tracks.
    You may want to pass '-s' option for the first run to save default configuration
(output dir, cover image size, etc.) so you won't need to pass a lot of options
every time, only a filename.
    Script will try to find CUE sheet if it wasn't specified."

# parse arguments
while [ "$1" ]
do
    case $1 in
        -o) DIR=$2; shift;;
        -cue) CUE=$2; shift;;
        -c) NOPIC=0; PIC=$2; shift;;
        -nc) NOPIC=1;;
        -cs) PIC_SIZE=$2; shift;;
        -d) NOSUBDIRS=0;;
        -nd) NOSUBDIRS=1;;
        -r) NORENAME=0;;
        -nr) NORENAME=1;;
        -p) DRY=1;;
        -s) SAVE=1;;
        -h) echo "${HELP}"; exit 0;;
        -H) echo "${README}"; exit 0;;
        *)
            if [ -r "${FILE}" ]
            then
                echo "Unknown option $1"
                echo "${HELP}"
                exit 1
            elif [ ! -r "$1" ]
            then
                echo "Unable to read $1"
                exit 1
            else
                FILE="$1"
            fi;;
    esac
    shift
done

# search for a cue sheet if not specified
if [ -z "${CUE}" ]
then
    CUE="${FILE}.cue"
    if [ ! -r "${CUE}" ]
    then
        CUE="`echo ${FILE} | sed 's/[^\.]*$//'`cue"
        if [ ! -r "${CUE}" ]
        then
        # try to extract internal one
            CUESHEET="`metaflac --show-tag=CUESHEET \"${FILE}\" 2>/dev/null | sed 's/CUESHEET=//I'`"

            if [ -z "${CUESHEET}" ]
            then
                CUESHEET="`wvunpack -q -c \"${FILE}\" 2>/dev/null`"
            fi

            if [ "${CUESHEET}" ]
            then
                CUE="${TMPCUE}"
                echo "${CUESHEET}" > "${CUE}"

                if [ $? -ne 0 ]
                then
                    echo "Unable to save internal cue sheet"
                    exit 1
                fi
            else
                unset CUE
            fi
        fi
    fi
fi

# print some info and check arguments
echo "Input file  :" ${FILE:?"${HELP}"}
echo "Cue sheet   :" ${CUE:?"No cue sheet"}

# search for a front cover image
if [ "${NOPIC}" -eq 1 ]
then
    unset PIC
elif [ -z "${PIC}" ]
then
    # try common names 
    SDIR="`dirname \"${FILE}\"`"

    for i in cover.jpg front_cover.jpg folder.jpg
    do
        if [ -r "${SDIR}/$i" ]
        then
            PIC="${SDIR}/$i"
            break
        fi
    done

    # try to extract internal one
    if [ -z "${PIC}" ]
    then
        metaflac --export-picture-to="${TMPPIC}" "${FILE}" 2>/dev/null
        if [ $? -ne 0 ]
        then
            echo "Unable to export internal front cover image"
            unset PIC
        else
            PIC="${TMPPIC}"
        fi
    fi
fi

echo "Cover image :" ${PIC:-"not set"}
echo "Output dir  :" ${DIR:?"Output directory wasn't set"}

# save configuration if needed
if [ "${SAVE}" -eq 1 ]
then
    echo "DIR=\"${DIR}\"" > "${CONFIG}"
    echo "NOSUBDIRS=${NOSUBDIRS}" >> "${CONFIG}"
    echo "NORENAME=${NORENAME}" >> "${CONFIG}"
    echo "NOPIC=${NOPIC}" >> "${CONFIG}"
    echo "PIC_SIZE=${PIC_SIZE}" >> "${CONFIG}"
    echo "Configuration saved"
fi

GETTAG="cueprint -n 1 -t"
VALIDATE="tr -d -C \"[:space:][:alnum:]&\-_#,.'\""

# get common tags
TAG_ARTIST="`${GETTAG} %P \"${CUE}\"`"
TAG_ALBUM="`${GETTAG} %T \"${CUE}\"`"
TRACKS_NUM="`${GETTAG} %N \"${CUE}\"`"

YEAR="`awk '{ if (/REM[ \t]+DATE/) { printf \"%i\", $3; exit } }' < \"${CUE}\"`"

if [ "${YEAR}" -a "${YEAR}" -ne 0 ]
then
    TAG_DATE="${YEAR}"
else
    unset TAG_DATE
fi

echo
echo "Artist : ${TAG_ARTIST}"
echo "Album  : ${TAG_ALBUM}"
echo "Year   : ${TAG_DATE}"
echo "Tracks : ${TRACKS_NUM}"
echo

# prepare output directory
OUT="${DIR}"

if [ "${NOSUBDIRS}" -ne 1 ]
then
    DIR_ARTIST="`echo ${TAG_ARTIST} | ${VALIDATE}`"
    DIR_ALBUM="`echo ${TAG_ALBUM} | ${VALIDATE}`"

    if [ "${TAG_DATE}" ]
    then
        DIR_ALBUM="${TAG_DATE} - ${DIR_ALBUM}"
    fi

    OUT="${OUT}/${DIR_ARTIST}/${DIR_ALBUM}"
fi

echo "Saving tracks to \"${OUT}\""

if [ "${DRY}" -ne 1 ]
then
    # create output dir
    mkdir -p "${OUT}"

    if [ $? -ne 0 ]
    then
        echo "Failed to create output directory"
        exit 1
    fi

    # split to tracks
    cuebreakpoints "${CUE}" | \
        shnsplit -O never -o "flac flac -8 - -o %f"  -d "${OUT}" -t "%n" "${FILE}"
    if [ $? -ne 0 ]
    then
        echo "Failed to split"
        exit 1
    fi

    # prepare cover image
    if [ "${PIC}" ]
    then
        convert "${PIC}" -resize "${PIC_SIZE}" "${TMPPIC}"
        if [ $? -eq 0 ]
        then
            PIC="${TMPPIC}"
        else
            echo "Failed to convert cover image"
            unset PIC
        fi
    fi
fi

# set tags and rename
echo
echo "Setting tags"

i=1
while [ $i -le ${TRACKS_NUM} ]
do
    TAG_TITLE="`cueprint -n $i -t %t \"${CUE}\"`"
    f="${OUT}/`printf %02i $i`.flac"
    FILE_TRACK="`basename \"$f\" .flac`"
    FILE_TITLE="`echo ${TAG_TITLE} | ${VALIDATE}`"

    echo "$i: ${TAG_TITLE}"

    if [ "${NORENAME}" -ne 1 ]
    then
        FINAL="${OUT}/${FILE_TRACK} - ${FILE_TITLE}.flac"
    else
        FINAL="$f"
    fi

    if [ "${DRY}" -ne 1 ]
    then
        metaflac --remove-all-tags \
            --set-tag="ARTIST=${TAG_ARTIST}" \
            --set-tag="ALBUM=${TAG_ALBUM}" \
            --set-tag="TITLE=${TAG_TITLE}" \
            --set-tag="TRACKNUMBER=$i" \
            "$f"

        [ "${TAG_DATE}" ] && metaflac --set-tag="DATE=${TAG_DATE}" "$f"
        [ "${PIC}" ] && metaflac --import-picture-from="${PIC}" "$f"

        if [ "${NORENAME}" -ne 1 ]
        then
            mv "$f" "${FINAL}"
        fi
    fi

    echo "   -> ${FINAL}"

    i=$(($i + 1))
done

rm -f "${TMPPIC}"
rm -f "${TMPCUE}"

echo
echo "Finished"