Skip to content

Instantly share code, notes, and snippets.

@ddelange
Created April 25, 2024 09:34
Show Gist options
  • Save ddelange/370a32b9d9da35f4b80d373306ce3cc2 to your computer and use it in GitHub Desktop.
Save ddelange/370a32b9d9da35f4b80d373306ce3cc2 to your computer and use it in GitHub Desktop.
Conditionally copy or encode video stream into avc (x264) mp4 with ffmpeg and ffprobe
#!/usr/bin/env bash
set -euxo pipefail
video_in="video_in.mkv"
video_out="video_out.mp4"
# full metadata payload: $(ffprobe -loglevel error -print_format json -show_format -show_streams "${video_in}")
is_avc=$(ffprobe -loglevel error -select_streams v:0 -show_entries stream=is_avc -of default=noprint_wrappers=1:nokey=1 "${video_in}")
if [ "${is_avc}" = "true" ]; then
# copy avc video stream (no re-encode), discard audio (-an), add faststart ref https://trac.ffmpeg.org/wiki/Encode/H.264#faststartforwebvideo
ffmpeg \
-y \
-hide_banner \
-loglevel \
error \
-i \
"${video_in}" \
-an \
-c:v \
copy \
-movflags \
+faststart \
"${video_out}"
else
# re-encode to avc (x264), discard audio (-an), add faststart ref https://trac.ffmpeg.org/wiki/Encode/H.264#faststartforwebvideo
ffmpeg \
-y \
-hide_banner \
-loglevel \
error \
-i \
"${video_in}" \
-an \
-c:v \
libx264 \
-crf \
18 \
-preset \
veryfast \
-movflags \
+faststart \
"${video_out}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment