Skip to content
Brian Sherson edited this page May 17, 2020 · 2 revisions

Welcome to the python-matroska wiki!

How can I iterate through all packets in a Matroska file?

import matroska

f = matroska.MatroskaFile("movie.mkv", "r")

for packet in f.demux():
    # Do stuff

How can I iterate through packets from only a select stream?

This example shows how to iterate through packets of only track 1.

import matroska

f = matroska.MatroskaFile("movie.mkv", "r")

for packet in f.demux(trackEntry=1):
    # Do stuff

How can I iterate through packets starting at a specific time?

This example shows how to iterate through packets starting 10 seconds into a stream.

import matroska

f = matroska.MatroskaFile("movie.mkv", "r")

for packet in f.demux(start_pts=10):
    # Do stuff

How can I decode packets?

Packet decoding is not supported, nor is intended to be supported. For decoding, you can use PyAV.

This example assumes the stream is HEVC. It is strongly recommended you start demuxing at a keyframe.

import matroska
import av

f = matroska.MatroskaFile("movie.mkv", "r")
hevc = av.CodecContext.create("hevc", "r")

# Need to feed the decoder private data before decoding can begin.
hevc.extradata = f.tracks.byTrackNumber[1].codecPrivate

for packet in f.demux(trackNumber=1):
    # Need to convert to av.packet.Packet
    avpkt = av.packet.Packet(packet.data)
    avpkt.time_base = 10**9
    avpkt.pts = packet.pts

    for frame in hevc.decode(avpkt):
        # Do stuff