Skip to content

vsmuxtools.video.settings

__all__ module-attribute

__all__ = ['settings_builder_x265', 'settings_builder_x264', 'sb', 'sb265', 'sb264', 'settings_builder_5fish_svt_av1_high_quality', 'settings_builder_5fish_svt_av1_mini', 'settings_builder_5fish_svt_av1_mini_high_dlf', 'settings_builder_svt_av1_essential']

sb module-attribute

sb = settings_builder_x265

sb265 module-attribute

sb265 = sb

sb264 module-attribute

sb264 = settings_builder_x264

is_full_zone

is_full_zone
Source code in vsmuxtools/video/settings.py
def is_full_zone(zone: Zone) -> bool:
    if isinstance(zone[2], str):
        if len(zone) < 4:
            raise error(f"Zone '{zone}' is invalid.")
        return True
    else:
        return False

norm_zones

norm_zones

Normalize zones to be within the clip's range.

Parameters:

Name Type Description Default
clip_or_max_frames VideoNode | int

The clip or a max frame count to normalize to.

required
zones Zone | list[Zone] | None

The zones to normalize.

required

Returns:

Type Description
list[Zone]

The normalized zones.

Source code in vsmuxtools/video/settings.py
def norm_zones(clip_or_max_frames: vs.VideoNode | int, zones: Zone | list[Zone] | None) -> list[Zone]:
    """
    Normalize zones to be within the clip's range.

    :param clip_or_max_frames:      The clip or a max frame count to normalize to.
    :param zones:                   The zones to normalize.

    :return:                        The normalized zones.
    """

    if not zones:
        return []

    max_frames = clip_or_max_frames if isinstance(clip_or_max_frames, int) else clip_or_max_frames.num_frames

    if not isinstance(zones, list):
        zones = [zones]

    newzones = list[Zone]()

    for zone in zones:
        start, end, *params = zone

        if start is None:
            start = 0
        elif isinstance(start, int) and start < 0:
            start = max_frames - abs(start)

        if end is None:
            end = max_frames - 1
        elif isinstance(end, int) and end < 0:
            end = max_frames - abs(end)

        if start > end:
            raise CustomValueError(f"Zone '{zone}' start frame is after end frame!", norm_zones, f"{start} > {end}")

        newzones.append(cast(Zone, (start, min(end, max_frames - 1), *params)))  # type:ignore[type-var]

    return newzones

shift_zones

shift_zones
Source code in vsmuxtools/video/settings.py
def shift_zones(zones: Zone | list[Zone] | None, start_frame: int = 0) -> list[Zone] | None:
    if not zones:
        return None
    if not isinstance(zones, list):
        zones = [zones]

    newzones = list[Zone]()

    for zone in zones:
        assert zone[0] is not None and zone[1] is not None
        start = zone[0] - start_frame
        end = zone[1] - start_frame
        if end < 0:
            continue
        if start < 0:
            start = 0

        new_zone = list(zone)
        new_zone[0] = start
        new_zone[1] = end
        newzones.append(tuple(new_zone))  # type: ignore

    return newzones

zones_to_args

zones_to_args
Source code in vsmuxtools/video/settings.py
def zones_to_args(zones: Zone | list[Zone] | None, x265: bool) -> list[str]:
    args: list[str] = []
    if not zones:
        return args
    if not isinstance(zones, list):
        zones = [zones]
    zones_settings: str = ""
    for i, zone in enumerate(zones):
        if is_full_zone(zone):
            if x265 and str(zone[2]).lower() not in ["q", "b"]:
                raise error(f"Zone '{zone}' is invalid for x265. Please only use b or q.")
            zones_settings += f"{zone[0]},{zone[1]},{zone[2]}={zone[3]}"  # type: ignore
        else:
            zones_settings += f"{zone[0]},{zone[1]},b={zone[2]}"
        if i != len(zones) - 1:
            zones_settings += "/"
    args.extend(["--zones", zones_settings])
    return args

settings_builder_x265

settings_builder_x265

Simple settings builder for x265 encoding.
Defaults are a decently high quality settings for 1080p content.

For explanations on each parameter, check your x265's --fullhelp output or its documentation.

Unlike the builders for SVTAV1, this builder returns a String that is supposed to be passed to the encoders settings parameter.
However, every encoder class can still take arbitrary kwargs for custom args. See Dynamic Dataclasses.

Source code in vsmuxtools/video/settings.py
def settings_builder_x265(
    preset: str | int = "slower",
    crf: float = 14.0,
    qcomp: float = 0.75,
    psy_rd: float = 2.0,
    psy_rdoq: float = 2.0,
    aq_strength: float = 0.75,
    aq_mode: int = 3,
    rd: int = 4,
    rect: bool = True,
    amp: bool = False,
    chroma_qpoffsets: int = -2,
    tu_intra_depth: int = 2,
    tu_inter_depth: int = 2,
    rskip: bool | int = 0,
    tskip: bool = False,
    ref: int = 4,
    bframes: int = 16,
    cutree: bool = False,
    rc_lookahead: int = 60,
    subme: int = 5,
    me: int = 3,
    b_intra: bool = True,
    weightb: bool = True,
    deblock: list[int] | str = [-2, -2],
    open_gop: bool = False,
    append: str = "",
    **kwargs,
) -> str:
    """
    Simple settings builder for x265 encoding.<br>
    Defaults are a decently high quality settings for 1080p content.

    For explanations on each parameter, check your x265's `--fullhelp` output or its [documentation](https://x265.readthedocs.io/en/master/cli.html).


    Unlike the builders for SVTAV1, this builder returns a String that is supposed to be passed to the encoders `settings` parameter.<br>
    However, every encoder class can still take arbitrary kwargs for custom args. See [Dynamic Dataclasses](https://muxtools.vodes.pw/guide/dynamic-dataclasses/).
    """
    # Simple insert values
    settings = f" --preset {preset} --crf {crf} --bframes {bframes} --ref {ref} --rc-lookahead {rc_lookahead} --subme {subme} --me {me}"
    settings += f" --aq-mode {aq_mode} --aq-strength {aq_strength} --qcomp {qcomp} --cbqpoffs {chroma_qpoffsets} --crqpoffs {chroma_qpoffsets}"
    settings += f" --rd {rd} --psy-rd {psy_rd} --psy-rdoq {psy_rdoq} --tu-intra-depth {tu_intra_depth} --tu-inter-depth {tu_inter_depth}"

    # Less simple
    settings += f" --{'rect' if rect else 'no-rect'} --{'amp' if amp else 'no-amp'} --{'tskip' if tskip else 'no-tskip'}"
    settings += f" --{'b-intra' if b_intra else 'no-b-intra'} --{'weightb' if weightb else 'no-weightb'} --{'cutree' if cutree else 'no-cutree'}"
    settings += f" --{'open-gop' if open_gop else 'no-open-gop'}"
    settings += f" --rskip {int(rskip) if isinstance(rskip, bool) else rskip}"

    if isinstance(deblock, list):
        deblock = f"{str(deblock[0])}:{str(deblock[1])}"
    settings += f" --deblock={deblock}"

    # Don't need to change these lol
    settings += " --no-sao --no-sao-non-deblock --no-strong-intra-smoothing"

    for k, v in kwargs.items():
        prefix = "--"
        if k.startswith("_"):
            prefix = "-"
            k = k[1:]
        settings += f" {prefix}{k.replace('_', '-')} {v}"

    settings += (" " + append.strip()) if append.strip() else ""
    return settings

settings_builder_x264

settings_builder_x264

Simple settings builder for x264 encoding.
Defaults are a decently high quality settings for 1080p content.

For explanations on each parameter, check your x264's --fullhelp output.

Unlike the builders for SVTAV1, this builder returns a String that is supposed to be passed to the encoders settings parameter.
However, every encoder class can still take arbitrary kwargs for custom args. See Dynamic Dataclasses.

Source code in vsmuxtools/video/settings.py
def settings_builder_x264(
    preset: str = "placebo",
    crf: float = 13,
    qcomp: float = 0.7,
    psy_rd: float = 1.0,
    psy_trellis: float = 0.0,
    trellis: int | None = None,
    aq_strength: float = 0.8,
    aq_mode: int = 3,
    ref: int = 16,
    bframes: int = 16,
    mbtree: bool = False,
    rc_lookahead: int = 250,
    me: str = "umh",
    subme: int = 11,
    threads: int = 6,
    merange: int = 32,
    deblock: list[int] | str = [-1, -1],
    dct_decimate: bool = False,
    open_gop: bool = False,
    append: str = "",
    **kwargs,
) -> str:
    """
    Simple settings builder for x264 encoding.<br>
    Defaults are a decently high quality settings for 1080p content.

    For explanations on each parameter, check your x264's `--fullhelp` output.


    Unlike the builders for SVTAV1, this builder returns a String that is supposed to be passed to the encoders `settings` parameter.<br>
    However, every encoder class can still take arbitrary kwargs for custom args. See [Dynamic Dataclasses](https://muxtools.vodes.pw/guide/dynamic-dataclasses/).
    """
    # Simple insert values
    settings = f" --preset {preset} --crf {crf} --bframes {bframes} --ref {ref} --rc-lookahead {rc_lookahead} --me {me} --merange {merange}"
    settings += f" --aq-mode {aq_mode} --aq-strength {aq_strength} --qcomp {qcomp}"
    settings += f" --psy-rd {psy_rd}:{psy_trellis} --subme {subme} --threads {threads}"
    if trellis is not None:
        settings += f" --trellis {trellis}"
    if open_gop:
        settings += " --open-gop"

    # Less simple
    settings += f" {'--no-mbtree' if not mbtree else ''} {'--no-dct-decimate' if not dct_decimate else ''}"

    if isinstance(deblock, list):
        deblock = f"{str(deblock[0])}:{str(deblock[1])}"
    settings += f" --deblock {deblock}"

    for k, v in kwargs.items():
        prefix = "--"
        if k.startswith("_"):
            prefix = "-"
            k = k[1:]
        settings += f" {prefix}{k.replace('_', '-')} {v}"

    settings += (" " + append.strip()) if append.strip() else ""
    return settings

settings_builder_5fish_svt_av1_high_quality

settings_builder_5fish_svt_av1_high_quality

This is a settings_builder for 5fish/SVT-AV1 v2.3.261005 or later v2.3 versions.

Source Repository & Builds: https://github.com/5fish/svt-av1.

You can denoise or regrain as normal before sending to the encoder.
However, utilizing the film grain layer and, particularly on a clean source, stabilizing the video would be much more efficient.

If you want to adjust the parameters for your source, check the Usage section in README.md in encoder's GitHub repository.

To use this settings_builder,

settings = settings_builder_5fish_svt_av1_high_quality()
mini = SVTAV1(**settings, sd_clip=src).encode(final)

Source code in vsmuxtools/video/settings.py
def settings_builder_5fish_svt_av1_high_quality(
    preset: int = 2,
    crf: float = 11.00,
    lineart_psy_bias: int = 6,
    texture_psy_bias: int = 4,
    progress: int | None = 2,
    **kwargs,
) -> dict[str, Any]:
    """
    This is a settings_builder for 5fish/SVT-AV1 v2.3.261005 or later v2.3 versions.

    Source Repository & Builds: <https://github.com/5fish/svt-av1>.

    You can denoise or regrain as normal before sending to the encoder.<br>
    However, utilizing the film grain layer and, particularly on a clean source, stabilizing the video would be much more efficient.

    If you want to adjust the parameters for your source, check the Usage section in `README.md` in encoder's GitHub repository.

    To use this settings_builder,
    ```py
    settings = settings_builder_5fish_svt_av1_high_quality()
    mini = SVTAV1(**settings, sd_clip=src).encode(final)
    ```
    """
    args = dict[str, Any]()
    args["_settings_builder_id"] = r"SVT-AV1 \[5fish"

    for k in inspect.getfullargspec(settings_builder_5fish_svt_av1_high_quality).args:
        if locals()[k] is not None:
            args[k] = locals()[k]

    return args | kwargs

settings_builder_5fish_svt_av1_mini

settings_builder_5fish_svt_av1_mini

This is a settings_builder for 5fish/SVT-AV1 v2.3.261005 or later v2.3 versions.

Source Repository & Builds: https://github.com/5fish/svt-av1.

This method is best suited for clean sources. For sources with noise or with regrain, use settings_builder_5fish_svt_av1_mini_high_dlf.

On a clean source, the recommended method is to completely stabilize the video so that it doesn't have any noise, including debanding and dithering noise.
When completely stabilized, on a typical clean source, you should be able to hit 2 Mbps or less over the whole source at --crf 21.00.
Example filtering:

from vsdeband import pfdeband, placebo_deband
from vsdenoise import Prefilter, mc_degrain, MVToolsPreset
from vstools import DitherType, finalize_clip
debanded = pfdeband(source, debander=placebo_deband, thr=2.0)
stabilized = mc_degrain(debanded, mfilter=source, prefilter=Prefilter.DFTTEST(source), preset=MVToolsPreset.HQ_COHERENCE, thsad=40, tr=4)
final = finalize_clip(stabilized, dither_type=DitherType.NONE)

If you want to adjust the parameters for your source, check the Usage section in README.md in encoder's GitHub repository.

To use this settings_builder,

settings = settings_builder_5fish_svt_av1_mini()
mini = SVTAV1(**settings, sd_clip=src).encode(final)

Source code in vsmuxtools/video/settings.py
def settings_builder_5fish_svt_av1_mini(
    preset: int = 2,
    crf: float = 21.00,
    lineart_psy_bias: int = 3,
    texture_psy_bias: int = 3,
    progress: int | None = 2,
    **kwargs,
) -> dict[str, Any]:
    """
    This is a settings_builder for 5fish/SVT-AV1 v2.3.261005 or later v2.3 versions.

    Source Repository & Builds: <https://github.com/5fish/svt-av1>.

    This method is best suited for clean sources. For sources with noise or with regrain, use `settings_builder_5fish_svt_av1_mini_high_dlf`.

    On a clean source, the recommended method is to completely stabilize the video so that it doesn't have any noise, including debanding and dithering noise.<br>
    When completely stabilized, on a typical clean source, you should be able to hit 2 Mbps or less over the whole source at `--crf 21.00`.<br>
    Example filtering:
    ```py
    from vsdeband import pfdeband, placebo_deband
    from vsdenoise import Prefilter, mc_degrain, MVToolsPreset
    from vstools import DitherType, finalize_clip
    debanded = pfdeband(source, debander=placebo_deband, thr=2.0)
    stabilized = mc_degrain(debanded, mfilter=source, prefilter=Prefilter.DFTTEST(source), preset=MVToolsPreset.HQ_COHERENCE, thsad=40, tr=4)
    final = finalize_clip(stabilized, dither_type=DitherType.NONE)
    ```

    If you want to adjust the parameters for your source, check the Usage section in `README.md` in encoder's GitHub repository.

    To use this settings_builder,
    ```py
    settings = settings_builder_5fish_svt_av1_mini()
    mini = SVTAV1(**settings, sd_clip=src).encode(final)
    ```
    """
    args = dict[str, Any]()
    args["_settings_builder_id"] = r"SVT-AV1 \[5fish"

    for k in inspect.getfullargspec(settings_builder_5fish_svt_av1_mini).args:
        if locals()[k] is not None:
            args[k] = locals()[k]

    return args | kwargs

settings_builder_5fish_svt_av1_mini_high_dlf

settings_builder_5fish_svt_av1_mini_high_dlf

This is a settings_builder for 5fish/SVT-AV1 v2.3.261005 or later v2.3 versions.

Source Repository & Builds: https://github.com/5fish/svt-av1.

Compared to the settings_builder_5fish_svt_av1_mini, this high DLF version is suitable for very noisy or regrained sources.
Denoise is not preferred even for very noisy sources as denoise seems to commonly result in very bad detail retention.

If you want to adjust the parameters for your source, check the Usage section in README.md in the encoder's GitHub repository.

To use this settings_builder,

settings = settings_builder_5fish_svt_av1_mini_high_dlf()
mini = SVTAV1(**settings, sd_clip=src).encode(final)

Source code in vsmuxtools/video/settings.py
def settings_builder_5fish_svt_av1_mini_high_dlf(
    preset: int = 2,
    crf: float = 26.00,
    lineart_psy_bias: int = 3,
    texture_psy_bias: int = 5,
    dlf_bias_max_dlf: str | None = "24,4",
    dlf_bias_min_dlf: str | None = "16,0",
    texture_cdef_bias_max_cdef: str | None = "0,0,0,0",
    progress: int | None = 2,
    **kwargs,
) -> dict[str, Any]:
    """
    This is a settings_builder for 5fish/SVT-AV1 v2.3.261005 or later v2.3 versions.

    Source Repository & Builds: <https://github.com/5fish/svt-av1>.

    Compared to the `settings_builder_5fish_svt_av1_mini`, this high DLF version is suitable for very noisy or regrained sources.<br>
    Denoise is not preferred even for very noisy sources as denoise seems to commonly result in very bad detail retention.

    If you want to adjust the parameters for your source, check the Usage section in `README.md` in the encoder's GitHub repository.

    To use this settings_builder,
    ```py
    settings = settings_builder_5fish_svt_av1_mini_high_dlf()
    mini = SVTAV1(**settings, sd_clip=src).encode(final)
    ```
    """
    args = dict[str, Any]()
    args["_settings_builder_id"] = r"SVT-AV1 \[5fish"

    for k in inspect.getfullargspec(settings_builder_5fish_svt_av1_mini_high_dlf).args:
        if locals()[k] is not None:
            args[k] = locals()[k]

    return args | kwargs

settings_builder_svt_av1_essential

settings_builder_svt_av1_essential

This is a settings_builder for SVT-AV1-Essential v4.0.1-Essential or later versions.

Repository: https://github.com/nekotrix/SVT-AV1-Essential.
Builds: https://github.com/Akatmks/SVT-AV1-Builds/releases?q=SVT-AV1-Essential.

For higher quality mini and non mini encodes, check out settings_builder_5fish_svt_av1_psy.

For better explanations of parameters, check the Docs/Parameters.md file in the encoder's GitHub repository.

To use this settings_builder,

settings = settings_builder_svt_av1_essential(...)
mini = SVTAV1(**settings).encode(final)

Parameters:

Name Type Description Default
speed str | None

Adjust the speed.

slower (--preset 2) is the recommended starting point. slow (--preset 4) is faster.

'slower'
quality str | None

Adjust the quality.

medium (--crf 30) is the recommended starting point. high (--crf 25) is higher, and low (--crf 35), or lower (--crf 40) is lower.

'medium'
Source code in vsmuxtools/video/settings.py
def settings_builder_svt_av1_essential(
    speed: str | None = "slower",
    quality: str | None = "medium",
    preset: int | None = None,
    crf: int | None = None,
    scm: int | None = 0,
    progress: int | None = 3,
    **kwargs,
) -> dict[str, Any]:
    """
    This is a settings_builder for SVT-AV1-Essential v4.0.1-Essential or later versions.

    Repository: <https://github.com/nekotrix/SVT-AV1-Essential>.<br>
    Builds: <https://github.com/Akatmks/SVT-AV1-Builds/releases?q=SVT-AV1-Essential>.

    For higher quality mini and non mini encodes, check out `settings_builder_5fish_svt_av1_psy`.

    For better explanations of parameters, check the `Docs/Parameters.md` file in the encoder's GitHub repository.

    To use this settings_builder,
    ```py
    settings = settings_builder_svt_av1_essential(...)
    mini = SVTAV1(**settings).encode(final)
    ```

    :param speed:           Adjust the speed.\n
                            `slower` (`--preset 2`) is the recommended starting point. `slow` (`--preset 4`) is faster.
    :param quality:         Adjust the quality.\n
                            `medium` (`--crf 30`) is the recommended starting point. `high` (`--crf 25`) is higher, and `low` (`--crf 35`), or `lower` (`--crf 40`) is lower.
    """
    args = dict[str, Any]()
    args["_settings_builder_id"] = "SVT-AV1-Essential"

    for k in inspect.getfullargspec(settings_builder_svt_av1_essential).args:
        if locals()[k] is not None:
            args[k] = locals()[k]

    args = args | kwargs

    if "speed" in args and "preset" in args:
        del args["speed"]
    if "quality" in args and "crf" in args:
        del args["quality"]

    if "speed" not in args and "preset" not in args:
        raise error("You must specify either speed or preset", settings_builder_svt_av1_essential)
    if "quality" not in args and "crf" not in args:
        raise error("You must specify either quality or crf", settings_builder_svt_av1_essential)

    return args

file_or_default

file_or_default
Source code in vsmuxtools/video/settings.py
def file_or_default(file: PathLike | list[str], default: str, no_warn: bool = False) -> tuple[str | list[str], bool]:
    if isinstance(file, list):
        return file, False
    if file is not None and os.path.isfile(file):
        file = ensure_path(file, None)
        if file.exists():
            with open(file, "r") as r:
                settings = str(r.read())
                settings = settings.replace("\n", " ")
                settings = re.sub(r"(?:-o|--output) {clip.+?}", "", settings, flags=re.I).strip()
                return settings, True

    if not no_warn:
        warn("Settings file wasn't found. Using default.", None, 3)
    return default, False