MKVFile¶
MKVFile is the core class of pymkv. It is used to import, create, modify, and mux MKV files.
Examples
Below are some basic examples of how the MKVFile objects can be used.
Create and mux a new MKV. This example takes an standalone video and audio track and combines them into an MKV file.
>>> from pymkv import MKVFile
>>> mkv = MKVFile()
>>> mkv.add_track('/path/to/track.h264')
>>> mkv.add_track(MKVTrack('/path/to/track.aac'))
>>> mkv.mux('/path/to/output.mkv')
Generate the mkvmerge command to mux an MKV. This is example is identical to the first example except the command is only generated, not executed.
>>> mkv = MKVFile()
>>> mkv.add_track('/path/to/track.h264')
>>> mkv.add_track(MKVTrack('/path/to/another/track.aac'))
>>> mkv.command('/path/to/output.mkv')
Import an existing MKV and remove a track. This example will import an MKV that already exists on your filesystem, remove a track and allow you to mux that change into a new file.
>>> mkv = MKVFile('/path/to/file.mkv')
>>> mkv.get_track(0).track_name = 'Some Name'
>>> mkv.mux('/path/to/output.mkv')
Combine two MKVs. This example takes two existing MKVs and combines their tracks into a single MKV file.
>>> mkv1 = MKVFile('/path/to/file1.mkv')
>>> mkv2 = MKVFile('/path/to/file2.mkv')
>>> mkv1.add_file(mkv2)
>>> mkv1.mux('/path/to/output.mkv')
>>>
>>> # Use a progress handler to track muxing progress
>>> def progress(p):
... print(f"Progress: {p}%")
>>>
>>> mkv = MKVFile('/path/to/file.mkv')
>>> mkv.mux('/path/to/output.mkv', progress_handler=progress)
>>>
>>> # Inspect attachments from an existing file
>>> mkv = MKVFile('/path/to/with_attachments.mkv')
>>> for attachment in mkv.attachments:
... print(f"Attachment: {attachment.name}, MIME: {attachment.mime_type}")
-
class pymkv.MKVFile(file_path: str | PathLike | None =
None, title: str | None =None, mkvmerge_path: str | PathLike | Iterable[str] ='mkvmerge')¶ A class that represents an MKV file.
The
MKVFileclass can either import a pre-existing MKV file or create a new one. After anMKVFileobject has been instantiated,MKVTrackobjects or otherMKVFileobjects can be added usingadd_track()andadd_file()respectively.Tracks are always added in the same order that they exist in a file or are added in. They can be reordered using
move_track_front(),move_track_end(),move_track_forward(),move_track_backward(), orswap_tracks().After an
MKVFilehas been created, an mkvmerge command can be generated usingcommand()or the file can be muxed usingmux().- Parameters:¶
- file_path : str, optional¶
Path to a pre-existing MKV file. The file will be imported into the new
MKVFileobject.- title : str, optional¶
The internal title given to the
MKVFile. If title is not specified, the title of the pre-existing file will be used if it exists.- mkvmerge_path : str, optional¶
The path where pymkv looks for the mkvmerge executable. pymkv relies on the mkvmerge executable to parse files. By default, it is assumed mkvmerge is in your shell’s $PATH variable. If it is not, you need to set mkvmerge_path to the executable location.
- Raises:¶
FileNotFoundError – Raised if the path to mkvmerge could not be verified.
- add_attachment(attachment: str | MKVAttachment) None¶
Add an attachment to the
MKVFile.- Parameters:¶
- attachment: str | MKVAttachment¶
The attachment to be added to the
MKVFileobject.
- Raises:¶
TypeError – Raised if if attachment is not a string-like path to an attachment file or an
MKVAttachment.
Examples
>>> mkv = MKVFile() >>> # Add attachment from file path >>> mkv.add_attachment('cover.jpg') >>> # Add MKVAttachment object >>> att = MKVAttachment('font.ttf', name='Font') >>> mkv.add_attachment(att)
- add_file(file: MKVFile | str | PathLike) None¶
Add an MKV file into the
MKVFileobject.- Parameters:¶
- Raises:¶
TypeError – Raised if if file is not a string-like path to an MKV file or an
MKVFileobject.
Examples
>>> mkv1 = MKVFile('part1.mkv') >>> mkv2 = MKVFile('part2.mkv') >>> # Concatenate mkv2 to mkv1 >>> mkv1.add_file(mkv2) >>> # Add file directly from path >>> mkv1.add_file('part3.mkv')
-
add_track(track: str | MKVTrack, new_file: bool =
True) None¶ Add a track to the
MKVFile.- Parameters:¶
- Raises:¶
TypeError – Raised if track is not a string-like path to a track file or an
MKVTrack.
Examples
>>> mkv = MKVFile() >>> # Add a track from a file path >>> mkv.add_track('video.h264') >>> # Add an MKVTrack object >>> track = MKVTrack('audio.aac', language='eng') >>> mkv.add_track(track)
- property chapter_language : str | None¶
Get the language code of the chapters in the MKVFile object.
-
chapters(file_path: str, language: str | None =
None) None¶ Add a chapters file to the
MKVFileobject.
-
command(output_path: str, subprocess: bool =
False) str | list[str]¶ Generates an mkvmerge command based on the configured
MKVFile.- Parameters:¶
- Returns:¶
The full command to mux the
MKVFileas a string containing spaces. Will be returned as a list of strings with no spaces if subprocess is True.- Return type:¶
str, list of str
Examples
>>> mkv = MKVFile() >>> mkv.add_track('path/to/track.h264') >>> # Generate command string >>> cmd_str = mkv.command('output.mkv') >>> print(cmd_str) mkvmerge -o output.mkv path/to/track.h264 >>> # Generate command list for subprocess >>> cmd_list = mkv.command('output.mkv', subprocess=True) >>> print(cmd_list) ['mkvmerge', '-o', 'output.mkv', 'path/to/track.h264']
- static flatten(item: Any) list[Any]¶
Flatten a list or a tuple.
Takes a list or a tuple that contains other lists or tuples and flattens into a non-nested list.
Examples
>>> tup = ((1, 2), (3, (4, 5))) >>> MKVFile.flatten(tup) [1, 2, 3, 4, 5]>>> tup = (["abc", "d"]) >>> MKVFile.flatten(tup) ['abc', 'd']
-
get_attachment(attachment_num: int | None =
None) MKVAttachment | list[MKVAttachment]¶ Get an
MKVAttachmentfrom theMKVFileobject.- Parameters:¶
- attachment_num : int, optional¶
Index of attachment to retrieve. Will return a list of
MKVAttachmentobjects if argument is not provided.
- Returns:¶
A list of all
MKVAttachmentobjects in aMKVFile. Returns a specificMKVAttachmentif attachment_num is specified.- Return type:¶
MKVAttachment, list ofMKVAttachment
-
get_track(track_num: int | None =
None) MKVTrack | list[MKVTrack]¶ Get a
MKVTrackfrom theMKVFileobject.- Parameters:¶
- Returns:¶
A list of all
MKVTrackobjects in anMKVFile. Returns a specificMKVTrackif track_num is specified.- Return type:¶
Examples
>>> mkv = MKVFile('input.mkv') >>> # Get all tracks >>> all_tracks = mkv.get_track() >>> # Get the first track >>> first_track = mkv.get_track(0)
- property global_tag_entries : int¶
Gets the number of global tag entries in the MKVFile object.
- link_to_none() None¶
Remove all linking to previous and next files.
This method clears any existing links to previous or next files, effectively removing the file linking options for the current MKVFile object.
- link_to_previous(file_path: str) None¶
Link the output file as the predecessor of the file_path file.
- move_track_backward(track_num: int) None¶
Move a track backward in the
MKVFileobject.- Parameters:¶
- track_num : int¶
The track number of the track to move backward.
- Raises:¶
IndexError – Raised if track_num is is out of range of the track list.
Examples
>>> mkv = MKVFile() >>> mkv.add_track('track1.mkv') >>> mkv.add_track('track2.mkv') >>> mkv.move_track_backward(1)
- move_track_end(track_num: int) None¶
Set as track as the last in the
MKVFileobject.- Parameters:¶
- track_num : int¶
The track number of the track to move to the back.
- Raises:¶
IndexError – Raised if track_num is is out of range of the track list.
Examples
>>> mkv = MKVFile() >>> mkv.add_track('track1.mkv') >>> mkv.add_track('track2.mkv') >>> mkv.move_track_end(0)
- move_track_forward(track_num: int) None¶
Move a track forward in the
MKVFileobject.- Parameters:¶
- track_num : int¶
The track number of the track to move forward.
- Raises:¶
IndexError – Raised if track_num is is out of range of the track list.
Examples
>>> mkv = MKVFile() >>> mkv.add_track('track1.mkv') >>> mkv.add_track('track2.mkv') >>> mkv.move_track_forward(0)
- move_track_front(track_num: int) None¶
Set a track as the first in the
MKVFileobject.- Parameters:¶
- track_num : int¶
The track number of the track to move to the front.
- Raises:¶
IndexError – Raised if track_num is is out of range of the track list.
Examples
>>> mkv = MKVFile() >>> mkv.add_track('track1.mkv') >>> mkv.add_track('track2.mkv') >>> mkv.move_track_front(1)
-
mux(output_path: str | PathLike, silent: bool =
False, ignore_warning: bool =False, progress_handler: Callable[[int], None] | None =None) int¶ Mixes the specified
MKVFile.- Parameters:¶
- output_path : str¶
The path to be used as the output file in the mkvmerge command.
- silent : bool, optional¶
By default the mkvmerge output will be shown unless silent is True.
- ignore_warning : bool, optional¶
If set to True, the muxing process will ignore any warnings (exit code 1) from mkvmerge.
- progress_handler : Callable[[int], None], optional¶
A callback function that will be called with the current progress percentage (0-100).
- Returns:¶
return code
- Return type:¶
int
- Raises:¶
ValueError – Raised if the external mkvmerge command fails with a non-zero exit status (except for warnings when ignore_warning is True).
Examples
>>> mkv = MKVFile() >>> mkv.add_track('video.h264') >>> # Basic muxing >>> mkv.mux('output.mkv') 0 >>> # Muxing silently >>> mkv.mux('output.mkv', silent=True) 0 >>> # Muxing with progress handler >>> def progress(p): ... print(f"Progress: {p}%") >>> mkv.mux('output.mkv', progress_handler=progress) 0
- no_attachments() None¶
Ignore the existing attachments of all tracks in the
MKVFileobject.This method sets the no_attachments attribute to True for all tracks in the MKVFile.
- no_chapters() None¶
Ignore the existing chapters of all tracks in the
MKVFileobject.This method sets the no_chapters attribute to True for all tracks in the MKVFile.
- no_global_tags() None¶
Ignore the existing global tags of all tracks in the
MKVFileobject.This method sets the no_global_tags attribute to True for all tracks in the MKVFile.
- no_track_tags() None¶
Ignore the existing track tags of all tracks in the
MKVFileobject.This method sets the no_track_tags attribute to True for all tracks in the MKVFile.
- order_tracks_by_file_id() None¶
Assigns file IDs to tracks based on their source files.
Creates a mapping of unique file paths to numeric IDs, then assigns each track a file ID corresponding to its source file. Tracks from the same file will have the same file ID.
This method modifies the file_id attribute of each track in self.tracks.
- remove_all_attachments() None¶
Remove all attachments from the
MKVFileobject.This will clear the attachment list, effectively removing all attachments that would otherwise be included in the output file.
- remove_attachment(attachment_num: int) None¶
Remove an attachment from the
MKVFileobject.
- remove_track(track_num: int) None¶
Remove a track from the
MKVFileobject.- Parameters:¶
- track_num : int¶
The track number of the track to remove.
- Raises:¶
IndexError – Raised if track_num is is out of range of the track list.
Examples
>>> mkv = MKVFile() >>> mkv.add_track('t1.mkv') >>> mkv.remove_track(0)
- replace_track(track_num: int, track: MKVTrack) None¶
Replace a track with another track in the
MKVFileobject.Examples
>>> mkv = MKVFile() >>> mkv.add_track('t1.mkv') >>> mkv.replace_track(0, MKVTrack('new.mkv'))
-
split_chapters(*chapters: int | Iterable[int], link: bool =
False) None¶ Split the output file into parts by chapters.
-
split_duration(duration: str | int, link: bool | None =
False) None¶ Split the output file into parts by duration.
- Parameters:¶
- duration : str, int¶
The duration of each split file. Takes either a str formatted to HH:MM:SS.nnnnnnnnn or an integer representing the number of seconds. The duration string requires formatting of at least M:S.
- link : bool, optional¶
Determines if the split files should be linked together after splitting.
Examples
>>> mkv = MKVFile('input.mkv') >>> # Split every 1 minute >>> mkv.split_duration('00:01:00') >>> # Split every 600 seconds >>> mkv.split_duration(600)
-
split_frames(*frames: int | Iterable[int], link: bool | None =
False) None¶ Split the output file into parts by frames.
- Parameters:¶
- Raises:¶
TypeError – Raised if non-int frames are passed in for *frames or within the *frames iterable.
ValueError – Raised if improperly formatted frames are passed in for *frames.
Examples
>>> mkv = MKVFile('input.mkv') >>> # Split at specific frame numbers >>> mkv.split_frames(1000, 5000)
- split_none() None¶
Remove all splitting options.
-
split_parts_frames(frame_parts: Iterable[int], link: bool | None =
False) None¶ Split the output in parts by frames.
- Parameters:¶
- frame_parts : list, tuple¶
An Iterable of frame sets. Each frame set should be an
Iterableobject of an even number of frames or any number of frame pairs. The very first and last frames are permitted to be None. Frame sets containing four or more frames will output as one file containing the parts specified.- link : bool, optional¶
Determines if the split files should be linked together after splitting.
- Raises:¶
TypeError – Raised if any of the frame sets are not a list or tuple.
ValueError – Raised if frame_parts contains improperly formatted parts.
-
split_size(size: Bitmath | int, link: bool | None =
False) None¶ Split the output file into parts by size.
Examples
>>> import bitmath >>> mkv = MKVFile('input.mkv') >>> # Split by 100MB >>> mkv.split_size(100 * 1024 * 1024) >>> # Split by bitmath object >>> mkv.split_size(bitmath.MiB(50))
-
split_timestamp_parts(timestamp_parts: Iterable[list[str] | tuple[str, ...]], link: bool | None =
False) None¶ Split the output in parts by time parts.
- Parameters:¶
- timestamp_parts : list, tuple¶
An Iterable of timestamp sets. Each timestamp set should be an Iterable of an even number of timestamps or any number of timestamp pairs. The very first and last timestamps are permitted to be None. Timestamp sets containing 4 or more timestamps will output as one file containing the parts specified.
- link : bool, optional¶
Determines if the split files should be linked together after splitting.
- Raises:¶
TypeError – Raised if any of the timestamp sets are not a list or tuple.
ValueError – Raised if timestamp_parts contains improperly formatted parts.
-
split_timestamps(*timestamps: Iterable[str | int], link: bool | None =
False) None¶ Split the output file into parts by timestamps.
- Parameters:¶
- *timestamps : Iterable[str | int]¶
The timestamps to split the file by. Can be passed as any combination of strs and ints, inside or outside an
Iterableobject. Any lists will be flattened. Timestamps must be ints, representing seconds, or strs in the form HH:MM:SS.nnnnnnnnn. The timestamp string requires formatting of at least M:S.- link : bool, optional¶
Determines if the split files should be linked together after splitting.
- Raises:¶
ValueError – Raised if invalid or improperly formatted timestamps are passed in for *timestamps.
Examples
>>> mkv = MKVFile('input.mkv') >>> # Split at specific timestamps >>> mkv.split_timestamps('00:01:00', '00:05:30') >>> # Split at seconds >>> mkv.split_timestamps(60, 330)
- swap_tracks(track_num_1: int, track_num_2: int) None¶
Swap the position of two tracks in the
MKVFileobject.- Parameters:¶
- Raises:¶
IndexError – Raised if track_num_1 or track_num_2 are out of range of the track list.
Examples
>>> mkv = MKVFile() >>> mkv.add_track('track1.mkv') >>> mkv.add_track('track2.mkv') >>> mkv.swap_tracks(0, 1)
-
track_tags(*track_ids: int | list | tuple, exclusive: bool | None =
False) None¶ Include or exclude tags from specific tracks.
- Parameters:¶
Track ids to have tags included or excluded from.
Determines if the track_ids should have their tags kept or removed. exclusive is False by default and will remove tags from unspecified tracks.
- Raises:¶
IndexError – Raised if any ids from *track_ids is is out of range of the track list.
TypeError – Raised if an ids from *track_ids are not of type int.
ValueError – Raised if *track_ids are improperly formatted.