pymp4: MP4 Box Parser
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
- breaking The definition of `TrackEncryptionBox` (tenc) was significantly corrected in v1.4.0. Fields like `version`, `is_encrypted`, and `iv_size` now have strict value constraints.
- gotcha `pymp4` is exclusively a parser library. It is designed to read and interpret existing MP4 box structures but does not provide functionality for creating, modifying, or writing MP4 files.
- gotcha The library expects valid MP4 box structures. Parsing malformed or corrupted MP4 files may lead to exceptions, partial parsing, or incorrect data interpretation rather than graceful error recovery in all scenarios.
Install
-
pip install pymp4
Imports
- BoxParser
from pymp4.parser import BoxParser
- Box
from pymp4.dataclasses import Box
- ftyp
from pymp4.boxes import ftyp
Quickstart
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}'.")