Skip to content

muxtools.helpers.extract

MKVExtract

MKVExtract(fileIn: PathLike, output: PathLike = None)

A helper for mkvextract to extract tracks and attachments without conversion.

Creates the mkvextract helper for a Matroska or WebM file.

Parameters:

Name Type Description Default
fileIn PathLike

File to extract from.

required
output PathLike

Default output directory. None uses get_workdir().

The directory will be created if it does not exist.

None
Source code in muxtools/helpers/extract.py
def __init__(self, fileIn: PathLike, output: PathLike = None) -> None:
    """
    Creates the mkvextract helper for a Matroska or WebM file.

    :param fileIn:              File to extract from.
    :param output:              Default output directory. `None` uses `get_workdir()`.\n
                                The directory will be created if it does not exist.
    """
    self._parsed = ParsedFile.from_file(fileIn, self, _allow_unknown_codecs=True)
    self._fileIn = self._parsed.source
    self.output = ensure_path(get_workdir() if output is None else output, self)
    if self.output.exists() and not self.output.is_dir():
        raise ValueError(f"Extraction output '{self.output}' is not a directory.")
    self.output.mkdir(parents=True, exist_ok=True)
    try:
        self._info = self._parsed.raw_mkvmerge or MKVInfo.from_file(self._fileIn, mkvmerge=get_executable("mkvmerge"))
    except Exception as exc:
        raise error(f"Could not parse '{self._fileIn.name}' as Matroska/WebM.", self) from exc
    container = self._info.container
    if not container.recognized or not container.supported or (container.type or "").casefold() not in {"matroska", "webm"}:
        raise ValueError(f"'{self._fileIn.name}' is not a supported Matroska/WebM file.")

    self._executable = get_executable("mkvextract")

video_track

video_track(track: int = 0, output: PathLike = None, quiet: bool = True, **kwargs: Any) -> VideoTrack

Extract a video track from the file.

The track name, language, default/forced flags and custom tags are inherited unless overridden.

Timestamps are extracted automatically to preserve variable frame rate and container timing.

Parameters:

Name Type Description Default
track int

Relative video track number, starting at 0.

0
output PathLike

Custom output. Can be an existing directory or a file.

None uses the default output directory of the helper.

The file extension will be set automatically.

None
quiet bool

Suppresses the output.

The stdout will still be printed on failure regardless of this setting.

True
kwargs Any

Any other parameters to pass to VideoTrack. These override inherited metadata.

Pass timecode_file to use existing timestamps instead of extracting them.

delay adds a shift in ms to the timestamped video.

{}

Returns:

Type Description
VideoTrack

The extracted video as a VideoTrack.

Source code in muxtools/helpers/extract.py
def video_track(self, track: int = 0, output: PathLike = None, quiet: bool = True, **kwargs: Any) -> VideoTrack:
    """
    Extract a video track from the file.

    The track name, language, default/forced flags and custom tags are inherited unless overridden.\n
    Timestamps are extracted automatically to preserve variable frame rate and container timing.

    :param track:               Relative video track number, starting at 0.
    :param output:              Custom output. Can be an existing directory or a file.\n
                                `None` uses the default output directory of the helper.\n
                                The file extension will be set automatically.

    :param quiet:               Suppresses the output.\n
                                The stdout will still be printed on failure regardless of this setting.

    :param kwargs:              Any other parameters to pass to `VideoTrack`. These override inherited metadata.\n
                                Pass `timecode_file` to use existing timestamps instead of extracting them.\n
                                `delay` adds a shift in ms to the timestamped video.

    :return:                    The extracted video as a `VideoTrack`.
    """
    return self._extract_track(VideoTrack, TrackType.VIDEO, track, output, quiet, **kwargs)

audio_track

audio_track(track: int = 0, output: PathLike = None, quiet: bool = True, **kwargs: Any) -> AudioTrack

Extract an audio track from the file without conversion.

The track name, language, default/forced flags and custom tags are inherited unless overridden.

The format has to be supported by AudioFormat. Existing container timing is preserved.

Parameters:

Name Type Description Default
track int

Relative audio track number, starting at 0.

0
output PathLike

Custom output. Can be an existing directory or a file.

None uses the default output directory of the helper.

The file extension will be set automatically.

None
quiet bool

Suppresses the output.

The stdout will still be printed on failure regardless of this setting.

True
kwargs Any

Any other parameters to pass to AudioTrack. These override inherited metadata.

delay replaces the preserved source offset in ms.

{}

Returns:

Type Description
AudioTrack

The extracted audio as an AudioTrack.

Source code in muxtools/helpers/extract.py
def audio_track(self, track: int = 0, output: PathLike = None, quiet: bool = True, **kwargs: Any) -> AudioTrack:
    """
    Extract an audio track from the file without conversion.

    The track name, language, default/forced flags and custom tags are inherited unless overridden.\n
    The format has to be supported by `AudioFormat`. Existing container timing is preserved.

    :param track:               Relative audio track number, starting at 0.
    :param output:              Custom output. Can be an existing directory or a file.\n
                                `None` uses the default output directory of the helper.\n
                                The file extension will be set automatically.

    :param quiet:               Suppresses the output.\n
                                The stdout will still be printed on failure regardless of this setting.

    :param kwargs:              Any other parameters to pass to `AudioTrack`. These override inherited metadata.\n
                                `delay` replaces the preserved source offset in ms.

    :return:                    The extracted audio as an `AudioTrack`.
    """
    return self._extract_track(AudioTrack, TrackType.AUDIO, track, output, quiet, **kwargs)

sub_track

sub_track(track: int = 0, output: PathLike = None, quiet: bool = True, **kwargs: Any) -> SubTrack

