Merge pull request #371 from TheCaptain989/lidarr-flac2mp3

Lidarr: flac2mp3 release 2.0
This commit is contained in:
aptalca 2022-05-13 11:45:19 -04:00 committed by GitHub
commit d0c35ef78f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 430 additions and 239 deletions

View File

@ -20,9 +20,10 @@ jobs:
cat <<EOF
Building version $VERSION
EOF
# Insert version into scripts
sed -i -e "s/{{VERSION}}/$VERSION/" $GITHUB_WORKSPACE/root/usr/local/bin/flac2mp3.sh $GITHUB_WORKSPACE/root/etc/cont-init.d/98-flac2mp3
# Build image
docker build --build-arg VERSION=$VERSION \
--no-cache \
docker build --no-cache \
--tag ${{ github.sha }} .
- name: Tag image
if: ${{ github.ref == format('refs/heads/{0}-{1}', env.BASEIMAGE, env.MODNAME) }}

View File

@ -1,20 +1,7 @@
## Buildstage ##
FROM lsiobase/ubuntu:xenial as buildstage
# Build arguments
ARG VERSION
# Add version number for use in container init script
RUN mkdir -p /root-layer/etc && \
echo "$VERSION" > /root-layer/etc/version.tc989
# Stage local files
COPY root/ /root-layer/
## Single layer deployed image ##
FROM scratch
LABEL maintainer="TheCaptain989"
# Copy files from buildstage
COPY --from=buildstage /root-layer/ /
# Copy local files
COPY root/ /

102
README.md
View File

@ -1,6 +1,7 @@
# About
A [Docker Mod](https://github.com/linuxserver/docker-mods) for the LinuxServer.io Lidarr Docker container that uses ffmpeg and a script to automatically convert downloaded FLAC files to MP3s. Default output quality is 320Kbps constant bit rate.
Advanced options act as a light wrapper to ffmpeg, allowing conversion to any supported audio format, including AAC, AC3, and Opus.
Advanced options act as a light wrapper to ffmpeg, allowing conversion to any supported audio format, including AAC, AC3, Opus, and many others.
A [Batch Mode](./README.md#batch-mode) is also supported that allows usage outside of Lidarr.
>**NOTE:** This mod supports Linux OSes only.
@ -40,7 +41,7 @@ Production Container info: ![Docker Image Size](https://img.shields.io/docker/im
2. Start the container.
3. After the above configuration is complete, to use ffmpeg, configure a custom script from Lidarr's *Settings* > *Connect* screen and type the following in the **Path** field:
3. Configure a custom script from Lidarr's *Settings* > *Connect* screen and type the following in the **Path** field:
`/usr/local/bin/flac2mp3.sh`
*Example*
@ -51,65 +52,81 @@ Production Container info: ![Docker Image Size](https://img.shields.io/docker/im
*For any other setting, you **must** either use one of the [included wrapper scripts](./README.md#included-wrapper-scripts) or create a custom script with the command line options you desire. See the [Syntax](./README.md#syntax) section below.*
## Usage
New file(s) with an MP3 extension will be placed in the same directory as the original FLAC file(s) and have the same owner and permissions. Existing MP3 files with the same track name will be overwritten.
New file(s) with will be placed in the same directory as the original FLAC file(s) (unless redirected with the `--output` option below) and have the same owner and permissions. Existing files with the same track name will be overwritten.
If you've configured Lidarr's **Recycle Bin** path correctly, the original audio file will be moved there.
![danger] **NOTE:** If you have *not* configured the Recycle Bin, the original FLAC audio file(s) will be deleted and permanently lost.
By default, if you've configured Lidarr's **Recycle Bin** path correctly, the original audio file will be moved there.
![danger] **NOTE:** If you have *not* configured the Recycle Bin, the original FLAC audio file(s) will be deleted and permanently lost. This behavior may be modifed with the `--keep-file` option.
### Syntax
>**Note:** The **Arguments** field for Custom Scripts was removed in Lidarr release [v0.7.0.1347](https://github.com/lidarr/Lidarr/commit/b9d240924f8965ebb2c5e307e36b810ae076101e "Lidarr commit notes") due to security concerns.
To support options with this version and later, a wrapper script can be manually created that will call *flac2mp3.sh* with the required arguments.
The script accepts five command line options:
#### Command Line Options and Arguments
The script may be called with optional command line arguments.
`[-d] [-b <bitrate> | -v <quality> | -a "<options>" -e <extension>]`
The syntax for the command line is:
`flac2mp3 [OPTIONS] [{-b|--bitrate} <bitrate> | {-v|--quality} <quality> | {-a|--advanced} "<options>" {-e|--extension} <extension>]`
OR
`flac2mp3 [OPTIONS] {-f|--file} <audio_file>`
The `-b bitrate` option sets the output quality in constant bits per second (CBR).
Where:
The `-v quality` option sets the output quality using a variable bit rate (VBR) where `quality` is a value between 0 and 9, with 0 being the highest quality.
See the [FFmpeg MP3 Encoding Guide](https://trac.ffmpeg.org/wiki/Encode/MP3) for more details.
The `-a "options"` setting is used in conjunction with `-e` to set advanced ffmpeg options. The specified command line options replace all script defaults and are sent directly to ffmpeg. The `options` value must be enclosed in quotes.
![danger] **WARNING:** When using `-a`, you must specify an audio codec (via `-c:a`) or the resulting file will contain no audio.
![danger] **WARNING:** Invalid `options` could result in script failure!
See [FFmpeg Options](https://ffmpeg.org/ffmpeg.html#Options) for details on valid options.
See [Guidelines for high quality audio encoding](https://trac.ffmpeg.org/wiki/Encode/HighQualityAudio) for more information.
The `-e extension` option sets the output file extension, and must be used in conjunction with `-a`. The `extension` may be prefixed by a dot (".") or not.
Option|Argument|Description
---|---|---
-d, --debug|\[\<level\>\]|Enables debug logging. Level is optional.<br/>Default of 1 (low).<br/>2 includes JSON output.
-b, --bitrate|\<bitrate\>|Sets the output quality in constant bits per second (CBR).<br/>Examples: 160k, 240k, 300000<br/>**Note:** May not be specified with `-v`, `-a`, or `-e`.
-v, --quality|\<quality\>|Sets the output variable bit rate (VBR).<br/>Specify a value between 0 and 9, with 0 being the highest quality.<br/>See the [FFmpeg MP3 Encoding Guide](https://trac.ffmpeg.org/wiki/Encode/MP3) for more details.<br/>**Note:** May not be specified with `-b`, `-a`, or `-e`.
-a, --advanced|\"\<options\>\"|Advanced ffmpeg options.<br/>The specified `options` replace all script defaults and are sent directly to ffmpeg.<br/>The `options` value must be enclosed in quotes.<br/>See [FFmpeg Options](https://ffmpeg.org/ffmpeg.html#Options) for details on valid options, and [Guidelines for high quality audio encoding](https://trac.ffmpeg.org/wiki/Encode/HighQualityAudio) for suggested usage.<br/>**Note:** Requires the `-e` option to also be specified. May not be specified with `-v` or `-b`.<br/>![danger] **WARNING:** You must specify an audio codec (by including a `-c:a <codec>` ffmpeg option) or the resulting file will contain no audio!<br/>![danger] **WARNING:** Invalid `options` could result in script failure!
-e, --extension|\<extension\>|Sets the output file extension<br/>The extension may be prefixed by a dot (".") or not.<br/>**Note:** Requires the `-a` option to also be specified. May not be specified with `-v` or `-b`.
-f, --file|<audio_file>|If included, the script enters **[Batch Mode](./README.md#batch-mode)** and converts the specified audio file.<br/>![danger] **WARNING:** Do not use this argument when called from Lidarr!
-o, --output|\<directory\>|Converted audio file(s) are saved to `directory` instead of being located in the same directory as the source audio file.<br/>The path will be created if it does not exist.
-k, --keep-file| |Do not delete the source file or move it to the Lidarr Recycle bin.<br/>**Note:** This also disables triggering a Lidarr rescan after conversion.
--help| |Display help and exit.
--version| |Display version and exit.
If neither `-b`, `-v`, `-a`, or `-e` options are specified, the script will default to a constant 320Kbps MP3.
The `-d` option enables debug logging.
#### Technical notes on `-a` advanced options
The `-a` option effectively makes the script a somewhat generic wrapper for ffmpeg. FFmpeg is executed once per track with only the loglevel, input filename, and output filename being set. All other options are passed unparsed to the command line.
#### Technical notes on advanced options
The `-a` option effectively makes the script a generic wrapper for ffmpeg. FFmpeg is executed once per track with only the loglevel, input filename, and output filename being set. All other options are passed unparsed to the command line.
The exact format of the executed ffmpeg command is:
```
ffmpeg -loglevel error -i "Original.flac" ${Options} "NewTrack${Extension}"
ffmpeg -loglevel error -i "input.flac" ${options} "output.${extension}"
```
### Examples
```
-b 320k # Output 320 kbit/s MP3 (non VBR; same as default behavior)
-b 320k # Output 320 kbit/s MP3 (non-VBR; same as default behavior)
-v 0 # Output variable bitrate MP3, VBR 220-260 kbit/s
-d -b 160k # Enable debugging, and output a 160 kbit/s MP3
-a "-c:v libtheora -map 0 -q:v 10 -c:a libopus -b:a 192k" -e .opus # Convert to Opus format, VBR 192 kbit/s, cover art
-a "-y -map 0 -c:a aac -b:a 240k -c:v copy" -e mp4 # Convert to MP4 format, using AAC 240 kbit/s audio, cover art, overwrite file
-d -b 160k # Enable debugging level 1, and output a 160 kbit/s MP3
-a "-c:v libtheora -map 0 -q:v 10 -c:a libopus -b:a 192k" -e .opus
# Convert to Opus format, VBR 192 kbit/s, cover art, no overwright
-a "-y -map 0 -c:a aac -b:a 240k -c:v copy" -e mp4
# Convert to MP4 format, using AAC 240 kbit/s audio, cover art, overwrite file
--file "/path/to/audio/a-ha/Hunting High and Low/01 Take on Me.flac"
# Batch Mode
# Output 320kbit/s MP3
-o "/path/to/audio" -k
# Place the converted file(s) in the specified directory and do not delete the original audio file(s).
```
### Included Wrapper Scripts
### Wrapper Scripts
To supply arguments to the script, one of the included wrapper scripts may be used or a custom wrapper script must be created.
#### Included Wrapper Scripts
For your convenience, several wrapper scripts are included in the `/usr/local/bin/` directory.
You may use any of these scripts in place of the `flac2mp3.sh` mentioned in the [Installation](./README.md#installation) section above.
```
flac2mp3-debug.sh # Enable debugging
flac2mp3-debug.sh # Enable debugging, level 1
flac2mp3-debug-2.sh # Enable debugging, level 2
flac2mp3-vbr.sh # Use variable bit rate MP3, quality 0
flac2opus.sh # Convert to Opus format using .opus extension, 192 kbit/s, no covert art
flac2alac.sh # Convert to Apple Lossless using an .m4a extension
```
### Example Wrapper Script
To configure the middle entry from the [Examples](./README.md#examples) section above, create and save a file called `flac2mp3-custom.sh` to `/config` containing the following text:
#### Example Wrapper Script
To configure an entry from the [Examples](./README.md#examples) section above, create and save a file called `flac2mp3-custom.sh` to `/config` containing the following text:
```shell
#!/bin/bash
@ -125,7 +142,24 @@ Then put `/config/flac2mp3-custom.sh` in the **Path** field in place of `/usr/lo
>**Note:** If you followed the Linuxserver.io recommendations when configuring your container, the `/config` directory will be mapped to an external storage location. It is therefore recommended to place custom scripts in the `/config` directory so they will survive container updates, but they may be placed anywhere that is accessible by Lidarr.
### Triggers
The only events/notification triggers that have been tested are **On Release Import** and **On Upgrade**
The only events/notification triggers that are supported are **On Release Import** and **On Upgrade**
### Batch Mode
Batch mode allows the script to be executed independently of Lidarr. It converts the file specified on the command line and ignores any environment variables that are normally expected to be set by the music management program.
Using this function, you can easily process all of your audio files in any subdirectory at once. See the [Batch Example](./README.md#batch-example) below.
#### Script Execution Differences in Batch Mode
Because the script is not called from within Lidarr, expect the following behavior while in Batch Mode:
* *The file name must be specified on the command line*<br/>(The `-f` option places the script in Batch Mode)
* *Lidarr APIs are not called and its database is not updated.*<br/>This may require a manual rescan of converted music files.
* *Original audio files are deleted.*<br/>The Recycle Bin function is not available. (Modifiable using the `-k` option.)
#### Batch Example
To convert all .FLAC files in the `/music` directory to Apple Lossless Audio Codec (ALAC), enter the following at the Linux command line:
```shell
find /music/ -type f -name "*.flac" | while read file; do /usr/local/bin/flac2mp3.sh -f "$file" -a "-c:a alac" -e m4a; done
```
### Logs
A log file is created for the script activity called:
@ -135,7 +169,7 @@ A log file is created for the script activity called:
This log can be downloaded from Lidarr under *System* > *Log Files*
Log rotation is performed, with 5 log files of 1MB each kept, matching Lidarr's log retention.
>![danger] **NOTE:** If debug logging is enabled, the log file can grow very large very quickly. *Do not leave debug logging enabled permanently.*
>![danger] **NOTE:** If debug logging is enabled with a level above 1, the log file can grow very large very quickly. *Do not leave high-level debug logging enabled permanently.*
## Credits
This would not be possible without the following:
@ -147,4 +181,4 @@ This would not be possible without the following:
Icons made by [Freepik](https://www.freepik.com) from [Flaticon](https://www.flaticon.com/)
[warning]: .assets/warning.png "Warning"
[danger]: .assets/danger.png "Danger"
[danger]: .assets/danger.png "Danger"

View File

@ -6,8 +6,8 @@ Only the latest major and minor version are supported.
| Version | Supported |
| ------- | ------------------ |
| 1.3.x | :heavy_check_mark: |
| < 1.3 | :x: |
| 2.0.x | :heavy_check_mark: |
| < 2.0 | :x: |
## Reporting a Vulnerability

View File

@ -7,7 +7,7 @@ Repos:
Dev/test: https://github.com/TheCaptain989/lidarr-flac2mp3
Prod: https://github.com/linuxserver/docker-mods/tree/lidarr-flac2mp3
Version: $(cat /etc/version.tc989)
Version: {{VERSION}}
----------------
EOF

View File

@ -0,0 +1,3 @@
#!/bin/bash
. /usr/local/bin/flac2mp3.sh -a "-vn -c:a alac" -e m4a

View File

@ -0,0 +1,3 @@
#!/bin/bash
. /usr/local/bin/flac2mp3.sh -d 2

View File

@ -1,3 +1,3 @@
#!/bin/bash
. /usr/local/bin/flac2mp3.sh -d
. /usr/local/bin/flac2mp3.sh -d 1

View File

@ -8,66 +8,262 @@
# Dependencies:
# ffmpeg
# awk
# curl
# jq
# stat
# nice
# basename
# printenv
# chmod
# Exit codes:
# 0 - success; or test
# 1 - no tracks files found in environment
# 2 - mkvmerge not found
# 1 - no audio file specified on command line
# 2 - ffmpeg not found
# 3 - invalid command line arguments
# 5 - specified audio file not found
# 6 - error when creating output directory
# 7 - unknown eventtype environment variable
# 10 - awk script generated an error
# 20 - general error
### Variables
export flac2mp3_script=$(basename "$0")
export flac2mp3_ver="{{VERSION}}"
export flac2mp3_pid=$$
export flac2mp3_config=/config/config.xml
export flac2mp3_log=/config/logs/flac2mp3.txt
export flac2mp3_maxlogsize=1024000
export flac2mp3_maxlog=4
export flac2mp3_debug=0
export flac2mp3_tracks="$lidarr_addedtrackpaths"
[ -z "$flac2mp3_tracks" ] && flac2mp3_tracks="$lidarr_trackfile_path" # For other event type
export flac2mp3_keep=0
export flac2mp3_type=$(printenv | sed -n 's/_eventtype *=.*$//p')
### Functions
# Usage function
function usage {
usage="
$flac2mp3_script
$flac2mp3_script Version: $flac2mp3_ver
Audio conversion script designed for use with Lidarr
Source: https://github.com/TheCaptain989/lidarr-flac2mp3
Usage:
$0 [-d] [-b <bitrate> | -v <quality> | -a \"<options>\" -e <extension>]
$0 [OPTIONS] [-b <bitrate> | -v <quality> | -a \"<options>\" -e <extension>]
$0 [OPTIONS] {-f|--file} <audio_file>
Options:
-d enable debug logging
-b <bitrate> set output quality in constant bits per second [default: 320k]
Ex: 160k, 240k, 300000
-v <quality> set variable bitrate; quality between 0-9
0 is highest quality, 9 is lowest
See https://trac.ffmpeg.org/wiki/Encode/MP3 for more details
-a \"<options>\" advanced ffmpeg options enclosed in quotes
Specified options replace all script defaults and are sent as
entered to ffmpeg for processing.
See https://ffmpeg.org/ffmpeg.html#Options for details on valid options.
WARNING: You must specify an audio codec!
WARNING: Invalid options could result in script failure!
Requires -e option to also be specified
See https://github.com/TheCaptain989/lidarr-flac2mp3 for more details
-e <extension> file extension for output file, with or without dot
Required when -a is specified!
-d, --debug [<level>] enable debug logging
Level is optional, default of 1 (low)
-b, --bitrate <bitrate> set output quality in constant bits per second
[default: 320k]
Ex: 160k, 240k, 300000
-v, --quality <quality> set variable bitrate; quality between 0-9
0 is highest quality, 9 is lowest
For more details, see:
https://trac.ffmpeg.org/wiki/Encode/MP3
-a, --advanced \"<options>\" advanced ffmpeg options enclosed in quotes
Specified options replace all script defaults
and are sent as entered to ffmpeg for
processing.
For more details on valid options, see:
https://ffmpeg.org/ffmpeg.html#Options
WARNING: You must specify an audio codec!
WARNING: Invalid options could result in script
failure!
Requires -e option to also be specified
For more details, see:
https://github.com/TheCaptain989/lidarr-flac2mp3
-e, --extension <extension> file extension for output file, with or without
dot
Required when -a is specified!
-f, --file <audio_file> the script enters batch mode, using the
specified audio file as input
WARNING: Do not use this argument when called
from Lidarr!
-o, --output <directory> specify a directory for the converted audio
file(s)
This will be created if it does not exist.
-k, --keep-file do not delete the source file or move it to the
Lidarr Recycle bin
This also disables the Lidarr rescan.
--help display this help and exit
--version display script version and exit
Examples:
$flac2mp3_script -b 320k # Output 320 kbit/s MP3 (non VBR; same as default behavior)
$flac2mp3_script -v 0 # Output variable bitrate MP3, VBR 220-260 kbit/s
$flac2mp3_script -d -b 160k # Enable debugging and set output a 160 kbit/s MP3
$flac2mp3_script -a \"-vn -c:a libopus -b:a 192K\" -e .opus # Convert to Opus format, VBR 192 kbit/s, no cover art
$flac2mp3_script -a \"-y -map 0 -c:a aac -b:a 240K -c:v copy\" -e mp4 # Convert to MP4 format, using AAC 240 kbit/s audio, cover art, overwrite file
$flac2mp3_script -b 320k # Output 320 kbit/s MP3 (non-VBR; same as
default behavior)
$flac2mp3_script -v 0 # Output variable bitrate MP3, VBR 220-260
kbit/s
$flac2mp3_script -d -b 160k # Enable debugging level 1 and set output a
160 kbit/s MP3
$flac2mp3_script -a \"-vn -c:a libopus -b:a 192K\" -e .opus
# Convert to Opus format, VBR 192 kbit/s, no
cover art
$flac2mp3_script -a \"-y -map 0 -c:a aac -b:a 240K -c:v copy\" -e mp4
# Convert to MP4 format, using AAC 240 kbit/s
audio, cover art, overwrite file
$flac2mp3_script -f \"/path/to/audio/a-ha/Hunting High and Low/01 Take on Me.flac\"
# Batch Mode
Output 320 kbit/s MP3
$flac2mp3_script -o \"/path/to/audio\" -k
# Place the converted file(s) in specified
directory and do not delete the original audio
file(s).
"
echo "$usage" >&2
}
# Process arguments
while (( "$#" )); do
case "$1" in
-d|--debug ) # Enable debugging, with optional level
if [ -n "$2" ] && [ ${2:0:1} != "-" ] && [[ "$2" =~ ^[0-9]+$ ]]; then
export flac2mp3_debug=$2
shift 2
else
export flac2mp3_debug=1
shift
fi
;;
--help ) # Display usage
usage
exit 0
;;
--version ) # Display version
echo "$flac2mp3_script $flac2mp3_ver"
exit 0
;;
-f|--file ) # Batch Mode
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
# Overrides detected *_eventtype
export flac2mp3_type="batch"
export flac2mp3_tracks="$2"
shift 2
else
echo "Error|Invalid option: $1 requires an argument." >&2
usage
exit 1
fi
;;
-b|--bitrate ) # Set constant bit rate
if [ -n "$flac2mp3_vbrquality" ]; then
echo "Error|Both -b and -v options cannot be set at the same time." >&2
usage
exit 3
elif [ -n "$flac2mp3_ffmpegadv" -o -n "$flac2mp3_extension" ]; then
echo "Error|The -a and -e options cannot be set at the same time as either -v or -b options." >&2
usage
exit 3
elif [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
export flac2mp3_bitrate="$2"
shift 2
else
echo "Error|Invalid option: $1 requires an argument." >&2
usage
exit 3
fi
;;
-v|--quality ) # Set variable quality
if [ -n "$flac2mp3_bitrate" ]; then
echo "Error|Both -v and -b options cannot be set at the same time." >&2
usage
exit 3
elif [ -n "$flac2mp3_ffmpegadv" -o -n "$flac2mp3_extension" ]; then
echo "Error|The -a and -e options cannot be set at the same time as either -v or -b options." >&2
usage
exit 3
elif [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
export flac2mp3_vbrquality="$2"
shift 2
else
echo "Error|Invalid option: $1 requires an argument." >&2
usage
exit 3
fi
;;
-a|--advanced ) # Set advanced options
if [ -n "$flac2mp3_vbrquality" -o -n "$flac2mp3_bitrate" ]; then
echo "Error|The -a and -e options cannot be set at the same time as either -v or -b options." >&2
usage
exit 3
elif [ -n "$2" ]; then
export flac2mp3_ffmpegadv="$2"
shift 2
else
echo "Error|Invalid option: $1 requires an argument." >&2
usage
exit 3
fi
;;
-e|--extension ) # Set file extension
if [ -n "$flac2mp3_vbrquality" -o -n "$flac2mp3_bitrate" ]; then
echo "Error|The -a and -e options cannot be set at the same time as either -v or -b options." >&2
usage
exit 3
elif [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
export flac2mp3_extension="$2"
shift 2
else
echo "Error|Invalid option: $1 requires an argument." >&2
usage
exit 3
fi
# Test for dot prefix
[ "${flac2mp3_extension:0:1}" != "." ] && flac2mp3_extension=".${flac2mp3_extension}"
;;
-o|--output ) # Set output directory
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
export flac2mp3_output="$2"
shift 2
else
echo "Error|Invalid option: $1 requires an argument." >&2
usage
exit 3
fi
# Test for trailing slash
[ "${flac2mp3_output: -1:1}" != "/" ] && flac2mp3_output="${flac2mp3_output}/"
;;
-k|--keep-file ) # Do not delete source file(s)
export flac2mp3_keep=1
shift
;;
-*|--*=) # Unknown option
echo "Error|Unknown option: $1" >&2
usage
exit 20
;;
*) # Remove unknown positional parameters
shift
;;
esac
done
# Test for either -a and -e, but not both: logical XOR = non-equality
if [ "${flac2mp3_ffmpegadv:+data}" != "${flac2mp3_extension:+data}" ]; then
echo "Error|The -a and -e options must be specified together." >&2
usage
exit 3
fi
# Set default bit rate
[ -z "$flac2mp3_vbrquality" -a -z "$flac2mp3_bitrate" -a -z "$flac2mp3_ffmpegadv" -a -z "$flac2mp3_extension" ] && flac2mp3_bitrate="320k"
## Mode specific variables
if [[ "${flac2mp3_type,,}" = "batch" ]]; then
# Batch mode
export lidarr_eventtype="Convert"
elif [[ "${flac2mp3_type,,}" = "lidarr" ]]; then
export flac2mp3_tracks="$lidarr_addedtrackpaths"
# Catch for other environment variable
[ -z "$flac2mp3_tracks" ] && flac2mp3_tracks="$lidarr_trackfile_path"
else
# Called in an unexpected way
echo -e "Error|Unknown or missing 'lidarr_eventtype' environment variable: ${flac2mp3_type}\nNot called within Lidarr?\nTry using Batch Mode option: -f <file>"
exit 7
fi
### Functions
# Can still go over flac2mp3_maxlog if read line is too long
# Must include whole function in subshell for read to work!
function log {(
@ -94,11 +290,11 @@ function read_xml {
function rescan {
flac2mp3_message="Info|Calling Lidarr API to rescan artist"
echo "$flac2mp3_message" | log
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Forcing rescan of artist '$lidarr_artist_id'. Calling Lidarr API 'RefreshArtist' using POST and URL '$flac2mp3_api_url/command'" | log
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Forcing rescan of artist '$lidarr_artist_id'. Calling Lidarr API 'RefreshArtist' using POST and URL '$flac2mp3_api_url/command'" | log
flac2mp3_result=$(curl -s -H "X-Api-Key: $flac2mp3_apikey" \
-d "{\"name\": 'RefreshArtist', \"artistId\": $lidarr_artist_id}" \
-X POST "$flac2mp3_api_url/command")
[ $flac2mp3_debug -eq 1 ] && echo "API returned: $flac2mp3_result" | awk '{print "Debug|"$0}' | log
[ $flac2mp3_debug -ge 2 ] && echo "API returned: $flac2mp3_result" | awk '{print "Debug|"$0}' | log
flac2mp3_jobid="$(echo $flac2mp3_result | jq -crM .id)"
if [ "$flac2mp3_jobid" != "null" ]; then
local flac2mp3_return=0
@ -111,10 +307,10 @@ function rescan {
function check_rescan {
local i=0
for ((i=1; i <= 15; i++)); do
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Checking job $flac2mp3_jobid completion, try #$i. Calling Lidarr API using GET and URL '$flac2mp3_api_url/command/$flac2mp3_jobid'" | log
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Checking job $flac2mp3_jobid completion, try #$i. Calling Lidarr API using GET and URL '$flac2mp3_api_url/command/$flac2mp3_jobid'" | log
flac2mp3_result=$(curl -s -H "X-Api-Key: $flac2mp3_apikey" \
-X GET "$flac2mp3_api_url/command/$flac2mp3_jobid")
[ $flac2mp3_debug -eq 1 ] && echo "API returned: $flac2mp3_result" | awk '{print "Debug|"$0}' | log
[ $flac2mp3_debug -ge 2 ] && echo "API returned: $flac2mp3_result" | awk '{print "Debug|"$0}' | log
if [ "$(echo $flac2mp3_result | jq -crM .status)" = "completed" ]; then
local flac2mp3_return=0
break
@ -125,7 +321,7 @@ function check_rescan {
else
# It may have timed out, so let's wait a second
local flac2mp3_return=1
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Job not done. Waiting 1 second." | log
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Job not done. Waiting 1 second." | log
sleep 1
fi
fi
@ -133,107 +329,35 @@ function check_rescan {
return $flac2mp3_return
}
# Process options
while getopts ":db:v:a:e:" opt; do
case ${opt} in
d ) # For debug purposes only
flac2mp3_message="Debug|Enabling debug logging."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
flac2mp3_debug=1
printenv | sort | sed 's/^/Debug|/' | log
;;
b ) # Set constant bit rate
if [ -n "$flac2mp3_vbrquality" ]; then
flac2mp3_message="Error|Both -b and -v options cannot be set at the same time."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
elif [ -n "$flac2mp3_ffmpegadv" -o -n "$flac2mp3_extension" ]; then
flac2mp3_message="Error|The -a and -e options cannot be set at the same time as either -v or -b options."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
else
flac2mp3_bitrate="$OPTARG"
fi
;;
v ) # Set variable quality
if [ -n "$flac2mp3_bitrate" ]; then
flac2mp3_message="Error|Both -v and -b options cannot be set at the same time."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
elif [ -n "$flac2mp3_ffmpegadv" -o -n "$flac2mp3_extension" ]; then
flac2mp3_message="Error|The -a and -e options cannot be set at the same time as either -v or -b options."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
else
flac2mp3_vbrquality="$OPTARG"
fi
;;
a ) # Set advanced options
if [ -n "$flac2mp3_vbrquality" -o -n "$flac2mp3_bitrate" ]; then
flac2mp3_message="Error|The -a and -e options cannot be set at the same time as either -v or -b options."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
else
flac2mp3_ffmpegadv="$OPTARG"
fi
;;
e ) # Set file extension
if [ -n "$flac2mp3_vbrquality" -o -n "$flac2mp3_bitrate" ]; then
flac2mp3_message="Error|The -a and -e options cannot be set at the same time as either -v or -b options."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
else
flac2mp3_extension="$OPTARG"
fi
# Test for dot
[ "${flac2mp3_extension:0:1}" != "." ] && flac2mp3_extension=".${flac2mp3_extension}"
;;
: ) # No required argument specified
flac2mp3_message="Error|Invalid option: -${OPTARG} requires an argument"
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
;;
* ) # Unknown option
flac2mp3_message="Error|Unknown option: -${OPTARG}"
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
;;
esac
done
# Test for either -a and -e, but not both: logical XOR = non-equality
if [ "${flac2mp3_ffmpegadv:+data}" != "${flac2mp3_extension:+data}" ]; then
flac2mp3_message="Error|The -a and -e options must be specified together."
# Check for required binaries
if [ ! -f "/usr/bin/ffmpeg" ]; then
flac2mp3_message="Error|/usr/bin/ffmpeg is required by this script"
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 3
exit 2
fi
shift $((OPTIND -1))
# Set default bit rate
[ -z "$flac2mp3_vbrquality" -a -z "$flac2mp3_bitrate" -a -z "$flac2mp3_ffmpegadv" -a -z "$flac2mp3_extension" ] && flac2mp3_bitrate="320k"
# Log Debug state
if [ $flac2mp3_debug -ge 1 ]; then
flac2mp3_message="Debug|Enabling debug logging level ${flac2mp3_debug}. Starting ${lidarr_eventtype^} run."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
fi
# Log environment
[ $flac2mp3_debug -ge 2 ] && printenv | sort | sed 's/^/Debug|/' | log
# Log Batch mode
if [ "$flac2mp3_type" = "batch" ]; then
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Switching to batch mode. Input filename: ${flac2mp3_tracks}" | log
fi
# Check for config file
if [ -f "$flac2mp3_config" ]; then
if [ "$flac2mp3_type" = "batch" ]; then
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Not using config file in batch mode." | log
elif [ -f "$flac2mp3_config" ]; then
# Read Lidarr config.xml
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Reading from Lidarr config file '$flac2mp3_config'" | log
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Reading from Lidarr config file '$flac2mp3_config'" | log
while read_xml; do
[[ $flac2mp3_xml_entity = "Port" ]] && flac2mp3_port=$flac2mp3_xml_content
[[ $flac2mp3_xml_entity = "UrlBase" ]] && flac2mp3_urlbase=$flac2mp3_xml_content
@ -247,16 +371,30 @@ if [ -f "$flac2mp3_config" ]; then
flac2mp3_api_url="http://$flac2mp3_bindaddress:$flac2mp3_port$flac2mp3_urlbase/api/v1"
# Check Lidarr version
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Getting Lidarr version. Calling Lidarr API using GET and URL '$flac2mp3_api_url/system/status'" | log
flac2mp3_version=$(curl -s -H "X-Api-Key: $flac2mp3_apikey" \
-X GET "$flac2mp3_api_url/system/status" | jq -crM .version)
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Detected Lidarr version $flac2mp3_version" | log
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Getting Lidarr version. Calling Lidarr API using GET and URL '$flac2mp3_api_url/system/status'" | log
flac2mp3_result=$(curl -s -H "X-Api-Key: $flac2mp3_apikey" \
-X GET "$flac2mp3_api_url/system/status")
flac2mp3_return=$?; [ "$flac2mp3_return" != 0 ] && {
flac2mp3_message="Error|[$flac2mp3_return] curl error when parsing: \"$flac2mp3_api_url/system/status\""
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
}
[ $flac2mp3_debug -ge 2 ] && echo "API returned: $flac2mp3_result" | awk '{print "Debug|"$0}' | log
flac2mp3_version="$(echo $flac2mp3_result | jq -crM .version)"
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Detected Lidarr version $flac2mp3_version" | log
# Get RecycleBin
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Getting Lidarr RecycleBin. Calling Lidarr API using GET and URL '$flac2mp3_api_url/config/mediamanagement'" | log
flac2mp3_recyclebin=$(curl -s -H "X-Api-Key: $flac2mp3_apikey" \
-X GET "$flac2mp3_api_url/config/mediamanagement" | jq -crM .recycleBin)
[ $flac2mp3_debug -eq 1 ] && echo "Debug|Detected Lidarr RecycleBin '$flac2mp3_recyclebin'" | log
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Getting Lidarr RecycleBin. Calling Lidarr API using GET and URL '$flac2mp3_api_url/config/mediamanagement'" | log
flac2mp3_result=$(curl -s -H "X-Api-Key: $flac2mp3_apikey" \
-X GET "$flac2mp3_api_url/config/mediamanagement")
flac2mp3_return=$?; [ "$flac2mp3_return" != 0 ] && {
flac2mp3_message="Error|[$flac2mp3_return] curl error when parsing: \"$flac2mp3_api_url/v3/config/mediamanagement\""
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
}
[ $flac2mp3_debug -ge 2 ] && echo "API returned: $flac2mp3_result" | awk '{print "Debug|"$0}' | log
flac2mp3_recyclebin="$(echo $flac2mp3_result | jq -crM .recycleBin)"
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Detected Lidarr RecycleBin '$flac2mp3_recyclebin'" | log
else
# No config file means we can't call the API. Best effort at this point.
flac2mp3_message="Warn|Unable to locate Lidarr config file: '$flac2mp3_config'"
@ -267,46 +405,62 @@ fi
# Handle Lidarr Test event
if [[ "$lidarr_eventtype" = "Test" ]]; then
echo "Info|Lidarr event: $lidarr_eventtype" | log
echo "Info|Script was test executed successfully." | log
flac2mp3_message="Info|Script was test executed successfully."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
exit 0
fi
# Check if called from within Lidarr
if [ -z "$flac2mp3_tracks" ]; then
flac2mp3_message="Error|No track file(s) specified! Not called from Lidarr?"
# Check if source audio file exists
if [ "$flac2mp3_type" = "batch" -a ! -f "$flac2mp3_tracks" ]; then
flac2mp3_message="Error|Input file not found: \"$flac2mp3_tracks\""
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
usage
exit 1
exit 5
fi
# Check for required binaries
if [ ! -f "/usr/bin/ffmpeg" ]; then
flac2mp3_message="Error|/usr/bin/ffmpeg is required by this script"
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
exit 2
# If specified, check if destination folder exists and create if necessary
if [ "$flac2mp3_output" -a ! -d "$flac2mp3_output" ]; then
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Destination directory does not exist. Creating: $flac2mp3_output" | log
mkdir -p "$flac2mp3_output"
flac2mp3_return=$?; [ "$flac2mp3_return" != 0 ] && {
flac2mp3_message="Error|[$flac2mp3_return] mkdir returned an error. Unable to create output directory."
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
exit 6
}
fi
# Legacy one-liner script for posterity
#find "$lidarr_artist_path" -name "*.flac" -exec bash -c 'ffmpeg -loglevel warning -i "{}" -y -acodec libmp3lame -b:a 320k "${0/.flac}.mp3" && rm "{}"' {} \;
#### MAIN
flac2mp3_message="Info|Lidarr event: ${lidarr_eventtype}, Artist: ${lidarr_artist_name} (${lidarr_artist_id}), Album: ${lidarr_album_title} (${lidarr_album_id}), "
if [ -z "$flac2mp3_ffmpegadv" ]; then
flac2mp3_message+="Export bitrate: ${flac2mp3_bitrate:-$flac2mp3_vbrquality}"
else
flac2mp3_message+="Advanced options: '${flac2mp3_ffmpegadv}', File extension: ${flac2mp3_extension}"
#### BEGIN MAIN
flac2mp3_message="Info|Lidarr event: ${lidarr_eventtype}"
if [ "$flac2mp3_type" != "batch" ]; then
flac2mp3_message+=", Artist: ${lidarr_artist_name} (${lidarr_artist_id}), Album: ${lidarr_album_title} (${lidarr_album_id})"
fi
flac2mp3_message+=", Tracks: ${flac2mp3_tracks}"
if [ -z "$flac2mp3_ffmpegadv" ]; then
flac2mp3_message+=", Export bitrate: ${flac2mp3_bitrate:-$flac2mp3_vbrquality}"
else
flac2mp3_message+=", Advanced options: '${flac2mp3_ffmpegadv}', File extension: ${flac2mp3_extension}"
fi
if [ -n "$flac2mp3_output" ]; then
flac2mp3_message+=", Output: ${flac2mp3_output}"
fi
if [ $flac2mp3_keep = 1 ]; then
flac2mp3_message+=", Keep source"
fi
flac2mp3_message+=", Track(s): ${flac2mp3_tracks}"
echo "${flac2mp3_message}" | log
echo "$flac2mp3_tracks" | awk -v Debug=$flac2mp3_debug \
echo -n "$flac2mp3_tracks" | awk -v Debug=$flac2mp3_debug \
-v Recycle="$flac2mp3_recyclebin" \
-v Bitrate="$flac2mp3_bitrate" \
-v VBR="$flac2mp3_vbrquality" \
-v FFmpegADV="$flac2mp3_ffmpegadv" \
-v EXT="$flac2mp3_extension" '
-v EXT="$flac2mp3_extension" \
-v Output="$flac2mp3_output" \
-v Keep="$flac2mp3_keep" '
BEGIN {
FFmpeg="/usr/bin/ffmpeg"
FS="|"
@ -314,49 +468,53 @@ BEGIN {
IGNORECASE=1
if (EXT == "") EXT=".mp3"
if (Bitrate) {
if (Debug) print "Debug|Using constant bitrate of "Bitrate
if (Debug >= 1) print "Debug|Using constant bitrate of "Bitrate
BrCommand="-b:a "Bitrate
} else if (VBR) {
if (Debug) print "Debug|Using variable quality of "VBR
} else if (VBR >= 0) {
if (Debug >= 1) print "Debug|Using variable quality of "VBR
BrCommand="-q:a "VBR
} else if (FFmpegADV) {
if (Debug) print "Debug|Using advanced ffmpeg options: \""FFmpegADV"\""
if (Debug) print "Debug|Exporting with file extension "EXT
if (Debug >= 1) print "Debug|Using advanced ffmpeg options: \""FFmpegADV"\""
if (Debug >= 1) print "Debug|Exporting with file extension "EXT
}
}
/\.flac/ {
/\.flac$/ {
# Get each FLAC file name and create a new MP3 (or other) name
Track=$1
sub(/\n/,"",Track)
NewTrack=substr(Track, 1, length(Track)-5) EXT
# Redirect output if asked
if (Output) sub(/^.*\//,Output ,NewTrack)
print "Info|Writing: "NewTrack
# Check for advanced options
if (FFmpegADV) FFmpegOPTS=FFmpegADV
else FFmpegOPTS="-c:v copy -map 0 -y -acodec libmp3lame "BrCommand" -write_id3v1 1 -id3v2_version 3"
# Convert the track
if (Debug) print "Debug|Executing: nice "FFmpeg" -loglevel error -i \""Track"\" "FFmpegOPTS" \""NewTrack"\""
if (Debug >= 1) print "Debug|Executing: nice "FFmpeg" -loglevel error -i \""Track"\" "FFmpegOPTS" \""NewTrack"\""
Result=system("nice "FFmpeg" -loglevel error -i \""Track"\" "FFmpegOPTS" \""NewTrack"\" 2>&1")
if (Result) {
print "Error|Exit code "Result" converting \""Track"\""
} else {
if (Recycle == "") {
# No Recycle Bin, so check for non-zero size new file and delete the old one
if (Debug) print "Debug|Deleting: \""Track"\" and setting permissions on \""NewTrack"\""
#Command="[ -s \""NewTrack"\" ] && [ -f \""Track"\" ] && chown --reference=\""Track"\" \""NewTrack"\" && chmod --reference=\""Track"\" \""NewTrack"\" && rm \""Track"\""
Command="if [ -s \""NewTrack"\" ]; then if [ -f \""Track"\" ]; then chown --reference=\""Track"\" \""NewTrack"\"; chmod --reference=\""Track"\" \""NewTrack"\"; rm \""Track"\"; fi; fi"
if (Debug) print "Debug|Executing: "Command
system(Command)
if (Keep == 1) {
# Do not delete the source file
if (Debug >= 1) print "Debug|Keeping original: \""Track"\" and setting permissions on \""NewTrack"\""
Command="if [ -s \""NewTrack"\" ]; then if [ -f \""Track"\" ]; then chown --reference=\""Track"\" \""NewTrack"\"; chmod --reference=\""Track"\" \""NewTrack"\"; fi; fi"
} else {
# Recycle Bin is configured, so check if it exists, append a relative path to it from the track, check for non-zero size new file, and move the old one to the Recycle Bin
match(Track,/^\/?[^\/]+\//)
RecPath=substr(Track,RSTART+RLENGTH)
sub(/[^\/]+$/,"",RecPath)
RecPath=Recycle RecPath
if (Debug) print "Debug|Recycling: \""Track"\" to \""RecPath"\" and setting permissions on \""NewTrack"\""
Command="if [ ! -e \""RecPath"\" ]; then mkdir -p \""RecPath"\"; fi; if [ -s \""NewTrack"\" ]; then if [ -f \""Track"\" ]; then chown --reference=\""Track"\" \""NewTrack"\"; chmod --reference=\""Track"\" \""NewTrack"\"; mv -t \""RecPath"\" \""Track"\"; fi; fi"
if (Debug) print "Debug|Executing: "Command
system(Command)
if (Recycle == "") {
# No Recycle Bin, so check for non-zero size new file and delete the old one
if (Debug >= 1) print "Debug|Deleting: \""Track"\" and setting permissions on \""NewTrack"\""
Command="if [ -s \""NewTrack"\" ]; then if [ -f \""Track"\" ]; then chown --reference=\""Track"\" \""NewTrack"\"; chmod --reference=\""Track"\" \""NewTrack"\"; rm \""Track"\"; fi; fi"
} else {
# Recycle Bin is configured, so check if it exists, append a relative path to it from the track, check for non-zero size new file, and move the old one to the Recycle Bin
match(Track,/^\/?[^\/]+\//)
RecPath=substr(Track,RSTART+RLENGTH)
sub(/[^\/]+$/,"",RecPath)
RecPath=Recycle RecPath
if (Debug >= 1) print "Debug|Recycling: \""Track"\" to \""RecPath"\" and setting permissions on \""NewTrack"\""
Command="if [ ! -e \""RecPath"\" ]; then mkdir -p \""RecPath"\"; fi; if [ -s \""NewTrack"\" ]; then if [ -f \""Track"\" ]; then chown --reference=\""Track"\" \""NewTrack"\"; chmod --reference=\""Track"\" \""NewTrack"\"; mv -t \""RecPath"\" \""Track"\"; fi; fi"
}
}
if (Debug >= 2) print "Debug|Executing: "Command
system(Command)
}
}
' | log
@ -365,15 +523,20 @@ BEGIN {
# Check for awk script completion
flac2mp3_return="${PIPESTATUS[1]}" # captures awk exit status
if [ $flac2mp3_return != "0" ]; then
flac2mp3_message="Error|Script exited abnormally. File permissions issue?"
if [ "$flac2mp3_return" != 0 ]; then
flac2mp3_message="Error|[$flac2mp3_return] Script exited abnormally. File permissions issue?"
echo "$flac2mp3_message" | log
echo "$flac2mp3_message" >&2
exit 10
fi
# Call Lidarr API to RescanArtist
if [ -n "$flac2mp3_api_url" ]; then
if [ "$flac2mp3_type" = "batch" ]; then
[ $flac2mp3_debug -ge 1 ] && echo "Debug|Cannot use API in batch mode." | log
elif [ $flac2mp3_keep -eq 1 ]; then
echo "Info|Original audio file(s) kept, no rescan performed." | log
elif [ -n "$flac2mp3_api_url" ]; then
# Check for artist ID
if [ "$lidarr_artist_id" ]; then
# Scan the disk for the new audio tracks
if rescan; then