pymp4: MP4 Box Parser

1.4.0 · active · verified Tue Apr 14

pymp4 is a Python library designed for parsing MP4 boxes, providing a structured way to read and interpret the internal components of an MP4 file. It focuses on low-level access to box data. The current version is 1.4.0, and releases occur periodically, often in response to bug fixes or new box definitions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pymp4` to parse top-level boxes from an MP4 file. It creates a simple dummy MP4 file for demonstration, then uses `BoxParser` to iterate through and print information about the parsed boxes. In a real application, you would replace the dummy file creation with opening an existing MP4 file.

import os
from pymp4.parser import BoxParser

# For demonstration, we'll create a dummy MP4 file.
# In a real scenario, you would open an existing MP4 file.
dummy_mp4_path = "dummy_test.mp4"
try:
    # A minimal, valid MP4 often starts with an 'ftyp' box.
    # This is not a full MP4 file, just a placeholder to demonstrate parsing.
    # Real files are more complex and would have many more boxes.
    with open(dummy_mp4_path, "wb") as f:
        f.write(b'\x00\x00\x00\x18ftypisom\x00\x00\x00\x01isomiso2avc1mp41')
        f.write(b'\x00\x00\x00\x08moov') # Placeholder for a moov box

    # Initialize the parser
    parser = BoxParser()

    # Open the MP4 file in binary read mode
    with open(dummy_mp4_path, "rb") as f:
        # Parse all top-level boxes
        print(f"Parsing boxes from '{dummy_mp4_path}':")
        for box in parser.parse(f):
            print(f"  Parsed Box: type={box.type.decode('ascii')}, size={box.size}")
            if box.type == b'ftyp':
                print(f"    Major Brand: {box.major_brand.decode('ascii')}")
                print(f"    Minor Version: {box.minor_version}")
                print(f"    Compatible Brands: {[b.decode('ascii') for b in box.compatible_brands]}")
            elif box.type == b'moov':
                print(f"    (This is a placeholder moov box. Real ones contain child boxes like 'trak', 'mvhd' etc.)")

except FileNotFoundError:
    print(f"Error: Dummy file '{dummy_mp4_path}' could not be created or found.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    # Clean up the dummy file
    if os.path.exists(dummy_mp4_path):
        os.remove(dummy_mp4_path)
        print(f"Cleaned up '{dummy_mp4_path}'.")

view raw JSON →