Skip to content

Instantly share code, notes, and snippets.

@oznek
Created April 8, 2014 21:43

Revisions

  1. oznek created this gist Apr 8, 2014.
    76 changes: 76 additions & 0 deletions build-mkv-with-subtitles
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    #!/bin/bash
    # Build MKV file with subtitles inside
    # Author: Kenzo Okamura

    # This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.

    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    # GNU General Public License at <http://www.gnu.org/licenses/> for
    # more details.

    ME=$(readlink -f "$0")
    SCRIPT_NAME=$(basename "$ME")
    MKVMERGE=$(which mkvmerge)

    if [ $# -ne 2 ];
    then
    echo "Builds an MKV with a subtitle file inside."
    echo "Subtitle file needs to have the same base name as video file."
    echo "(e.g. video.mp4 and video.srt)"
    echo ""
    echo "Usage:"
    echo " $SCRIPT_NAME <video file> <output directory>"
    exit 1
    fi

    input="$1"
    output_dir="$2"

    if [ ! -e "$input" ];
    then
    echo "Video file $input not found"
    exit 2
    fi

    if [ ! -d "$output_dir" ];
    then
    echo "Output directory $output_dir not found or is not a directory"
    exit 3
    fi

    base_name="$(echo $input | sed 's/\....$//')"

    extensions="srt sub"
    for ext in $extensions ; do
    srt=$base_name.$ext;
    if [[ -e $srt ]]; then break; fi
    done

    if [ ! -e "$srt" ];
    then
    echo "Subtitle for video not found"
    exit 4
    fi

    if [ ! -x "$MKVMERGE" ];
    then
    echo "You need mkvmerge to continue!"
    echo "(for Debian users: apt-get install mkvtoolnix)"
    fi

    echo "Base name: $base_name"
    echo "Input: $input"
    echo "Subtitles: $srt"
    echo "Output Dir: $output_dir"

    "$MKVMERGE" -o "$output_dir/$base_name.mkv" \
    --no-global-tags \
    --no-chapters "(" "$input" ")" \
    --forced-track 0:no \
    --no-global-tags \
    --no-chapters "(" "$srt" ")"