Skip to content

Instantly share code, notes, and snippets.

@vdugnist
Last active January 30, 2017 13:24
Show Gist options
  • Save vdugnist/e8f2357d341df9e4b6b78f0a46992c5b to your computer and use it in GitHub Desktop.
Save vdugnist/e8f2357d341df9e4b6b78f0a46992c5b to your computer and use it in GitHub Desktop.
Small script for video crop.
#!/bin/bash
# Small script for video crop. It takes a file as an argument.
# File format: source_name start_time end_time destination_name
# Example: GOPR0766.MP4 16:50 17:10 example
folder_name="croppy_result"
array_contains() {
local e
for e in "${@:2}"; do
[[ "$e" == "$1" ]] && return 0;
done
return 1
}
seconds_from_time() {
minutes=$(cut -d ":" -f 1 <<< "$1")
seconds=$(cut -d ":" -f 2 <<< "$1")
result=$((10#$minutes * 60 + 10#$seconds))
echo $result
}
# Check if directory contains all files listed in passed config
missing_files=()
while read Fn St Et Rn; do
if [ ! -r $Fn ]; then
missing_files+=($Fn)
fi
done < $1
if [ -n "$missing_files" ]; then
echo "Can't find files: "${missing_files[@]}""
exit 1
fi
# Check if all passed times less then video duration
out_of_bounds=0
while read Fn St Et Rn; do
duration_seconds=$(ffprobe -v quiet -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $Fn | cut -d '.' -f 1)
start_time_seconds=$(seconds_from_time $St)
end_time_seconds=$(seconds_from_time $Et)
if [ $start_time_seconds -gt $duration_seconds ] || [ $end_time_seconds -gt $duration_seconds ]; then
echo "Out of bounds: $Fn"
out_of_bounds=1
fi
done < $1
if [ $out_of_bounds -gt 0 ]; then
exit 1
fi
# Create result directory
mkdir ./$folder_name
# Crop
filenames=()
while read Fn St Et Rn; do
filename=$Rn
# Add suffix for duplicate files
if array_contains "$filename" "${filenames[@]}"; then
i=2
while array_contains "$filename$i" "${filenames[@]}"; do
let i++
done
filename="$filename$i"
fi
filenames+=($filename)
ffmpeg -i $Fn -ss $St -to $Et -vcodec libx264 ./$folder_name/$filename.mp4 < /dev/null
done < $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment