Skip to content

transcoding

RationalToInt

Rational value stored as division of 2 integers using string.

Source code in client/ayon_core/lib/transcoding.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
class RationalToInt:
    """Rational value stored as division of 2 integers using string."""

    def __init__(self, string_value):
        parts = string_value.split("/")
        top = float(parts[0])
        bottom = 1.0
        if len(parts) != 1:
            bottom = float(parts[1])

        self._value = float(top) / float(bottom)
        self._string_value = string_value

    @property
    def value(self):
        return self._value

    @property
    def string_value(self):
        return self._string_value

    def __format__(self, *args, **kwargs):
        return self._string_value.__format__(*args, **kwargs)

    def __float__(self):
        return self._value

    def __str__(self):
        return self._string_value

    def __repr__(self):
        return "<{}> {}".format(self.__class__.__name__, self._string_value)

convert_color_values(application, color_value)

Get color mapping for ffmpeg and oiiotool.

Parameters:

Name Type Description Default
application str

Application for which command should be created.

required
color_value tuple[int, int, int, float]

List of 8bit int values for RGBA.

required

Returns:

Name Type Description
str

ffmpeg returns hex string, oiiotool is string with floats.

Source code in client/ayon_core/lib/transcoding.py
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
def convert_color_values(application, color_value):
    """Get color mapping for ffmpeg and oiiotool.

    Args:
        application (str): Application for which command should be created.
        color_value (tuple[int, int, int, float]): List of 8bit int values
            for RGBA.

    Returns:
        str: ffmpeg returns hex string, oiiotool is string with floats.

    """
    red, green, blue, alpha = color_value

    if application == "ffmpeg":
        return "{0:0>2X}{1:0>2X}{2:0>2X}@{3}".format(
            red, green, blue, alpha
        )
    elif application == "oiiotool":
        red = float(red / 255)
        green = float(green / 255)
        blue = float(blue / 255)

        return "{0:.3f},{1:.3f},{2:.3f},{3:.3f}".format(
            red, green, blue, alpha)
    else:
        raise ValueError(
            "\"application\" input argument should "
            "be either \"ffmpeg\" or \"oiiotool\""
        )

convert_colorspace(input_path, output_path, config_path, source_colorspace, target_colorspace=None, view=None, display=None, additional_command_args=None, logger=None)

Convert source file from one color space to another.

Parameters:

Name Type Description Default
input_path str

Path that should be converted. It is expected that contains single file or image sequence of same type (sequence in format 'file.FRAMESTART-FRAMEEND#.ext', see oiio docs, eg big.1-3#.tif)

required
output_path str

Path to output filename. (must follow format of 'input_path', eg. single file or sequence in 'file.FRAMESTART-FRAMEEND#.ext', output.1-3#.tif)

required
config_path str

path to OCIO config file

required
source_colorspace str

ocio valid color space of source files

required
target_colorspace str

ocio valid target color space if filled, 'view' and 'display' must be empty

None
view str

name for viewer space (ocio valid) both 'view' and 'display' must be filled (if 'target_colorspace')

None
display str

name for display-referred reference space (ocio valid) both 'view' and 'display' must be filled (if 'target_colorspace')

None
additional_command_args list

arguments for oiiotool (like binary depth for .dpx)

None
logger Logger

Logger used for logging.

None

Raises: ValueError: if misconfigured

Source code in client/ayon_core/lib/transcoding.py
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def convert_colorspace(
    input_path,
    output_path,
    config_path,
    source_colorspace,
    target_colorspace=None,
    view=None,
    display=None,
    additional_command_args=None,
    logger=None,
):
    """Convert source file from one color space to another.

    Args:
        input_path (str): Path that should be converted. It is expected that
            contains single file or image sequence of same type
            (sequence in format 'file.FRAMESTART-FRAMEEND#.ext', see oiio docs,
            eg `big.1-3#.tif`)
        output_path (str): Path to output filename.
            (must follow format of 'input_path', eg. single file or
             sequence in 'file.FRAMESTART-FRAMEEND#.ext', `output.1-3#.tif`)
        config_path (str): path to OCIO config file
        source_colorspace (str): ocio valid color space of source files
        target_colorspace (str): ocio valid target color space
                    if filled, 'view' and 'display' must be empty
        view (str): name for viewer space (ocio valid)
            both 'view' and 'display' must be filled (if 'target_colorspace')
        display (str): name for display-referred reference space (ocio valid)
            both 'view' and 'display' must be filled (if 'target_colorspace')
        additional_command_args (list): arguments for oiiotool (like binary
            depth for .dpx)
        logger (logging.Logger): Logger used for logging.
    Raises:
        ValueError: if misconfigured
    """
    if logger is None:
        logger = logging.getLogger(__name__)

    input_info = get_oiio_info_for_input(input_path, logger=logger)

    # Collect channels to export
    input_arg, channels_arg = get_oiio_input_and_channel_args(input_info)

    # Prepare subprocess arguments
    oiio_cmd = get_oiio_tool_args(
        "oiiotool",
        # Don't add any additional attributes
        "--nosoftwareattrib",
        "--colorconfig", config_path
    )

    oiio_cmd.extend([
        input_arg, input_path,
        # Tell oiiotool which channels should be put to top stack
        #   (and output)
        "--ch", channels_arg
    ])

    if all([target_colorspace, view, display]):
        raise ValueError("Colorspace and both screen and display"
                         " cannot be set together."
                         "Choose colorspace or screen and display")
    if not target_colorspace and not all([view, display]):
        raise ValueError("Both screen and display must be set.")

    if additional_command_args:
        oiio_cmd.extend(additional_command_args)

    if target_colorspace:
        oiio_cmd.extend(["--colorconvert:subimages=0",
                         source_colorspace,
                         target_colorspace])
    if view and display:
        oiio_cmd.extend(["--iscolorspace", source_colorspace])
        oiio_cmd.extend(["--ociodisplay:subimages=0", display, view])

    oiio_cmd.extend(["-o", output_path])

    logger.debug("Conversion command: {}".format(" ".join(oiio_cmd)))
    run_subprocess(oiio_cmd, logger=logger)

convert_ffprobe_fps_to_float(value)

Convert string value of frame rate to float.

Copy of 'convert_ffprobe_fps_value' which raises exceptions on invalid value, does not convert value to string and does not return "Unknown" string.

Parameters:

Name Type Description Default
value str

Value to be converted.

required

Returns:

Name Type Description
Float

Converted frame rate in float. If divisor in value is '0' then '0.0' is returned.

Raises:

Type Description
ValueError

Passed value is invalid for conversion.

Source code in client/ayon_core/lib/transcoding.py
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
def convert_ffprobe_fps_to_float(value):
    """Convert string value of frame rate to float.

    Copy of 'convert_ffprobe_fps_value' which raises exceptions on invalid
    value, does not convert value to string and does not return "Unknown"
    string.

    Args:
        value (str): Value to be converted.

    Returns:
        Float: Converted frame rate in float. If divisor in value is '0' then
            '0.0' is returned.

    Raises:
        ValueError: Passed value is invalid for conversion.
    """

    if not value:
        raise ValueError("Got empty value.")

    items = value.split("/")
    if len(items) == 1:
        return float(items[0])

    if len(items) > 2:
        raise ValueError((
            "FPS expression contains multiple dividers \"{}\"."
        ).format(value))

    dividend = float(items.pop(0))
    divisor = float(items.pop(0))
    if divisor == 0.0:
        return 0.0
    return dividend / divisor

convert_ffprobe_fps_value(str_value)

Returns (str) value of fps from ffprobe frame format (120/1)

Source code in client/ayon_core/lib/transcoding.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
def convert_ffprobe_fps_value(str_value):
    """Returns (str) value of fps from ffprobe frame format (120/1)"""
    if str_value == "0/0":
        print("WARNING: Source has \"r_frame_rate\" value set to \"0/0\".")
        return "Unknown"

    items = str_value.split("/")
    if len(items) == 1:
        fps = float(items[0])

    elif len(items) == 2:
        fps = float(items[0]) / float(items[1])

    # Check if fps is integer or float number
    if int(fps) == fps:
        fps = int(fps)

    return str(fps)

convert_for_ffmpeg(first_input_path, output_dir, input_frame_start=None, input_frame_end=None, logger=None)

Convert source file to format supported in ffmpeg.

Currently can convert only exrs.

Parameters:

Name Type Description Default
first_input_path str

Path to first file of a sequence or a single file path for non-sequential input.

required
output_dir str

Path to directory where output will be rendered. Must not be same as input's directory.

required
input_frame_start int

Frame start of input.

None
input_frame_end int

Frame end of input.

None
logger Logger

Logger used for logging.

None

Raises:

Type Description
ValueError

If input filepath has extension not supported by function. Currently is supported only ".exr" extension.

Source code in client/ayon_core/lib/transcoding.py
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
def convert_for_ffmpeg(
    first_input_path,
    output_dir,
    input_frame_start=None,
    input_frame_end=None,
    logger=None
):
    """Convert source file to format supported in ffmpeg.

    Currently can convert only exrs.

    Args:
        first_input_path (str): Path to first file of a sequence or a single
            file path for non-sequential input.
        output_dir (str): Path to directory where output will be rendered.
            Must not be same as input's directory.
        input_frame_start (int): Frame start of input.
        input_frame_end (int): Frame end of input.
        logger (logging.Logger): Logger used for logging.

    Raises:
        ValueError: If input filepath has extension not supported by function.
            Currently is supported only ".exr" extension.
    """
    if logger is None:
        logger = logging.getLogger(__name__)

    logger.warning((
        "DEPRECATED: 'ayon_core.lib.transcoding.convert_for_ffmpeg' is"
        " deprecated function of conversion for FFMpeg. Please replace usage"
        " with 'ayon_core.lib.transcoding.convert_input_paths_for_ffmpeg'"
    ))

    ext = os.path.splitext(first_input_path)[1].lower()
    if ext != ".exr":
        raise ValueError((
            "Function 'convert_for_ffmpeg' currently support only"
            " \".exr\" extension. Got \"{}\"."
        ).format(ext))

    is_sequence = False
    if input_frame_start is not None and input_frame_end is not None:
        is_sequence = int(input_frame_end) != int(input_frame_start)

    input_info = get_oiio_info_for_input(first_input_path, logger=logger)

    # Change compression only if source compression is "dwaa" or "dwab"
    #   - they're not supported in ffmpeg
    compression = input_info["attribs"].get("compression")
    if compression in ("dwaa", "dwab"):
        compression = "none"

    # Prepare subprocess arguments
    oiio_cmd = get_oiio_tool_args(
        "oiiotool",
        # Don't add any additional attributes
        "--nosoftwareattrib",
    )
    # Add input compression if available
    if compression:
        oiio_cmd.extend(["--compression", compression])

    # Collect channels to export
    input_arg, channels_arg = get_oiio_input_and_channel_args(input_info)

    oiio_cmd.extend([
        input_arg, first_input_path,
        # Tell oiiotool which channels should be put to top stack (and output)
        "--ch", channels_arg,
        # Use first subimage
        "--subimage", "0"
    ])

    # Add frame definitions to arguments
    if is_sequence:
        oiio_cmd.extend([
            "--frames", "{}-{}".format(input_frame_start, input_frame_end)
        ])

    for attr_name, attr_value in input_info["attribs"].items():
        if not isinstance(attr_value, str):
            continue

        # Remove attributes that have string value longer than allowed length
        #   for ffmpeg or when contain prohibited symbols
        erase_reason = "Missing reason"
        erase_attribute = False
        if len(attr_value) > MAX_FFMPEG_STRING_LEN:
            erase_reason = "has too long value ({} chars).".format(
                len(attr_value)
            )
            erase_attribute = True

        if not erase_attribute:
            for char in NOT_ALLOWED_FFMPEG_CHARS:
                if char in attr_value:
                    erase_attribute = True
                    erase_reason = (
                        "contains unsupported character \"{}\"."
                    ).format(char)
                    break

        if erase_attribute:
            # Set attribute to empty string
            logger.info((
                "Removed attribute \"{}\" from metadata because {}."
            ).format(attr_name, erase_reason))
            oiio_cmd.extend(["--eraseattrib", attr_name])

    # Add last argument - path to output
    if is_sequence:
        ext = os.path.splitext(first_input_path)[1]
        base_filename = "tmp.%{:0>2}d{}".format(
            len(str(input_frame_end)), ext
        )
    else:
        base_filename = os.path.basename(first_input_path)
    output_path = os.path.join(output_dir, base_filename)
    oiio_cmd.extend([
        "-o", output_path
    ])

    logger.debug("Conversion command: {}".format(" ".join(oiio_cmd)))
    run_subprocess(oiio_cmd, logger=logger)

convert_input_paths_for_ffmpeg(input_paths, output_dir, logger=None)

Convert source file to format supported in ffmpeg.

Currently can convert only exrs. The input filepaths should be files with same type. Information about input is loaded only from first found file.

Filenames of input files are kept so make sure that output directory is not the same directory as input files have. - This way it can handle gaps and can keep input filenames without handling frame template

Parameters:

Name Type Description Default
input_paths str

Paths that should be converted. It is expected that contains single file or image sequence of same type.

required
output_dir str

Path to directory where output will be rendered. Must not be same as input's directory.

required
logger Logger

Logger used for logging.

None

Raises:

Type Description
ValueError

If input filepath has extension not supported by function. Currently is supported only ".exr" extension.

Source code in client/ayon_core/lib/transcoding.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def convert_input_paths_for_ffmpeg(
    input_paths,
    output_dir,
    logger=None
):
    """Convert source file to format supported in ffmpeg.

    Currently can convert only exrs. The input filepaths should be files
    with same type. Information about input is loaded only from first found
    file.

    Filenames of input files are kept so make sure that output directory
    is not the same directory as input files have.
    - This way it can handle gaps and can keep input filenames without handling
        frame template

    Args:
        input_paths (str): Paths that should be converted. It is expected that
            contains single file or image sequence of same type.
        output_dir (str): Path to directory where output will be rendered.
            Must not be same as input's directory.
        logger (logging.Logger): Logger used for logging.

    Raises:
        ValueError: If input filepath has extension not supported by function.
            Currently is supported only ".exr" extension.
    """
    if logger is None:
        logger = logging.getLogger(__name__)

    first_input_path = input_paths[0]
    ext = os.path.splitext(first_input_path)[1].lower()

    if ext != ".exr":
        raise ValueError((
            "Function 'convert_for_ffmpeg' currently support only"
            " \".exr\" extension. Got \"{}\"."
        ).format(ext))

    input_info = get_oiio_info_for_input(first_input_path, logger=logger)

    # Change compression only if source compression is "dwaa" or "dwab"
    #   - they're not supported in ffmpeg
    compression = input_info["attribs"].get("compression")
    if compression in ("dwaa", "dwab"):
        compression = "none"

    # Collect channels to export
    input_arg, channels_arg = get_oiio_input_and_channel_args(input_info)

    for input_path in input_paths:
        # Prepare subprocess arguments
        oiio_cmd = get_oiio_tool_args(
            "oiiotool",
            # Don't add any additional attributes
            "--nosoftwareattrib",
        )
        # Add input compression if available
        if compression:
            oiio_cmd.extend(["--compression", compression])

        oiio_cmd.extend([
            input_arg, input_path,
            # Tell oiiotool which channels should be put to top stack
            #   (and output)
            "--ch", channels_arg,
            # Use first subimage
            "--subimage", "0"
        ])

        for attr_name, attr_value in input_info["attribs"].items():
            if not isinstance(attr_value, str):
                continue

            # Remove attributes that have string value longer than allowed
            #   length for ffmpeg or when containing prohibited symbols
            erase_reason = "Missing reason"
            erase_attribute = False
            if len(attr_value) > MAX_FFMPEG_STRING_LEN:
                erase_reason = "has too long value ({} chars).".format(
                    len(attr_value)
                )
                erase_attribute = True

            if not erase_attribute:
                for char in NOT_ALLOWED_FFMPEG_CHARS:
                    if char in attr_value:
                        erase_attribute = True
                        erase_reason = (
                            "contains unsupported character \"{}\"."
                        ).format(char)
                        break

            if erase_attribute:
                # Set attribute to empty string
                logger.info((
                    "Removed attribute \"{}\" from metadata because {}."
                ).format(attr_name, erase_reason))
                oiio_cmd.extend(["--eraseattrib", attr_name])

        # Add last argument - path to output
        base_filename = os.path.basename(input_path)
        output_path = os.path.join(output_dir, base_filename)
        oiio_cmd.extend([
            "-o", output_path
        ])

        logger.debug("Conversion command: {}".format(" ".join(oiio_cmd)))
        run_subprocess(oiio_cmd, logger=logger)

convert_value_by_type_name(value_type, value, logger=None)

Convert value to proper type based on type name.

In some cases value types have custom python class.

Source code in client/ayon_core/lib/transcoding.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def convert_value_by_type_name(value_type, value, logger=None):
    """Convert value to proper type based on type name.

    In some cases value types have custom python class.
    """
    if logger is None:
        logger = logging.getLogger(__name__)

    # Simple types
    if value_type == "string":
        return value

    if value_type == "int":
        return int(value)

    if value_type in ("float", "double"):
        return float(value)

    # Vectors will probably have more types
    if value_type in ("vec2f", "float2", "float2d"):
        return [float(item) for item in value.split(",")]

    # Matrix should be always have square size of element 3x3, 4x4
    # - are returned as list of lists
    if value_type in ("matrix", "matrixd"):
        output = []
        current_index = -1
        parts = value.split(",")
        parts_len = len(parts)
        if parts_len == 1:
            divisor = 1
        elif parts_len == 4:
            divisor = 2
        elif parts_len == 9:
            divisor = 3
        elif parts_len == 16:
            divisor = 4
        else:
            logger.info("Unknown matrix resolution {}. Value: \"{}\"".format(
                parts_len, value
            ))
            for part in parts:
                output.append(float(part))
            return output

        for idx, item in enumerate(parts):
            list_index = idx % divisor
            if list_index > current_index:
                current_index = list_index
                output.append([])
            output[list_index].append(float(item))
        return output

    if value_type == "rational2i":
        return RationalToInt(value)

    if value_type in ("vector", "vectord"):
        parts = [part.strip() for part in value.split(",")]
        output = []
        for part in parts:
            if part == "-nan":
                output.append(None)
                continue
            try:
                part = float(part)
            except ValueError:
                pass
            output.append(part)
        return output

    if value_type == "timecode":
        return value

    # Array of other types is converted to list
    re_result = ARRAY_TYPE_REGEX.findall(value_type)
    if re_result:
        array_type = re_result[0]
        output = []
        for item in value.split(","):
            output.append(
                convert_value_by_type_name(array_type, item, logger=logger)
            )
        return output

    logger.debug((
        "Dev note (missing implementation):"
        " Unknown attrib type \"{}\". Value: {}"
    ).format(value_type, value))
    return value

get_convert_rgb_channels(channel_names)

Get first available RGB(A) group from channels info.

Examples

# Ideal situation
channels_info: [
    "R", "G", "B", "A"
]

Result will be ("R", "G", "B", "A")

# Not ideal situation
channels_info: [
    "beauty.red",
    "beauty.green",
    "beauty.blue",
    "depth.Z"
]

Result will be ("beauty.red", "beauty.green", "beauty.blue", None)

Parameters:

Name Type Description Default
channel_names list[str]

List of channel names.

required

Returns:

Type Description

Union[NoneType, tuple[str, str, str, Union[str, None]]]: Tuple of 4 channel names defying channel names for R, G, B, A or None if there is not any layer with RGB combination.

Source code in client/ayon_core/lib/transcoding.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def get_convert_rgb_channels(channel_names):
    """Get first available RGB(A) group from channels info.

    ## Examples
    ```
    # Ideal situation
    channels_info: [
        "R", "G", "B", "A"
    ]
    ```
    Result will be `("R", "G", "B", "A")`

    ```
    # Not ideal situation
    channels_info: [
        "beauty.red",
        "beauty.green",
        "beauty.blue",
        "depth.Z"
    ]
    ```
    Result will be `("beauty.red", "beauty.green", "beauty.blue", None)`

    Args:
        channel_names (list[str]): List of channel names.

    Returns:
        Union[NoneType, tuple[str, str, str, Union[str, None]]]: Tuple of
            4 channel names defying channel names for R, G, B, A or None
            if there is not any layer with RGB combination.
    """

    channels_info = get_review_info_by_layer_name(channel_names)
    for item in channels_info:
        review_channels = item["review_channels"]
        return (
            review_channels["R"],
            review_channels["G"],
            review_channels["B"],
            review_channels["A"]
        )
    return None

get_ffmpeg_codec_args(ffprobe_data, source_ffmpeg_cmd=None, logger=None)

Copy codec from input metadata for output.

Parameters:

Name Type Description Default
ffprobe_data(dict)

Data received from ffprobe.

required
source_ffmpeg_cmd(str)

Command that created input if available.

required
Source code in client/ayon_core/lib/transcoding.py
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
def get_ffmpeg_codec_args(ffprobe_data, source_ffmpeg_cmd=None, logger=None):
    """Copy codec from input metadata for output.

    Args:
        ffprobe_data(dict): Data received from ffprobe.
        source_ffmpeg_cmd(str): Command that created input if available.
    """
    if logger is None:
        logger = logging.getLogger(__name__)

    video_stream = None
    no_audio_stream = None
    for stream in ffprobe_data["streams"]:
        codec_type = stream["codec_type"]
        if codec_type == "video":
            video_stream = stream
            break
        elif no_audio_stream is None and codec_type != "audio":
            no_audio_stream = stream

    if video_stream is None:
        if no_audio_stream is None:
            logger.warning(
                "Couldn't find stream that is not an audio file."
            )
            return []
        logger.info(
            "Didn't find video stream. Using first non audio stream."
        )
        video_stream = no_audio_stream

    codec_name = video_stream.get("codec_name")
    # Codec "prores"
    if codec_name == "prores":
        return _ffmpeg_prores_codec_args(video_stream, source_ffmpeg_cmd)

    # Codec "h264"
    if codec_name == "h264":
        return _ffmpeg_h264_codec_args(video_stream, source_ffmpeg_cmd)

    # Coded DNxHD
    if codec_name == "dnxhd":
        return _ffmpeg_dnxhd_codec_args(video_stream, source_ffmpeg_cmd)

    output = []
    if codec_name:
        output.extend(["-codec:v", codec_name])

    bit_rate = video_stream.get("bit_rate")
    if bit_rate:
        output.extend(["-b:v", bit_rate])

    pix_fmt = video_stream.get("pix_fmt")
    if pix_fmt:
        output.extend(["-pix_fmt", pix_fmt])

    output.extend(["-g", "1"])

    return output

get_ffmpeg_format_args(ffprobe_data, source_ffmpeg_cmd=None)

Copy format from input metadata for output.

Parameters:

Name Type Description Default
ffprobe_data(dict)

Data received from ffprobe.

required
source_ffmpeg_cmd(str)

Command that created input if available.

required
Source code in client/ayon_core/lib/transcoding.py
838
839
840
841
842
843
844
845
846
847
848
def get_ffmpeg_format_args(ffprobe_data, source_ffmpeg_cmd=None):
    """Copy format from input metadata for output.

    Args:
        ffprobe_data(dict): Data received from ffprobe.
        source_ffmpeg_cmd(str): Command that created input if available.
    """
    input_format = ffprobe_data.get("format") or {}
    if input_format.get("format_name") == "mxf":
        return _ffmpeg_mxf_format_args(ffprobe_data, source_ffmpeg_cmd)
    return []

get_ffprobe_data(path_to_file, logger=None)

Load data about entered filepath via ffprobe.

Parameters:

Name Type Description Default
path_to_file str

absolute path

required
logger Logger

injected logger, if empty new is created

None
Source code in client/ayon_core/lib/transcoding.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def get_ffprobe_data(path_to_file, logger=None):
    """Load data about entered filepath via ffprobe.

    Args:
        path_to_file (str): absolute path
        logger (logging.Logger): injected logger, if empty new is created
    """
    if not logger:
        logger = logging.getLogger(__name__)
    logger.debug(
        "Getting information about input \"{}\".".format(path_to_file)
    )
    ffprobe_args = get_ffmpeg_tool_args("ffprobe")
    args = ffprobe_args + [
        "-hide_banner",
        "-loglevel", "fatal",
        "-show_error",
        "-show_format",
        "-show_streams",
        "-show_programs",
        "-show_chapters",
        "-show_private_data",
        "-print_format", "json",
        path_to_file
    ]

    logger.debug("FFprobe command: {}".format(
        subprocess.list2cmdline(args)
    ))
    kwargs = {
        "stdout": subprocess.PIPE,
        "stderr": subprocess.PIPE,
    }
    if platform.system().lower() == "windows":
        kwargs["creationflags"] = (
            subprocess.CREATE_NEW_PROCESS_GROUP
            | getattr(subprocess, "DETACHED_PROCESS", 0)
            | getattr(subprocess, "CREATE_NO_WINDOW", 0)
        )

    popen = subprocess.Popen(args, **kwargs)

    popen_stdout, popen_stderr = popen.communicate()
    if popen_stdout:
        logger.debug("FFprobe stdout:\n{}".format(
            popen_stdout.decode("utf-8")
        ))

    if popen_stderr:
        logger.warning("FFprobe stderr:\n{}".format(
            popen_stderr.decode("utf-8")
        ))

    return json.loads(popen_stdout)

get_ffprobe_streams(path_to_file, logger=None)

Load streams from entered filepath via ffprobe.

Parameters:

Name Type Description Default
path_to_file str

absolute path

required
logger Logger

injected logger, if empty new is created

None
Source code in client/ayon_core/lib/transcoding.py
828
829
830
831
832
833
834
835
def get_ffprobe_streams(path_to_file, logger=None):
    """Load streams from entered filepath via ffprobe.

    Args:
        path_to_file (str): absolute path
        logger (logging.Logger): injected logger, if empty new is created
    """
    return get_ffprobe_data(path_to_file, logger)["streams"]

get_media_mime_type(filepath)

Determine Mime-Type of a file.

Parameters:

Name Type Description Default
filepath str

Path to file.

required

Returns:

Type Description
Optional[str]

Optional[str]: Mime type or None if is unknown mime type.

Source code in client/ayon_core/lib/transcoding.py
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
def get_media_mime_type(filepath: str) -> Optional[str]:
    """Determine Mime-Type of a file.

    Args:
        filepath (str): Path to file.

    Returns:
        Optional[str]: Mime type or None if is unknown mime type.

    """
    if not filepath or not os.path.exists(filepath):
        return None

    with open(filepath, "rb") as stream:
        content = stream.read()

    content_len = len(content)
    # Pre-validation (largest definition check)
    # - hopefully there cannot be media defined in less than 12 bytes
    if content_len < 12:
        return None

    # FTYP
    if content[4:8] == b"ftyp":
        return _get_media_mime_type_from_ftyp(content)

    # BMP
    if content[0:2] == b"BM":
        return "image/bmp"

    # Tiff
    if content[0:2] in (b"MM", b"II"):
        return "tiff"

    # PNG
    if content[0:4] == b"\211PNG":
        return "image/png"

    # SVG
    if b'xmlns="http://www.w3.org/2000/svg"' in content:
        return "image/svg+xml"

    # JPEG, JFIF or Exif
    if (
        content[0:4] == b"\xff\xd8\xff\xdb"
        or content[6:10] in (b"JFIF", b"Exif")
    ):
        return "image/jpeg"

    # Webp
    if content[0:4] == b"RIFF" and content[8:12] == b"WEBP":
        return "image/webp"

    # Gif
    if content[0:6] in (b"GIF87a", b"GIF89a"):
        return "gif"

    # Adobe PhotoShop file (8B > Adobe, PS > PhotoShop)
    if content[0:4] == b"8BPS":
        return "image/vnd.adobe.photoshop"

    # Windows ICO > this might be wild guess as multiple files can start
    #   with this header
    if content[0:4] == b"\x00\x00\x01\x00":
        return "image/x-icon"
    return None

get_oiio_info_for_input(filepath, logger=None, subimages=False)

Call oiiotool to get information about input and return stdout.

Stdout should contain xml format string.

Source code in client/ayon_core/lib/transcoding.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def get_oiio_info_for_input(filepath, logger=None, subimages=False):
    """Call oiiotool to get information about input and return stdout.

    Stdout should contain xml format string.
    """
    args = get_oiio_tool_args(
        "oiiotool",
        "--info",
        "-v"
    )
    if subimages:
        args.append("-a")

    args.extend(["-i:infoformat=xml", filepath])

    output = run_subprocess(args, logger=logger)
    output = output.replace("\r\n", "\n")

    xml_started = False
    subimages_lines = []
    lines = []
    for line in output.split("\n"):
        if not xml_started:
            if not line.startswith("<"):
                continue
            xml_started = True

        if xml_started:
            lines.append(line)
            if line == "</ImageSpec>":
                subimages_lines.append(lines)
                lines = []
                xml_started = False

    if not subimages_lines:
        raise ValueError(
            "Failed to read input file \"{}\".\nOutput:\n{}".format(
                filepath, output
            )
        )

    output = []
    for subimage_lines in subimages_lines:
        xml_text = "\n".join(subimage_lines)
        output.append(parse_oiio_xml_output(xml_text, logger=logger))

    if subimages:
        return output
    return output[0]

get_oiio_input_and_channel_args(oiio_input_info, alpha_default=None)

Get input and channel arguments for oiiotool. Args: oiio_input_info (dict): Information about input from oiio tool. Should be output of function get_oiio_info_for_input. alpha_default (float, optional): Default value for alpha channel. Returns: tuple[str, str]: Tuple of input and channel arguments.

Source code in client/ayon_core/lib/transcoding.py
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
def get_oiio_input_and_channel_args(oiio_input_info, alpha_default=None):
    """Get input and channel arguments for oiiotool.
    Args:
        oiio_input_info (dict): Information about input from oiio tool.
            Should be output of function `get_oiio_info_for_input`.
        alpha_default (float, optional): Default value for alpha channel.
    Returns:
        tuple[str, str]: Tuple of input and channel arguments.
    """
    channel_names = oiio_input_info["channelnames"]
    review_channels = get_convert_rgb_channels(channel_names)

    if review_channels is None:
        raise ValueError(
            "Couldn't find channels that can be used for conversion."
        )

    red, green, blue, alpha = review_channels
    input_channels = [red, green, blue]

    channels_arg = "R={0},G={1},B={2}".format(red, green, blue)
    if alpha is not None:
        channels_arg += ",A={}".format(alpha)
        input_channels.append(alpha)
    elif alpha_default:
        channels_arg += ",A={}".format(float(alpha_default))
        input_channels.append("A")

    input_channels_str = ",".join(input_channels)

    subimages = oiio_input_info.get("subimages")
    input_arg = "-i"
    if subimages is None or subimages == 1:
        # Tell oiiotool which channels should be loaded
        # - other channels are not loaded to memory so helps to avoid memory
        #       leak issues
        # - this option is crashing if used on multipart exrs
        input_arg += ":ch={}".format(input_channels_str)

    return input_arg, channels_arg

get_rescaled_command_arguments(application, input_path, target_width, target_height, target_par=None, bg_color=None, log=None)

Get command arguments for rescaling input to target size.

Parameters:

Name Type Description Default
application str

Application for which command should be created. Currently supported are "ffmpeg" and "oiiotool".

required
input_path str

Path to input file.

required
target_width int

Width of target.

required
target_height int

Height of target.

required
target_par Optional[float]

Pixel aspect ratio of target.

None
bg_color Optional[list[int]]

List of 8bit int values for background color. Should be in range 0 - 255.

None
log Optional[Logger]

Logger used for logging.

None

Returns:

Type Description

list[str]: List of command arguments.

Source code in client/ayon_core/lib/transcoding.py
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
def get_rescaled_command_arguments(
        application,
        input_path,
        target_width,
        target_height,
        target_par=None,
        bg_color=None,
        log=None
):
    """Get command arguments for rescaling input to target size.

    Args:
        application (str): Application for which command should be created.
            Currently supported are "ffmpeg" and "oiiotool".
        input_path (str): Path to input file.
        target_width (int): Width of target.
        target_height (int): Height of target.
        target_par (Optional[float]): Pixel aspect ratio of target.
        bg_color (Optional[list[int]]): List of 8bit int values for
            background color. Should be in range 0 - 255.
        log (Optional[logging.Logger]): Logger used for logging.

    Returns:
        list[str]: List of command arguments.
    """
    command_args = []
    target_par = target_par or 1.0
    input_par = 1.0

    input_height, input_width, stream_input_par = _get_image_dimensions(
        application, input_path, log)
    if stream_input_par:
        input_par = (
            float(stream_input_par.split(":")[0])
            / float(stream_input_par.split(":")[1])
        )
    # recalculating input and target width
    input_width = int(input_width * input_par)
    target_width = int(target_width * target_par)

    # calculate aspect ratios
    target_aspect = float(target_width) / target_height
    input_aspect = float(input_width) / input_height

    # calculate scale size
    scale_size = float(input_width) / target_width
    if input_aspect < target_aspect:
        scale_size = float(input_height) / target_height

    # calculate rescaled width and height
    rescaled_width = int(input_width / scale_size)
    rescaled_height = int(input_height / scale_size)

    # calculate width and height shift
    rescaled_width_shift = int((target_width - rescaled_width) / 2)
    rescaled_height_shift = int((target_height - rescaled_height) / 2)

    if application == "ffmpeg":
        # create scale command
        scale = "scale={0}:{1}".format(input_width, input_height)
        pad = "pad={0}:{1}:({2}-iw)/2:({3}-ih)/2".format(
            target_width,
            target_height,
            target_width,
            target_height
        )
        if input_width > target_width or input_height > target_height:
            scale = "scale={0}:{1}".format(rescaled_width, rescaled_height)
            pad = "pad={0}:{1}:{2}:{3}".format(
                target_width,
                target_height,
                rescaled_width_shift,
                rescaled_height_shift
            )

        if bg_color:
            color = convert_color_values(application, bg_color)
            pad += ":{0}".format(color)
        command_args.extend(["-vf", "{0},{1}".format(scale, pad)])

    elif application == "oiiotool":
        input_info = get_oiio_info_for_input(input_path, logger=log)
        # Collect channels to export
        _, channels_arg = get_oiio_input_and_channel_args(
            input_info, alpha_default=1.0)

        command_args.extend([
            # Tell oiiotool which channels should be put to top stack
            #   (and output)
            "--ch", channels_arg,
            # Use first subimage
            "--subimage", "0"
        ])

        if input_par != 1.0:
            command_args.extend(["--pixelaspect", "1"])

        width_shift = int((target_width - input_width) / 2)
        height_shift = int((target_height - input_height) / 2)

        # default resample is not scaling source image
        resample = [
            "--resize",
            "{0}x{1}".format(input_width, input_height),
            "--origin",
            "+{0}+{1}".format(width_shift, height_shift),
        ]
        # scaled source image to target size
        if input_width > target_width or input_height > target_height:
            # form resample command
            resample = [
                "--resize:filter=lanczos3",
                "{0}x{1}".format(rescaled_width, rescaled_height),
                "--origin",
                "+{0}+{1}".format(rescaled_width_shift, rescaled_height_shift),
            ]
        command_args.extend(resample)

        fullsize = [
            "--fullsize",
            "{0}x{1}".format(target_width, target_height)
        ]
        if bg_color:
            color = convert_color_values(application, bg_color)

            fullsize.extend([
                "--pattern",
                "constant:color={0}".format(color),
                "{0}x{1}".format(target_width, target_height),
                "4",  # 4 channels
                "--over"
            ])
        command_args.extend(fullsize)

    else:
        raise ValueError(
            "\"application\" input argument should "
            "be either \"ffmpeg\" or \"oiiotool\""
        )

    return command_args

get_review_info_by_layer_name(channel_names)

Get channels info grouped by layer name.

Finds all layers in channel names and returns list of dictionaries with information about channels in layer. Example output (not real world example): [ { "name": "Main", "review_channels": { "R": "Main.red", "G": "Main.green", "B": "Main.blue", "A": None, } }, { "name": "Composed", "review_channels": { "R": "Composed.R", "G": "Composed.G", "B": "Composed.B", "A": "Composed.A", } }, ... ]

Parameters:

Name Type Description Default
channel_names list[str]

List of channel names.

required

Returns:

Type Description

list[dict]: List of channels information.

Source code in client/ayon_core/lib/transcoding.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def get_review_info_by_layer_name(channel_names):
    """Get channels info grouped by layer name.

    Finds all layers in channel names and returns list of dictionaries with
    information about channels in layer.
    Example output (not real world example):
        [
            {
                "name": "Main",
                "review_channels": {
                    "R": "Main.red",
                    "G": "Main.green",
                    "B": "Main.blue",
                    "A": None,
                }
            },
            {
                "name": "Composed",
                "review_channels": {
                    "R": "Composed.R",
                    "G": "Composed.G",
                    "B": "Composed.B",
                    "A": "Composed.A",
                }
            },
            ...
        ]

    Args:
        channel_names (list[str]): List of channel names.

    Returns:
        list[dict]: List of channels information.
    """

    layer_names_order = []
    rgba_by_layer_name = collections.defaultdict(dict)
    channels_by_layer_name = collections.defaultdict(dict)

    for channel_name in channel_names:
        layer_name = ""
        last_part = channel_name
        if "." in channel_name:
            layer_name, last_part = channel_name.rsplit(".", 1)

        channels_by_layer_name[layer_name][channel_name] = last_part
        if last_part.lower() not in {
            "r", "red",
            "g", "green",
            "b", "blue",
            "a", "alpha"
        }:
            continue

        if layer_name not in layer_names_order:
            layer_names_order.append(layer_name)
        # R, G, B or A
        channel = last_part[0].upper()
        rgba_by_layer_name[layer_name][channel] = channel_name

    # Put empty layer to the beginning of the list
    # - if input has R, G, B, A channels they should be used for review
    if "" in layer_names_order:
        layer_names_order.remove("")
        layer_names_order.insert(0, "")

    output = []
    for layer_name in layer_names_order:
        rgba_layer_info = rgba_by_layer_name[layer_name]
        red = rgba_layer_info.get("R")
        green = rgba_layer_info.get("G")
        blue = rgba_layer_info.get("B")
        if not red or not green or not blue:
            continue
        output.append({
            "name": layer_name,
            "review_channels": {
                "R": red,
                "G": green,
                "B": blue,
                "A": rgba_layer_info.get("A"),
            }
        })
    return output

get_review_layer_name(src_filepath)

Find layer name that could be used for review.

Parameters:

Name Type Description Default
src_filepath str

Path to input file.

required

Returns:

Type Description

Union[str, None]: Layer name of None.

Source code in client/ayon_core/lib/transcoding.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def get_review_layer_name(src_filepath):
    """Find layer name that could be used for review.

    Args:
        src_filepath (str): Path to input file.

    Returns:
        Union[str, None]: Layer name of None.
    """

    ext = os.path.splitext(src_filepath)[-1].lower()
    if ext != ".exr":
        return None

    # Load info about file from oiio tool
    input_info = get_oiio_info_for_input(src_filepath)
    if not input_info:
        return None

    channel_names = input_info["channelnames"]
    channels_info = get_review_info_by_layer_name(channel_names)
    for item in channels_info:
        # Layer name can be '', when review channels are 'R', 'G', 'B'
        #   without layer
        return item["name"] or None
    return None

get_transcode_temp_directory()

Creates temporary folder for transcoding.

Its local, in case of farm it is 'local' to the farm machine.

Should be much faster, needs to be cleaned up later.

Source code in client/ayon_core/lib/transcoding.py
70
71
72
73
74
75
76
77
78
79
def get_transcode_temp_directory():
    """Creates temporary folder for transcoding.

    Its local, in case of farm it is 'local' to the farm machine.

    Should be much faster, needs to be cleaned up later.
    """
    return os.path.normpath(
        tempfile.mkdtemp(prefix="op_transcoding_")
    )

parse_oiio_xml_output(xml_string, logger=None)

Parse xml output from OIIO info command.

Source code in client/ayon_core/lib/transcoding.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def parse_oiio_xml_output(xml_string, logger=None):
    """Parse xml output from OIIO info command."""
    output = {}
    if not xml_string:
        return output

    # Fix values with ampresand (lazy fix)
    # - oiiotool exports invalid xml which ElementTree can't handle
    #   e.g. "&#01;"
    # WARNING: this will affect even valid character entities. If you need
    #   those values correctly, this must take care of valid character ranges.
    #   See https://github.com/pypeclub/OpenPype/pull/2729
    matches = XML_CHAR_REF_REGEX_HEX.findall(xml_string)
    for match in matches:
        new_value = match.replace("&", "&amp;")
        xml_string = xml_string.replace(match, new_value)

    if logger is None:
        logger = logging.getLogger("OIIO-xml-parse")

    tree = xml.etree.ElementTree.fromstring(xml_string)
    attribs = {}
    output["attribs"] = attribs
    for child in tree:
        tag_name = child.tag
        if tag_name == "attrib":
            attrib_def = child.attrib
            value = convert_value_by_type_name(
                attrib_def["type"], child.text, logger=logger
            )

            attribs[attrib_def["name"]] = value
            continue

        # Channels are stored as tex on each child
        if tag_name == "channelnames":
            value = []
            for channel in child:
                value.append(channel.text)

        # Convert known integer type tags to int
        elif tag_name in INT_TAGS:
            value = int(child.text)

        # Keep value of known string tags
        elif tag_name in STRING_TAGS:
            value = child.text

        # Keep value as text for unknown tags
        # - feel free to add more tags
        else:
            value = child.text
            logger.debug((
                "Dev note (missing implementation):"
                " Unknown tag \"{}\". Value \"{}\""
            ).format(tag_name, value))

        output[child.tag] = value

    return output

should_convert_for_ffmpeg(src_filepath)

Find out if input should be converted for ffmpeg.

Currently cares only about exr inputs and is based on OpenImageIO.

Returns:

Type Description

bool/NoneType: True if should be converted, False if should not and None if can't determine.

Source code in client/ayon_core/lib/transcoding.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def should_convert_for_ffmpeg(src_filepath):
    """Find out if input should be converted for ffmpeg.

    Currently cares only about exr inputs and is based on OpenImageIO.

    Returns:
        bool/NoneType: True if should be converted, False if should not and
            None if can't determine.
    """
    # Care only about exr at this moment
    ext = os.path.splitext(src_filepath)[-1].lower()
    if ext != ".exr":
        return False

    # Can't determine if should convert or not without oiio_tool
    if not is_oiio_supported():
        return None

    # Load info about file from oiio tool
    input_info = get_oiio_info_for_input(src_filepath)
    if not input_info:
        return None

    subimages = input_info.get("subimages")
    if subimages is not None and subimages > 1:
        return True

    # Check compression
    compression = input_info["attribs"].get("compression")
    if compression in ("dwaa", "dwab"):
        return True

    # Check channels
    channel_names = input_info["channelnames"]
    review_channels = get_convert_rgb_channels(channel_names)
    if review_channels is None:
        return None

    for attr_value in input_info["attribs"].values():
        if not isinstance(attr_value, str):
            continue

        if len(attr_value) > MAX_FFMPEG_STRING_LEN:
            return True

        for char in NOT_ALLOWED_FFMPEG_CHARS:
            if char in attr_value:
                return True
    return False

split_cmd_args(in_args)

Makes sure all entered arguments are separated in individual items.

Split each argument string with " -" to identify if string contains one or more arguments. Args: in_args (list): of arguments ['-n', '-d uint10'] Returns (list): ['-n', '-d', 'unint10']

Source code in client/ayon_core/lib/transcoding.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
def split_cmd_args(in_args):
    """Makes sure all entered arguments are separated in individual items.

    Split each argument string with " -" to identify if string contains
    one or more arguments.
    Args:
        in_args (list): of arguments ['-n', '-d uint10']
    Returns
        (list): ['-n', '-d', 'unint10']
    """
    splitted_args = []
    for arg in in_args:
        if not arg.strip():
            continue
        splitted_args.extend(arg.split(" "))
    return splitted_args