How to Attach PDF or Text Files to MKV Using FFmpeg

This article provides a straightforward guide on how to embed external document attachments, such as PDF files or license text, directly into an MKV (Matroska) video container using the FFmpeg command-line tool. You will learn the exact command-line syntax required to attach files, map their MIME types correctly, and verify the attachments without re-encoding your video.

The Basic Command Structure

The Matroska (MKV) container natively supports attachments like fonts, pictures, and text documents. To add an attachment using FFmpeg, you use the -attach option followed by the path to your file, and define the attachment’s MIME type using stream metadata.

Because you are only adding an attachment, you should use -c copy to copy the video, audio, and subtitle streams without re-encoding them. This makes the process nearly instantaneous.

Example 1: Attaching a PDF File

To attach a PDF document to an existing MKV file, use the following command:

ffmpeg -i input.mkv -attach document.pdf -metadata:s:t:0 mimetype=application/pdf -c copy output.mkv

Command breakdown: * -i input.mkv: Specifies the input video file. * -attach document.pdf: Tells FFmpeg to embed the specified file. * -metadata:s:t:0 mimetype=application/pdf: Sets the MIME type for the first attachment stream (s:t:0). Defining the MIME type is highly recommended so media players understand how to handle the file. * -c copy: Copies all existing video and audio streams without re-encoding. * output.mkv: The name of the new MKV file containing the attachment.

Example 2: Attaching a License or Text File

To attach a plain text file, such as a software license or read-me document, use text/plain as the MIME type:

ffmpeg -i input.mkv -attach license.txt -metadata:s:t:0 mimetype=text/plain -c copy output.mkv

Example 3: Attaching Multiple Files

You can attach multiple files in a single command. You must define the MIME type for each file sequentially by incrementing the attachment stream index (e.g., s:t:0, s:t:1):

ffmpeg -i input.mkv -attach document.pdf -attach license.txt \
-metadata:s:t:0 mimetype=application/pdf \
-metadata:s:t:1 mimetype=text/plain \
-c copy output.mkv

How to Verify the Attachments

Once the process is complete, you can verify that the documents were successfully embedded into the MKV container using ffprobe (which comes bundled with FFmpeg):

ffprobe output.mkv

Look at the output streams at the bottom of the report. You should see one or more attachment streams listed alongside your video and audio tracks, formatted like this:

Stream #0:2: Attachment: pdf
    Metadata:
      filename        : document.pdf
      mimetype        : application/pdf