Created
January 21, 2019 12:43
-
-
Save gibatronic/08d1b944a4515712f4bdce194651a60c to your computer and use it in GitHub Desktop.
ffmpeg: scale up or down the duration of the given video
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Scale up or down the duration of the given video | |
# The final video will be in the mp4 format | |
# | |
# Usage: | |
# scale-duration <video-path> <desired-duration> | |
# | |
# Options: | |
# video-path The video to scale | |
# desired-duration In secods, the final duration fo the video | |
# | |
# Example: | |
# `scale-duration '/fake/path/video.mov' '10'` | |
# This will scale the video to 10 seconds in a | |
# new file called: '/fake/path/video.mov.mp4' | |
# | |
failure() { | |
local message=$1 | |
echo -e "\033[31m✖\033[0m $message" 1>&2 | |
} | |
success() { | |
local message=$1 | |
echo -e "\033[32m✓\033[0m $message" 1>&2 | |
} | |
main() { | |
local desired_duration=$2 | |
local log_path="$(mktemp -t "$$")" | |
local video_path=$1 | |
if [ -z "$video_path" ]; then | |
failure 'No ‘video-path’ was given' | |
return 1 | |
fi | |
if [ ! -r "$video_path" ]; then | |
failure 'Unable to read the given ‘video-path’' | |
return 1 | |
fi | |
if [ -z "$desired_duration" ]; then | |
failure 'No ‘desired-duration’ was given' | |
return 1 | |
fi | |
if [[ ! "$desired_duration" =~ "^[0-9]+(\.[0-9]+)?$|^0?\.[0-9]+$" ]]; then | |
failure '‘desired-duration’ must be an integer or float' | |
return 1 | |
fi | |
local current_duration=$(ffprobe -i "$video_path" 2>&1 -show_format -v quiet | grep duration | cut -d '=' -f 2) | |
local ratio=$(bc -l <<< "$desired_duration / $current_duration") | |
local video_folder=$(dirname "$video_path") | |
local video_name=$(basename "$video_path") | |
ffmpeg -i "$video_path" -filter:v "setpts=$ratio*PTS" "${video_path}.mp4" &> "$log_path" | |
local exit_code=$? | |
if [ "$exit_code" = 0 ]; then | |
echo -e "\033[32m✓\033[0m $video_name" | |
rm -f "$log_path" | |
return 0 | |
fi | |
echo -e "\033[31m✖\033[0m $video_name" | |
cat "$log_path" 1>&2 | |
rm -f "$log_path" | |
return 1 | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment