Skip to content

Instantly share code, notes, and snippets.

@juliarose

juliarose/clip

Last active Oct 26, 2020
Embed
What would you like to do?
clip last n seconds from recording in progress - usage "clipgameplay <footage directory> <seconds>"
#!/bin/bash
# the directory containing gameplay footage
DIR=$1
# the number of seconds to clip
SECONDS=$2
if [ -z $DIR ]; then
echo "No directory given"
# exit - this must be provided
exit 1
elif [[ ! -d "$DIR" ]]; then
echo "Not a directory"
# exit - this must be provided
exit 1
fi
if [ -z $SECONDS ]; then
# default to 20
SECONDS=20
fi
# cd into the directory containing gameplay footage
cd $DIR
# get the first file with "gameplay" in the name
FILENAME=`find $1 -name "gameplay*" -type f -print0 | xargs -0 stat --format '%n' | sort -nr | cut -d: -f2- | head -1`
# extract the date from filename
FULL_DATE=$(echo "$FILENAME" | grep -Eo '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}_[[:digit:]]{2}.[[:digit:]]{2}.[[:digit:]]{2}')
# get the date from the extracted date string
DATE=$(echo "$FULL_DATE" | grep -Eo '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}')
# get the time from extracted date string
TIME=$(echo "$FULL_DATE" | grep -Eo '[[:digit:]]{2}.[[:digit:]]{2}.[[:digit:]]{2}$' | sed -r 's/\.+/:/g')
# put them together and convert them to a timestamp
TIMESTAMP=`date --date="$DATE $TIME" +"%s"`
# get the current timestamp
CURRENT_TIMESTAMP=`date +%s`
# get how many seconds ago the timestamp is
SECONDS_AGO=`expr $CURRENT_TIMESTAMP - $TIMESTAMP`
# get the starting point
STARTING_POINT=`expr $SECONDS_AGO - $SECONDS`
# for trimming it down to the precise amount of seconds
NEGATIVE_SECONDS=`expr $SECONDS \* -1`
# sleep to sync with end of video
sleep 2
if [ "$STARTING_POINT" -lt 0 ]
then
# this must not be negative
STARTING_POINT=0
fi
# make the directory for clips
mkdir -p clip
FILEPATH="$DIR/clip/$CURRENT_TIMESTAMP.mkv"
TMP_FILEPATH="$DIR/clip/$CURRENT_TIMESTAMP-temp.mkv"
# make the clip
ffmpeg -ss $STARTING_POINT -i $FILENAME -t $SECONDS -c copy -c:v copy -c:a copy -preset:v ultrafast $FILEPATH
VIDEO_LENGTH=`ffprobe -i $FILEPATH -show_entries format=duration -v quiet -of csv="p=0"`
if [ "$VIDEO_LENGTH" -lt "$SECONDS" ]
then
# video is already short enough
exit 1
fi
# take the last seconds from the clip created
ffmpeg -sseof $NEGATIVE_SECONDS -i $FILEPATH -c:v copy -c:a copy -preset:v ultrafast $TMP_FILEPATH
# then replace the previous clip with the more precise trimmed down clip
mv $TMP_FILEPATH $FILEPATH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.