#!/bin/sh
# File: split-on-chapters.sh
# Location: /mnt/public/Support/Programs/DVDs
# Author: bgstack15
# Startdate: 2024-02-17-7 14:22
# Title: Split mkv on chapters
# Purpose: oneliner for splitting mkv file into separate files per chapter
# History:
#    2024-02-22 moved -ss and -to before -i
# Usage:
# Reference:
#    man ffmpeg
#    slightly improved over https://superuser.com/questions/795373/split-mkv-based-on-chapters
#    https://superuser.com/questions/795373/split-mkv-based-on-chapters/1830690#1830690
#    https://stackoverflow.com/questions/14005110/how-to-split-a-video-using-ffmpeg-so-that-each-chunk-starts-with-a-key-frame/33188399#33188399
# Improve:
# Dependencies:
# Documentation:
#    This is insufficient:
#       HandBrakeCLI -c 2 -i twoeps.mkv -o 2.mkv # this does not get subtitles, and reencodes which takes a while
#   WARNING! Jellyfin+chromecast might malfunction on a video split in this manner, within the first few seconds of playback, because of the keyframe/chapter mismatch.

split_by_chapter() {
   for word in "${@}" ;
   do
      ffmpeg -i "${word}" 2>&1 | sed -n -r -e "/start.*end.*[0-9]*/{s/.*#[0-9]*:([0-9]*).* ([0-9]*\.[0-9]*).*( [0-9]*\.[0-9]*)/ffmpeg -ss \2 -to\3 -i ${word} -acodec copy -vcodec copy -scodec copy ${word%%.mkv}-chapter\1.mkv \;/g;p;}"
   done
}

split_by_chapter "${@}"