Extract a subtitle track from the file without conversion. SRT will stay SRT.

The track name, language, default/forced flags and custom tags are inherited unless overridden.

Existing subtitle timing is preserved. VobSub returns an .idx file with its .sub companion.

Parameters:

Name Type Description Default
track int

Relative subtitle track number, starting at 0.

0
output PathLike

Custom output. Can be an existing directory or a file.

None uses the default output directory of the helper.

The file extension will be set automatically.

None
quiet bool

Suppresses the output.

The stdout will still be printed on failure regardless of this setting.

True
kwargs Any

Any other parameters to pass to SubTrack. These override inherited metadata.

delay adds a shift in ms to the extracted subtitles.

{}

Returns:

Type Description
SubTrack

The extracted subtitle as a SubTrack.

Source code in muxtools/helpers/extract.py
def sub_track(self, track: int = 0, output: PathLike = None, quiet: bool = True, **kwargs: Any) -> SubTrack:
    """
    Extract a subtitle track from the file without conversion. SRT will stay SRT.

    The track name, language, default/forced flags and custom tags are inherited unless overridden.\n
    Existing subtitle timing is preserved. VobSub returns an `.idx` file with its `.sub` companion.

    :param track:               Relative subtitle track number, starting at 0.
    :param output:              Custom output. Can be an existing directory or a file.\n
                                `None` uses the default output directory of the helper.\n
                                The file extension will be set automatically.

    :param quiet:               Suppresses the output.\n
                                The stdout will still be printed on failure regardless of this setting.

    :param kwargs:              Any other parameters to pass to `SubTrack`. These override inherited metadata.\n
                                `delay` adds a shift in ms to the extracted subtitles.

    :return:                    The extracted subtitle as a `SubTrack`.
    """
    return self._extract_track(SubTrack, TrackType.SUB, track, output, quiet, **kwargs)

attachment

attachment(track: int = 0, output: PathLike = None, quiet: bool = True, *, name: str | None = None, mimetype: str | None = None) -> Attachment

Extract an attachment from the file.

The original attachment name and MIME type are inherited unless overridden.

Parameters:

Name Type Description Default
track int

Relative attachment number, starting at 0.

0
output PathLike

Custom output. Can be an existing directory or a file.

None uses the default output directory of the helper.

Generated filenames are based on the original attachment name.

None
quiet bool

Suppresses the output.

The stdout will still be printed on failure regardless of this setting.

True
name str | None

Name of the attachment when muxing. None keeps the original name.

None
mimetype str | None

MIME type of the returned attachment. None keeps the original MIME type.

None

Returns:

Type Description
Attachment

The extracted attachment as an Attachment.

Source code in muxtools/helpers/extract.py
def attachment(
    self, track: int = 0, output: PathLike = None, quiet: bool = True, *, name: str | None = None, mimetype: str | None = None
) -> Attachment:
    """
    Extract an attachment from the file.

    The original attachment name and MIME type are inherited unless overridden.

    :param track:               Relative attachment number, starting at 0.
    :param output:              Custom output. Can be an existing directory or a file.\n
                                `None` uses the default output directory of the helper.\n
                                Generated filenames are based on the original attachment name.

    :param quiet:               Suppresses the output.\n
                                The stdout will still be printed on failure regardless of this setting.

    :param name:                Name of the attachment when muxing. `None` keeps the original name.
    :param mimetype:            MIME type of the returned attachment. `None` keeps the original MIME type.
    :return:                    The extracted attachment as an `Attachment`.
    """
    if track < 0 or track >= len(self._info.attachments):
        raise ValueError(f"Could not find attachment {track} in '{self._fileIn.name}'.")
    item = self._info.attachments[track]
    path = self._attachment_output(item, output)
    with self._extract(["attachments", f"{item.id}:{path}"], [path], quiet):
        return Attachment(
            path, mimetype=(item.content_type or "") if mimetype is None else mimetype, name=item.file_name if name is None else name
        )

attachments

attachments(output: PathLike = None, quiet: bool = True) -> list[Attachment]

Extract all attachments from the file in one pass.

Original attachment names and MIME types are preserved.

Parameters:

Name Type Description Default
output PathLike

Output directory. None uses the default output directory of the helper.

The directory will be created if it does not exist.

None
quiet bool

Suppresses the output.

The stdout will still be printed on failure regardless of this setting.

True

Returns:

Type Description
list[Attachment]

A list of Attachment objects in source order.

An empty list is returned if the file has no attachments.

Source code in muxtools/helpers/extract.py
def attachments(self, output: PathLike = None, quiet: bool = True) -> list[Attachment]:
    """
    Extract all attachments from the file in one pass.

    Original attachment names and MIME types are preserved.

    :param output:              Output directory. `None` uses the default output directory of the helper.\n
                                The directory will be created if it does not exist.

    :param quiet:               Suppresses the output.\n
                                The stdout will still be printed on failure regardless of this setting.

    :return:                    A list of `Attachment` objects in source order.\n
                                An empty list is returned if the file has no attachments.
    """
    target = ensure_path(self.output if output is None else output, self)
    if target.exists() and not target.is_dir():
        raise ValueError("The output for attachments must be a directory.")
    target.mkdir(parents=True, exist_ok=True)
    paths: list[Path] = []
    for item in self._info.attachments:
        paths.append(self._attachment_output(item, target, reserved=paths))
    if not paths:
        return []
    args = ["attachments", *[f"{item.id}:{path}" for item, path in zip(self._info.attachments, paths)]]
    with self._extract(args, paths, quiet):
        return [Attachment(path, mimetype=item.content_type or "", name=item.file_name) for item, path in zip(self._info.attachments, paths)]