Skip to content

Instantly share code, notes, and snippets.

@mohan43u
Created April 20, 2024 01:43
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 mohan43u/b9976edf1f650eb0407927602dee2f94 to your computer and use it in GitHub Desktop.
Save mohan43u/b9976edf1f650eb0407927602dee2f94 to your computer and use it in GitHub Desktop.
videoedit.sh
#!/bin/bash
convert_to_seconds() {
time="${1}"
timev=(${time//:/ })
timea[2]=1
timea[1]=60
timea[0]=$((60 * 60))
index=$(("${#timev[*]}"))
time_seconds=0
while [[ "${index}" -gt 0 ]]; do
index=$(("${index}" - 1))
value=$(echo "${timev[${index}]}" | sed 's/^ *0*//g')
[[ -z "${value}" ]] && value=0
multiplier="${timea[${index}]}"
time_seconds=$(("${time_seconds}" + ("${value}" * "${multiplier}")))
done
echo "${time_seconds}"
}
timeline_in_seconds() {
while read line; do
(echo "${line}" | grep -v '^[0-9:, ]*$') && {
echo "Invalid Input: contains chars other than [0-9:, ]: ${line}" 2>&1
echo "Example Input: 00:02:34, 00:04:43"
continue
}
timev=(${line//,/ })
start=$(convert_to_seconds "${timev[0]}")
end=$(convert_to_seconds "${timev[1]}")
duration=$(("${end}" - "${start}"))
duration=$([[ "${duration}" -lt 0 ]] && echo 0 || echo "${duration}")
echo "${start}" "${duration}"
done
}
split_video() {
video="${1}"
chunknum=0
timeline_in_seconds | while read offset duration; do
chunk="${video%.*}.${chunknum}.mp4"
chunknum=$(("${chunknum}" + 1))
[[ -e "${chunk}" ]] && continue
[[ "${duration}" -le 0 ]] && unset duration
ffmpeg -y -nostdin -hide_banner -hwaccel vaapi -ss "${offset}" ${duration:+-t ${duration}} -i "${video}" -autoscale 0 -filter_complex 'hwupload,scale_vaapi=1920:1080' -c:a aac -c:v h264_vaapi -profile:v constrained_baseline -ar 44100 -r 24 -b:a 128k -b:v 1000k "${chunk}"
done
}
join_video() {
video="${1}"
combined="${video%.*}.combined.mp4"
concatinput=$(mktemp)
defer_join_video() {
rm "${concatinput}"
}
trap defer_join_video EXIT
[[ -e "${combined}" ]] && return
split_video "${@}"
chunks=$(ls -1 "${video%.*}"* | grep '\.[0-9]*\.mp4$')
for video in ${chunks}; do
video=$(realpath "${video}")
echo "file ${video}" >>"${concatinput}"
done
ffmpeg -y -nostdin -hide_banner -hwaccel vaapi -f concat -safe 0 -i "${concatinput}" -c copy "${combined}"
}
join_video "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment