Skip to content

Instantly share code, notes, and snippets.

@clayfreeman
Last active January 13, 2021 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clayfreeman/e10a5c344f9befc2afcc45ddb4b2bd64 to your computer and use it in GitHub Desktop.
Save clayfreeman/e10a5c344f9befc2afcc45ddb4b2bd64 to your computer and use it in GitHub Desktop.
A script to concatenate media files with matching codecs.
#!/bin/bash
set -euo pipefail
# A script to concatenate media files with matching codecs.
# Copyright (C) 2021 Clay Freeman
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# The license for this software can be found at the link below:
# https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
# Create a temporary file to hold the list of inputs.
FILE_LIST="$(mktemp)"
# Define a function used to clean up the temporary file list.
function clean_up() {
rm -f "$FILE_LIST"
}
# Define a function used to print a help message.
function print_help() {
if [ -n "${1-}" ]
then
echo "ERROR: $1" 1>&2
echo 1>&2
fi
echo "Usage: $0 output input [...]" 1>&2
exit 1
}
# Set up trap functions to capture certain events.
trap clean_up EXIT
trap print_help ERR
# Extract the name of the output file from the first argument.
OUTPUT_FILE="${1-}"
# Ensure that an output file was supplied.
if [ -z "$OUTPUT_FILE" ]
then
print_help "An output file is required."
else
shift
fi
# Build the input file list from all remaining arguments.
for file in "$@"
do
# Only add this file to the input list if it actually exists.
if [[ -f "$file" ]]
then
HAS_INPUT=1
printf 'file %q\n' "$(realpath "$file")"
fi
done > "$FILE_LIST"
# Ensure that there is at least one input file.
if [ -z "${HAS_INPUT-}" ]
then
print_help "At least one input file is required."
fi
# Log the job description to the error output stream.
cat <<EOF 1>&2
Output: "$OUTPUT_FILE"
Inputs
======
$(cat "$FILE_LIST")
EOF
# Concatenate the input files into a single file by copying.
ffmpeg -f concat -safe 0 -i "$FILE_LIST" -c copy "$OUTPUT_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment