Skip to content

Instantly share code, notes, and snippets.

@vdakalov
Last active February 1, 2023 16:45
Show Gist options
  • Save vdakalov/3e5975fd0fe3019fa465760c8734b91d to your computer and use it in GitHub Desktop.
Save vdakalov/3e5975fd0fe3019fa465760c8734b91d to your computer and use it in GitHub Desktop.
Find all video of the series, trim splash screen for each of them, keep and reorder two audio streams and make first by default
#!/usr/bin/env bash
source="/home/user/source"
target="/home/user/target"
find "$source" -type f -name "*.mkv" -print0 | while read -d $'\0' f; do
name=$(basename "$f" .mkv)
echo "$name"
ss=$(ffprobe -i "$f" 2>&1 | grep "Chapter #0:1" | grep -Eo "[0-9.]+" | head -3 | tail +3)
ss=$(echo $ss + 7 | bc)
ffmpeg \
-v error \
-nostdin \
-y \
-i "$f" \
-ss "$ss" \
-map 0:v -c:v copy \
-map 0:a:1 -c:a:0 copy \
-map 0:a:0 -c:a:1 copy \
-disposition:a:0 default \
-async 1 \
"$target/$name.mkv"
done
@vdakalov
Copy link
Author

vdakalov commented Jan 17, 2023

find "$source" -type f -name "*.mkv" -print0 | while read -d $'\0' f; do - just a fucking magic about find all video files and look up through each of them

ffprobe options:

  • ffprobe -i "$f" 2>&1 - outputs information into stdout
  • grep "Chapter #0:1" - find line with information about second chapter
  • grep -Eo "[0-9.]+" - extract any numbers from the line and print each on own line
  • head -3 - keep only first three lines
  • tail +3 - skip first two lines

ss=$(echo $ss + 7 | bc) - I don't know why but ffmpeg starts to cut the video at ~7 seconds early than specified, so this is the correction

ffmpeg options:

  • -v error - show only errors
  • -nostdin - ignore any data from stdin
  • -y - overwrite existent target files w/o any questions
  • -i "$f" input file
  • -ss "$ss" splash screen ends time
  • -map 0:v -c:v copy - copy video stream from file #0 into output file
  • -map 0:a:1 -c:a:0 copy - copy audio stream #1 from file #0 into stream #0 of output file
  • -map 0:a:0 -c:a:1 copy - copy audio stream #0 from file #0 into stream #1 of output file
  • -disposition:a:0 default - make audio stream #0 default
  • -async 1 not sure about it, probably may be removed
  • "$target/$name.mkv" - output file

@vdakalov
Copy link
Author

vdakalov commented Feb 1, 2023

If the stream disposition doesn't apply and first stream is remains default prepend this option with -disposition:s:0 0 that remove default disposition of the first stream.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment