Ubuntu – Batch convert H.265 mkv to H.264 with ffmpeg to make files compatible for re-encoding

batchcommand lineffmpegh264

I have H.265 encoded files that are so resource intensive they don't play well and my conversion software (mencoder) doesn't (currently) support the H.265 format. Can I convert them to H.264 in a command line batch file to rapidly convert the files for re-compression using Devede/OGMrip? Upon searching this site I have not found it discussed so I will post what I feel is a useful question and answer to the question.

Best Answer

Yes, using ffmpeg.

Open a terminal and direct it to the directory containing the H.265 encoded files, assuming you have ffmpeg and the appropriate libraries installed and assuming they are in MKV format copy and paste the following into the terminal window.

INPUT="$1"
for i in *.mkv ; do
    ffmpeg -i "$i" -bsf:v h264_mp4toannexb -sn -map 0:0 -map 0:1 -vcodec libx264 "$i.ts"
    mv "$i.ts" "$i.mpg"
    sleep 3
done

There you have it. This will convert to h.264 in an MPG container in the same directory.

Explanation of the command switches:

  • for i in *.mkv ; do ... done

    This sets up all .mkv files in a directory to be included in the batch process. This may be changed to accommodate the container extension of the files you wish to process.

  • ffmpeg -i "$i" Executes the program ffmpeg and calls for files to be processed.

    • -bsf:v activates the video bit stream filter to be used.

    • h264_mp4toannexb - Is the bit stream filter that is activated.

      Convert an H.264 bitstream from length prefixed mode to start code prefixed mode (as defined in the Annex B of the ITU-T H.264 specification).

      This is required by some streaming formats, typically the MPEG-2 transport stream format (mpegts) processing MKV h.264 (currently)requires this, if is not included you will get an error in the terminal window instructing you to use it.

    • -sn stops the streaming of subtitle streams (for those that do not want subtitles in their video) This is optional and can be removed.

    • -map 0:0 -map 0:1 Tells ffmpeg to only process the first two streams of the file (0:0 is the video stream, 0:1 is the first audio stream of the file). This does two things, strips the excess audio streams, usually the first audio stream is English but not always. Other streams such as embedded subtitles are removed reducing the file size. This is also an optional string. You can use ffprobe to view the streams available in the file. -map is optional and can be discarded from the command.

    • -vcodec libx264 This tells ffmpeg to encode the output to H.264

    • "$i.ts" Saves the output to .ts format, this is useful so as not to overwrite your source files.

  • mv "$i.ts" "$i.mpg" Converts the file extension to MPG in the same directory. This can be set up to send it to any directory you like.

  • sleep 3 - allows the process to rest giving ffmpeg time to queue the next file

Related Question