Blog-Archiv

Mittwoch, 18. September 2024

Slow Motion or Time Lapse with ffmpeg

Sometimes you want to slow down or speed up your H264 codec video (mind that this works smoothly only for videos without audio-track!). Here is a UNIX shell-script to do this losslessly when ffmpeg is installed. If you pass e.g. myVideo.mp4 as first parameter, the script will generate a new video-file named myVideo_timed.mp4 in the directory where the original video resides.

fileMarker=timed

[ -z "$1" -o ! -f "$1" ] && {
	echo "SYNTAX: $0 videoFile [framesPerSecond]" >&2
	echo "	Slows down or speeds up given video, creating an xxx_$fileMarker.mp4 file." >&2
	echo "	framesPerSecond default is 15, which is half speed of normal 30 fps." >&2
	exit 1
}

sourceVideo=$1
sourceDir=`dirname \$sourceVideo`
sourceFile=`basename \$sourceVideo`
filename=${sourceFile%.*}	# filename without extension
extension=${sourceFile#*.}	# extension without filename
targetVideo=$sourceDir/${filename}_$fileMarker.$extension

framesPerSecond=15
[ -n "$2" ] && framesPerSecond=$2

tempRawFile=raw.h264

cleanup()	{
	rm -rf $tempRawFile
}
error()	{
	cleanup
	exit $1
}

# copy the video to a raw bitstream format
ffmpeg -v error -y -i $sourceVideo -map 0:v -c:v copy -bsf:v h264_mp4toannexb $tempRawFile || error 2

# generate new timestamps while muxing to a container
ffmpeg -v error -y -fflags +genpts -r $framesPerSecond -i $tempRawFile -c:v copy $targetVideo || error 3

cleanup

echo "Created $targetVideo"

Normally the frames-per-second value is something like 30. By default the script will slow down the video by 50% when you do not pass an explicit FPS-value as second argument to the script call (framesPerSecond=15). If you pass a value of 60, the video will play in double speed.




Keine Kommentare: