Skip to content

extract_review

ExtractReview

Bases: InstancePlugin

Extracting Reviewable medias

Compulsory attribute of representation is tags list with "review", otherwise the representation is ignored.

All new representations are created and encoded by ffmpeg following presets found in AYON Settings interface at project_settings/global/publish/ExtractReview/profiles:outputs.

Source code in client/ayon_core/plugins/publish/extract_review.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
 165
 166
 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
 256
 257
 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
 318
 319
 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
 404
 405
 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
 448
 449
 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
 476
 477
 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
 527
 528
 529
 530
 531
 532
 533
 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
 658
 659
 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
 769
 770
 771
 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
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 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
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
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
1098
1099
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
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
1415
1416
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
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
class ExtractReview(pyblish.api.InstancePlugin):
    """Extracting Reviewable medias

    Compulsory attribute of representation is tags list with "review",
    otherwise the representation is ignored.

    All new representations are created and encoded by ffmpeg following
    presets found in AYON Settings interface at
    `project_settings/global/publish/ExtractReview/profiles:outputs`.
    """

    label = "Extract Review"
    order = pyblish.api.ExtractorOrder + 0.02
    families = ["review"]
    hosts = [
        "nuke",
        "maya",
        "blender",
        "houdini",
        "max",
        "shell",
        "hiero",
        "premiere",
        "harmony",
        "traypublisher",
        "fusion",
        "tvpaint",
        "resolve",
        "webpublisher",
        "aftereffects",
        "flame",
        "unreal",
        "batchdelivery",
        "photoshop"
    ]

    settings_category = "core"
    # Supported extensions
    image_exts = {"exr", "jpg", "jpeg", "png", "dpx", "tga", "tiff", "tif"}
    video_exts = {"mov", "mp4"}
    supported_exts = image_exts | video_exts

    alpha_exts = {"exr", "png", "dpx"}

    # Preset attributes
    profiles = []

    def process(self, instance):
        self.log.debug(str(instance.data["representations"]))
        # Skip review when requested.
        if not instance.data.get("review", True):
            return

        # Run processing
        self.main_process(instance)

        # Make sure cleanup happens and pop representations with "delete" tag.
        for repre in tuple(instance.data["representations"]):
            tags = repre.get("tags") or []
            # Representation is not marked to be deleted
            if "delete" not in tags:
                continue

            # The representation can be used as thumbnail source
            if "thumbnail" in tags or "need_thumbnail" in tags:
                continue

            self.log.debug(
                "Removing representation: {}".format(repre)
            )
            instance.data["representations"].remove(repre)

    def _get_outputs_for_instance(self, instance):
        host_name = instance.context.data["hostName"]
        product_type = instance.data["productType"]
        task_type = None
        task_entity = instance.data.get("taskEntity")
        if task_entity:
            task_type = task_entity["taskType"]

        self.log.debug("Host: \"{}\"".format(host_name))
        self.log.debug("Product type: \"{}\"".format(product_type))
        self.log.debug("Task type: \"{}\"".format(task_type))

        profile = filter_profiles(
            self.profiles,
            {
                "hosts": host_name,
                "product_types": product_type,
                "task_types": task_type
            },
            logger=self.log)
        if not profile:
            self.log.info((
                "Skipped instance. None of profiles in presets are for"
                " Host: \"{}\" | Product type: \"{}\""
            ).format(host_name, product_type))
            return

        self.log.debug("Matching profile: \"{}\"".format(json.dumps(profile)))

        product_name = instance.data.get("productName")
        instance_families = self.families_from_instance(instance)
        filtered_outputs = self.filter_output_defs(
            profile, product_name, instance_families
        )
        if not filtered_outputs:
            self.log.info((
                "Skipped instance. All output definitions from selected"
                " profile do not match instance families \"{}\" or"
                " product name \"{}\"."
            ).format(str(instance_families), product_name))

        # Store `filename_suffix` to save arguments
        profile_outputs = []
        for filename_suffix, definition in filtered_outputs.items():
            definition["filename_suffix"] = filename_suffix
            profile_outputs.append(definition)

        return profile_outputs

    def _get_outputs_per_representations(self, instance, profile_outputs):
        outputs_per_representations = []
        for repre in instance.data["representations"]:
            repre_name = str(repre.get("name"))
            tags = repre.get("tags") or []
            custom_tags = repre.get("custom_tags")
            if "review" not in tags:
                self.log.debug((
                    "Repre: {} - Didn't find \"review\" in tags. Skipping"
                ).format(repre_name))
                continue

            if "thumbnail" in tags:
                self.log.debug((
                    "Repre: {} - Found \"thumbnail\" in tags. Skipping"
                ).format(repre_name))
                continue

            if "passing" in tags:
                self.log.debug((
                    "Repre: {} - Found \"passing\" in tags. Skipping"
                ).format(repre_name))
                continue

            input_ext = repre["ext"].lower()
            if input_ext.startswith("."):
                input_ext = input_ext[1:]

            if input_ext not in self.supported_exts:
                self.log.info(
                    "Representation has unsupported extension \"{}\"".format(
                        input_ext
                    )
                )
                continue

            # Filter output definition by representation's
            # custom tags (optional)
            outputs = self.filter_outputs_by_custom_tags(
                profile_outputs, custom_tags)
            if not outputs:
                self.log.info((
                    "Skipped representation. All output definitions from"
                    " selected profile does not match to representation's"
                    " custom tags. \"{}\""
                ).format(str(custom_tags)))
                continue

            outputs_per_representations.append((repre, outputs))
        return outputs_per_representations

    def _single_frame_filter(self, input_filepaths, output_defs):
        single_frame_image = False
        if len(input_filepaths) == 1:
            ext = os.path.splitext(input_filepaths[0])[-1]
            single_frame_image = ext.lower() in IMAGE_EXTENSIONS

        filtered_defs = []
        for output_def in output_defs:
            output_filters = output_def.get("filter") or {}
            frame_filter = output_filters.get("single_frame_filter")
            if (
                (not single_frame_image and frame_filter == "single_frame")
                or (single_frame_image and frame_filter == "multi_frame")
            ):
                continue

            filtered_defs.append(output_def)

        return filtered_defs

    def main_process(self, instance):
        instance_label = get_publish_instance_label(instance)
        self.log.debug("Processing instance \"{}\"".format(instance_label))
        profile_outputs = self._get_outputs_for_instance(instance)
        if not profile_outputs:
            return

        # Loop through representations
        outputs_per_repres = self._get_outputs_per_representations(
            instance, profile_outputs
        )

        for repre, output_defs in outputs_per_repres:
            # Check if input should be preconverted before processing
            # Store original staging dir (it's value may change)
            src_repre_staging_dir = repre["stagingDir"]
            # Receive filepath to first file in representation
            first_input_path = None
            input_filepaths = []
            if not self.input_is_sequence(repre):
                first_input_path = os.path.join(
                    src_repre_staging_dir, repre["files"]
                )
                input_filepaths.append(first_input_path)
            else:
                for filename in repre["files"]:
                    filepath = os.path.join(
                        src_repre_staging_dir, filename
                    )
                    input_filepaths.append(filepath)
                    if first_input_path is None:
                        first_input_path = filepath

            filtered_output_defs = self._single_frame_filter(
                input_filepaths, output_defs
            )
            if not filtered_output_defs:
                self.log.debug((
                    "Repre: {} - All output definitions were filtered"
                    " out by single frame filter. Skipping"
                ).format(repre["name"]))
                continue

            # Skip if file is not set
            if first_input_path is None:
                self.log.warning((
                    "Representation \"{}\" have empty files. Skipped."
                ).format(repre["name"]))
                continue

            # Determine if representation requires pre conversion for ffmpeg
            do_convert = should_convert_for_ffmpeg(first_input_path)
            # If result is None the requirement of conversion can't be
            #   determined
            if do_convert is None:
                self.log.info((
                    "Can't determine if representation requires conversion."
                    " Skipped."
                ))
                continue

            layer_name = get_review_layer_name(first_input_path)

            # Do conversion if needed
            #   - change staging dir of source representation
            #   - must be set back after output definitions processing
            if do_convert:
                new_staging_dir = get_temp_dir(
                    project_name=instance.context.data["projectName"],
                    use_local_temp=True,
                )
                repre["stagingDir"] = new_staging_dir

                convert_input_paths_for_ffmpeg(
                    input_filepaths,
                    new_staging_dir,
                    self.log
                )

            try:
                self._render_output_definitions(
                    instance,
                    repre,
                    src_repre_staging_dir,
                    filtered_output_defs,
                    layer_name
                )

            finally:
                # Make sure temporary staging is cleaned up and representation
                #   has set origin stagingDir
                if do_convert:
                    # Set staging dir of source representation back to previous
                    #   value
                    repre["stagingDir"] = src_repre_staging_dir
                    if os.path.exists(new_staging_dir):
                        shutil.rmtree(new_staging_dir)

    def _render_output_definitions(
        self,
        instance,
        repre,
        src_repre_staging_dir,
        output_definitions,
        layer_name
    ):
        fill_data = copy.deepcopy(instance.data["anatomyData"])
        for _output_def in output_definitions:
            output_def = copy.deepcopy(_output_def)
            # Make sure output definition has "tags" key
            if "tags" not in output_def:
                output_def["tags"] = []

            if "burnins" not in output_def:
                output_def["burnins"] = []

            # Create copy of representation
            new_repre = copy.deepcopy(repre)
            new_tags = new_repre.get("tags") or []
            # Make sure new representation has origin staging dir
            #   - this is because source representation may change
            #       it's staging dir because of ffmpeg conversion
            new_repre["stagingDir"] = src_repre_staging_dir

            # Remove "delete" tag from new repre if there is
            if "delete" in new_tags:
                new_tags.remove("delete")

            if "need_thumbnail" in new_tags:
                new_tags.remove("need_thumbnail")

            # Add additional tags from output definition to representation
            for tag in output_def["tags"]:
                if tag not in new_tags:
                    new_tags.append(tag)

            # Return tags to new representation
            new_repre["tags"] = new_tags

            # Add burnin link from output definition to representation
            for burnin in output_def["burnins"]:
                if burnin not in new_repre.get("burnins", []):
                    if not new_repre.get("burnins"):
                        new_repre["burnins"] = []
                    new_repre["burnins"].append(str(burnin))

            self.log.debug(
                "Linked burnins: `{}`".format(new_repre.get("burnins"))
            )

            self.log.debug(
                "New representation tags: `{}`".format(
                    new_repre.get("tags"))
            )

            temp_data = self.prepare_temp_data(instance, repre, output_def)
            new_frame_files = {}
            if temp_data.input_is_sequence:
                self.log.debug("Checking sequence to fill gaps in sequence..")

                files = temp_data.origin_repre["files"]
                collections = clique.assemble(
                    files,
                )[0]
                if len(collections) != 1:
                    raise KnownPublishError(
                        "Multiple collections {} found.".format(collections))

                collection = collections[0]

                fill_missing_frames = _output_def["fill_missing_frames"]
                if fill_missing_frames == "closest_existing":
                    new_frame_files = self.fill_sequence_gaps_from_existing(
                        collection=collection,
                        staging_dir=new_repre["stagingDir"],
                        start_frame=temp_data.frame_start,
                        end_frame=temp_data.frame_end,
                    )
                elif fill_missing_frames == "blank":
                    new_frame_files = self.fill_sequence_gaps_with_blanks(
                        collection=collection,
                        staging_dir=new_repre["stagingDir"],
                        start_frame=temp_data.frame_start,
                        end_frame=temp_data.frame_end,
                        resolution_width=temp_data.resolution_width,
                        resolution_height=temp_data.resolution_height,
                        extension=temp_data.input_ext,
                        temp_data=temp_data,
                    )
                elif fill_missing_frames == "previous_version":
                    fill_output = fill_sequence_gaps_with_previous_version(
                        collection=collection,
                        staging_dir=new_repre["stagingDir"],
                        instance=instance,
                        current_repre_name=repre["name"],
                        start_frame=temp_data.frame_start,
                        end_frame=temp_data.frame_end,
                    )
                    _, new_frame_files = fill_output
                    # fallback to original workflow
                    if new_frame_files is None:
                        self.log.warning(
                            "Falling back to filling from currently "
                            "last rendered."
                        )
                        new_frame_files = (
                            self.fill_sequence_gaps_from_existing(
                            collection=collection,
                            staging_dir=new_repre["stagingDir"],
                            start_frame=temp_data.frame_start,
                            end_frame=temp_data.frame_end,
                        ))
                elif fill_missing_frames == "only_rendered":
                    temp_data.explicit_input_paths = [
                        os.path.join(
                            new_repre["stagingDir"], file
                        ).replace("\\", "/")
                        for file in files
                    ]
                    frame_start = min(collection.indexes)
                    frame_end = max(collection.indexes)
                    # modify range for burnins
                    instance.data["frameStart"] = frame_start
                    instance.data["frameEnd"] = frame_end
                    temp_data.frame_start = frame_start
                    temp_data.frame_end = frame_end

            temp_data.filled_files = new_frame_files

            # create or update outputName
            output_name = new_repre.get("outputName", "")
            output_ext = new_repre["ext"]
            if output_name:
                output_name += "_"
            output_name += output_def["filename_suffix"]
            if temp_data.without_handles:
                output_name += "_noHandles"

            # add outputName to anatomy format fill_data
            fill_data.update({
                "output": output_name,
                "ext": output_ext,

                # By adding `timecode` as data we can use it
                # in the ffmpeg arguments for `--timecode` so that editorial
                # like Resolve or Premiere can detect the start frame for e.g.
                # review output files
                "timecode": frame_to_timecode(
                    frame=temp_data.frame_start_handle,
                    fps=float(instance.data["fps"])
                )
            })

            try:  # temporary until oiiotool is supported cross platform
                ffmpeg_args = self._ffmpeg_arguments(
                    output_def,
                    instance,
                    new_repre,
                    temp_data,
                    fill_data,
                    layer_name,
                )
            except ZeroDivisionError:
                # TODO recalculate width and height using OIIO before
                #   conversion
                if 'exr' in temp_data.origin_repre["ext"]:
                    self.log.warning(
                        (
                            "Unsupported compression on input files."
                            " Skipping!!!"
                        ),
                        exc_info=True
                    )
                    return
                raise NotImplementedError

            subprcs_cmd = " ".join(ffmpeg_args)

            # run subprocess
            self.log.debug("Executing: {}".format(subprcs_cmd))

            run_subprocess(subprcs_cmd, shell=True, logger=self.log)

            # delete files added to fill gaps
            if new_frame_files:
                for filepath in new_frame_files.values():
                    os.unlink(filepath)

            for filepath in temp_data.paths_to_remove:
                os.unlink(filepath)

            new_repre.update({
                "fps": temp_data.fps,
                "name": "{}_{}".format(output_name, output_ext),
                "outputName": output_name,
                "outputDef": output_def,
                "ffmpeg_cmd": subprcs_cmd
            })

            # Force to pop these key if are in new repre
            new_repre.pop("thumbnail", None)
            if "clean_name" in new_repre.get("tags", []):
                new_repre.pop("outputName")

            # adding representation
            self.log.debug(
                "Adding new representation: {}".format(new_repre)
            )
            instance.data["representations"].append(new_repre)

            add_repre_files_for_cleanup(instance, new_repre)

    def input_is_sequence(self, repre):
        """Deduce from representation data if input is sequence."""
        # TODO GLOBAL ISSUE - Find better way how to find out if input
        #  is sequence. Issues (in theory):
        #   - there may be multiple files ant not be sequence
        #   - remainders are not checked at all
        #   - there can be more than one collection
        return isinstance(repre["files"], (list, tuple))

    def prepare_temp_data(self, instance, repre, output_def) -> TempData:
        """Prepare dictionary with values used across extractor's process.

        All data are collected from instance, context, origin representation
        and output definition.

        There are few required keys in Instance data: "frameStart", "frameEnd"
        and "fps".

        Args:
            instance (Instance): Currently processed instance.
            repre (dict): Representation from which new representation was
                copied.
            output_def (dict): Definition of output of this plugin.

        Returns:
            TempData: All data which are used across methods during process.
                Their values should not change during process but new keys
                with values may be added.
        """

        frame_start = instance.data["frameStart"]
        frame_end = instance.data["frameEnd"]

        # Try to get handles from instance
        handle_start = instance.data.get("handleStart")
        handle_end = instance.data.get("handleEnd")
        # If even one of handle values is not set on instance use
        # handles from context
        if handle_start is None or handle_end is None:
            handle_start = instance.context.data["handleStart"]
            handle_end = instance.context.data["handleEnd"]

        frame_start_handle = frame_start - handle_start
        frame_end_handle = frame_end + handle_end

        # Change output frames when output should be without handles
        without_handles = bool("no-handles" in output_def["tags"])
        if without_handles:
            output_frame_start = frame_start
            output_frame_end = frame_end
        else:
            output_frame_start = frame_start_handle
            output_frame_end = frame_end_handle

        handles_are_set = handle_start > 0 or handle_end > 0

        with_audio = True
        if (
            # Check if has `no-audio` tag
            "no-audio" in output_def["tags"]
            # Check if instance has ny audio in data
            or not instance.data.get("audio")
        ):
            with_audio = False

        input_is_sequence = self.input_is_sequence(repre)
        input_allow_bg = False
        first_sequence_frame = None

        if input_is_sequence and repre["files"]:
            # Calculate first frame that should be used
            cols, _ = clique.assemble(repre["files"])
            input_frames = list(sorted(cols[0].indexes))
            first_sequence_frame = input_frames[0]
            # WARNING: This is an issue as we don't know if first frame
            #   is with or without handles!
            # - handle start is added but how do not know if we should
            output_duration = (output_frame_end - output_frame_start) + 1
            if (
                without_handles
                and len(input_frames) - handle_start >= output_duration
            ):
                first_sequence_frame += handle_start

            ext = os.path.splitext(repre["files"][0])[1].replace(".", "")
            if ext.lower() in self.alpha_exts:
                input_allow_bg = True
        else:
            ext = os.path.splitext(repre["files"])[1].replace(".", "")

        return TempData(
            fps=float(instance.data["fps"]),
            frame_start=frame_start,
            frame_end=frame_end,
            handle_start=handle_start,
            handle_end=handle_end,
            frame_start_handle=frame_start_handle,
            frame_end_handle=frame_end_handle,
            output_frame_start=int(output_frame_start),
            output_frame_end=int(output_frame_end),
            pixel_aspect=instance.data.get("pixelAspect", 1),
            resolution_width=instance.data.get("resolutionWidth"),
            resolution_height=instance.data.get("resolutionHeight"),
            origin_repre=repre,
            input_is_sequence=input_is_sequence,
            first_sequence_frame=first_sequence_frame,
            input_allow_bg=input_allow_bg,
            with_audio=with_audio,
            without_handles=without_handles,
            handles_are_set=handles_are_set,
            input_ext=ext,
            explicit_input_paths=[],  # absolute paths to rendered files
            paths_to_remove=[]
        )

    def _ffmpeg_arguments(
        self,
        output_def,
        instance,
        new_repre,
        temp_data,
        fill_data,
        layer_name
    ):
        """Prepares ffmpeg arguments for expected extraction.

        Prepares input and output arguments based on output definition and
        input files.

        Args:
            output_def (dict): Currently processed output definition.
            instance (Instance): Currently processed instance.
            new_repre (dict): Representation representing output of this
                process.
            temp_data (TempData): Base data for successful process.
        """

        # Get FFmpeg arguments from profile presets
        out_def_ffmpeg_args = output_def.get("ffmpeg_args") or {}

        _ffmpeg_input_args = out_def_ffmpeg_args.get("input") or []
        _ffmpeg_output_args = out_def_ffmpeg_args.get("output") or []
        _ffmpeg_video_filters = out_def_ffmpeg_args.get("video_filters") or []
        _ffmpeg_audio_filters = out_def_ffmpeg_args.get("audio_filters") or []

        # Cleanup empty strings
        ffmpeg_input_args = [
            value for value in _ffmpeg_input_args if value.strip()
        ]
        ffmpeg_video_filters = [
            value for value in _ffmpeg_video_filters if value.strip()
        ]
        ffmpeg_audio_filters = [
            value for value in _ffmpeg_audio_filters if value.strip()
        ]

        ffmpeg_output_args = []
        for value in _ffmpeg_output_args:
            value = value.strip()
            if not value:
                continue
            try:
                value = value.format(**fill_data)
            except Exception:
                self.log.warning(
                    "Failed to format ffmpeg argument: {}".format(value),
                    exc_info=True
                )
                pass
            ffmpeg_output_args.append(value)

        # Prepare input and output filepaths
        self.input_output_paths(new_repre, output_def, temp_data)

        # Set output frames len to 1 when output is single image
        if (
            temp_data.output_ext_is_image
            and not temp_data.output_is_sequence
        ):
            output_frames_len = 1

        else:
            output_frames_len = (
                temp_data.output_frame_end
                - temp_data.output_frame_start
                + 1
            )

        duration_seconds = float(output_frames_len / temp_data.fps)

        # Define which layer should be used
        if layer_name:
            ffmpeg_input_args.extend(["-layer", layer_name])

        explicit_input_paths = temp_data.explicit_input_paths
        if temp_data.input_is_sequence and not explicit_input_paths:
            # Set start frame of input sequence (just frame in filename)
            # - definition of input filepath
            # - add handle start if output should be without handles
            start_number = temp_data.first_sequence_frame
            if temp_data.without_handles and temp_data.handles_are_set:
                start_number += temp_data.handle_start
            ffmpeg_input_args.extend([
                "-start_number", str(start_number)
            ])

            # TODO add fps mapping `{fps: fraction}` ?
            # - e.g.: {
            #     "25": "25/1",
            #     "24": "24/1",
            #     "23.976": "24000/1001"
            # }
            # Add framerate to input when input is sequence
            ffmpeg_input_args.extend([
                "-framerate", str(temp_data.fps)
            ])
            # Add duration of an input sequence if output is video
            if not temp_data.output_is_sequence:
                ffmpeg_input_args.extend([
                    "-to", "{:0.10f}".format(duration_seconds)
                ])

        if temp_data.output_is_sequence and not explicit_input_paths:
            # Set start frame of output sequence (just frame in filename)
            # - this is definition of an output
            ffmpeg_output_args.extend([
                "-start_number", str(temp_data.output_frame_start)
            ])

        # Change output's duration and start point if should not contain
        # handles
        if temp_data.without_handles and temp_data.handles_are_set:
            # Set output duration in seconds
            ffmpeg_output_args.extend([
                "-t", "{:0.10}".format(duration_seconds)
            ])

            # Add -ss (start offset in seconds) if input is not sequence
            if not temp_data.input_is_sequence:
                start_sec = float(temp_data.handle_start) / temp_data.fps
                # Set start time without handles
                # - Skip if start sec is 0.0
                if start_sec > 0.0:
                    ffmpeg_input_args.extend([
                        "-ss", "{:0.10f}".format(start_sec)
                    ])

        # Set frame range of output when input or output is sequence
        elif temp_data.output_is_sequence:
            ffmpeg_output_args.extend([
                "-frames:v", str(output_frames_len)
            ])

        if not explicit_input_paths:
            # Add video/image input path
            ffmpeg_input_args.extend([
                "-i", path_to_subprocess_arg(temp_data.full_input_path)
            ])
        else:
            frame_duration = 1 / temp_data.fps

            explicit_frames_meta = tempfile.NamedTemporaryFile(
                mode="w", prefix="explicit_frames", suffix=".txt", delete=False
            )
            explicit_frames_meta.close()
            explicit_frames_path = explicit_frames_meta.name
            with open(explicit_frames_path, "w") as fp:
                lines = [
                    f"file '{path}'{os.linesep}duration {frame_duration}"
                    for path in temp_data.explicit_input_paths
                ]
                fp.write("\n".join(lines))
            temp_data.paths_to_remove.append(explicit_frames_path)

            # let ffmpeg use only rendered files, might have gaps
            ffmpeg_input_args.extend([
                "-f", "concat",
                "-safe", "0",
                "-i", path_to_subprocess_arg(explicit_frames_path),
                "-r", str(temp_data.fps)
            ])

        # Add audio arguments if there are any. Skipped when output are images.
        if not temp_data.output_ext_is_image and temp_data.with_audio:
            audio_in_args, audio_filters, audio_out_args = self.audio_args(
                instance, temp_data, duration_seconds
            )
            ffmpeg_input_args.extend(audio_in_args)
            ffmpeg_audio_filters.extend(audio_filters)
            ffmpeg_output_args.extend(audio_out_args)

        res_filters = self.rescaling_filters(temp_data, output_def, new_repre)
        ffmpeg_video_filters.extend(res_filters)

        ffmpeg_input_args = self.split_ffmpeg_args(ffmpeg_input_args)

        lut_filters = self.lut_filters(new_repre, instance, ffmpeg_input_args)
        ffmpeg_video_filters.extend(lut_filters)

        bg_alpha = 0.0
        bg_color = output_def.get("bg_color")
        if bg_color:
            bg_red, bg_green, bg_blue, bg_alpha = bg_color

        if bg_alpha > 0.0:
            if not temp_data.input_allow_bg:
                self.log.info((
                    "Output definition has defined BG color input was"
                    " resolved as does not support adding BG."
                ))
            else:
                bg_color_hex = "#{0:0>2X}{1:0>2X}{2:0>2X}".format(
                    bg_red, bg_green, bg_blue
                )
                bg_color_str = "{}@{}".format(bg_color_hex, bg_alpha)

                self.log.info("Applying BG color {}".format(bg_color_str))
                color_args = [
                    "split=2[bg][fg]",
                    "[bg]drawbox=c={}:replace=1:t=fill[bg]".format(
                        bg_color_str
                    ),
                    "[bg][fg]overlay=format=auto"
                ]
                # Prepend bg color change before all video filters
                # NOTE at the time of creation it is required as video filters
                #   from settings may affect color of BG
                #   e.g. `eq` can remove alpha from input
                for arg in reversed(color_args):
                    ffmpeg_video_filters.insert(0, arg)

        # Add argument to override output file
        ffmpeg_output_args.append("-y")

        # NOTE This must be latest added item to output arguments.
        ffmpeg_output_args.append(
            path_to_subprocess_arg(temp_data.full_output_path)
        )

        return self.ffmpeg_full_args(
            ffmpeg_input_args,
            ffmpeg_video_filters,
            ffmpeg_audio_filters,
            ffmpeg_output_args
        )

    def split_ffmpeg_args(self, 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.
        """
        splitted_args = []
        for arg in in_args:
            sub_args = arg.split(" -")
            if len(sub_args) == 1:
                if arg and arg not in splitted_args:
                    splitted_args.append(arg)
                continue

            for idx, arg in enumerate(sub_args):
                if idx != 0:
                    arg = "-" + arg

                if arg and arg not in splitted_args:
                    splitted_args.append(arg)
        return splitted_args

    def ffmpeg_full_args(
        self, input_args, video_filters, audio_filters, output_args
    ):
        """Post processing of collected FFmpeg arguments.

        Just verify that output arguments does not contain video or audio
        filters which may cause issues because of duplicated argument entry.
        Filters found in output arguments are moved to list they belong to.

        Args:
            input_args (list): All collected ffmpeg arguments with inputs.
            video_filters (list): All collected video filters.
            audio_filters (list): All collected audio filters.
            output_args (list): All collected ffmpeg output arguments with
                output filepath.

        Returns:
            list: Containing all arguments ready to run in subprocess.
        """
        output_args = self.split_ffmpeg_args(output_args)

        video_args_dentifiers = ["-vf", "-filter:v"]
        audio_args_dentifiers = ["-af", "-filter:a"]
        for arg in tuple(output_args):
            for identifier in video_args_dentifiers:
                if arg.startswith("{} ".format(identifier)):
                    output_args.remove(arg)
                    arg = arg.replace(identifier, "").strip()
                    video_filters.append(arg)

            for identifier in audio_args_dentifiers:
                if arg.startswith("{} ".format(identifier)):
                    output_args.remove(arg)
                    arg = arg.replace(identifier, "").strip()
                    audio_filters.append(arg)

        all_args = [
            subprocess.list2cmdline(get_ffmpeg_tool_args("ffmpeg"))
        ]
        all_args.extend(input_args)
        if video_filters:
            all_args.append("-filter:v")
            all_args.append("\"{}\"".format(",".join(video_filters)))

        if audio_filters:
            all_args.append("-filter:a")
            all_args.append("\"{}\"".format(",".join(audio_filters)))

        all_args.extend(output_args)

        return all_args

    def fill_sequence_gaps_with_blanks(
        self,
        collection: str,
        staging_dir: str,
        start_frame: int,
        end_frame: int,
        resolution_width: int,
        resolution_height: int,
        extension: str,
        temp_data: TempData
    ) -> Optional[dict[int, str]]:
        """Fills missing files by blank frame."""

        blank_frame_path = None

        added_files = {}

        col_format = collection.format("{head}{padding}{tail}")
        for frame in range(start_frame, end_frame + 1):
            if frame in collection.indexes:
                continue
            hole_fpath = os.path.join(staging_dir, col_format % frame)
            if blank_frame_path is None:
                blank_frame_path = self._create_blank_frame(
                    staging_dir, extension, resolution_width, resolution_height
                )
                temp_data.paths_to_remove.append(blank_frame_path)
            speedcopy.copyfile(blank_frame_path, hole_fpath)
            added_files[frame] = hole_fpath

        return added_files

    def _create_blank_frame(
        self,
        staging_dir,
        extension,
        resolution_width,
        resolution_height
    ):
        blank_frame_path = os.path.join(staging_dir, f"blank.{extension}")

        command = get_ffmpeg_tool_args(
            "ffmpeg",
            "-f", "lavfi",
            "-i", "color=c=black:s={}x{}:d=1".format(
                resolution_width, resolution_height
            ),
            "-tune", "stillimage",
            "-frames:v", "1",
            blank_frame_path
        )

        self.log.debug("Executing: {}".format(" ".join(command)))
        output = run_subprocess(
            command, logger=self.log
        )
        self.log.debug("Output: {}".format(output))

        return blank_frame_path

    def fill_sequence_gaps_from_existing(
        self,
        collection,
        staging_dir: str,
        start_frame: int,
        end_frame: int
    ) -> dict[int, str]:
        """Fill missing files in sequence by duplicating existing ones.

        This will take nearest frame file and copy it with so as to fill
        gaps in sequence. Last existing file there is is used to for the
        hole ahead.

        Args:
            collection (clique.collection)
            staging_dir (str): Path to staging directory.
            start_frame (int): Sequence start (no matter what files are there)
            end_frame (int): Sequence end (no matter what files are there)

        Returns:
            dict[int, str] of added files. Those should be cleaned after work
                is done.

        Raises:
            KnownPublishError: if more than one collection is obtained.
        """

        # Prepare which hole is filled with what frame
        #   - the frame is filled only with already existing frames
        prev_frame = next(iter(collection.indexes))
        hole_frame_to_nearest = {}
        for frame in range(int(start_frame), int(end_frame) + 1):
            if frame in collection.indexes:
                prev_frame = frame
            else:
                # Use previous frame as source for hole
                hole_frame_to_nearest[frame] = prev_frame

        # Calculate paths
        added_files = {}
        col_format = collection.format("{head}{padding}{tail}")
        for hole_frame, src_frame in hole_frame_to_nearest.items():
            hole_fpath = os.path.join(staging_dir, col_format % hole_frame)
            src_fpath = os.path.join(staging_dir, col_format % src_frame)
            if not os.path.isfile(src_fpath):
                raise KnownPublishError(
                    "Missing previously detected file: {}".format(src_fpath))

            speedcopy.copyfile(src_fpath, hole_fpath)
            added_files[hole_frame] = hole_fpath

        return added_files

    def input_output_paths(self, new_repre, output_def, temp_data: TempData):
        """Deduce input nad output file paths based on entered data.

        Input may be sequence of images, video file or single image file and
        same can be said about output, this method helps to find out what
        their paths are.

        It is validated that output directory exist and creates if not.

        During process are set "files", "stagingDir", "ext" and
        "sequence_file" (if output is sequence) keys to new representation.
        """

        repre = temp_data.origin_repre
        src_staging_dir = repre["stagingDir"]
        dst_staging_dir = new_repre["stagingDir"]

        if temp_data.input_is_sequence:
            collections = clique.assemble(repre["files"])[0]
            full_input_path = os.path.join(
                src_staging_dir,
                collections[0].format("{head}{padding}{tail}")
            )

            filename = collections[0].format("{head}")
            if filename.endswith("."):
                filename = filename[:-1]

            # Make sure to have full path to one input file
            full_input_path_single_file = os.path.join(
                src_staging_dir, repre["files"][0]
            )

        else:
            full_input_path = os.path.join(
                src_staging_dir, repre["files"]
            )
            filename = os.path.splitext(repre["files"])[0]

            # Make sure to have full path to one input file
            full_input_path_single_file = full_input_path

        filled_files = temp_data.filled_files
        if filled_files:
            first_frame, first_file = next(iter(filled_files.items()))
            if first_file < full_input_path_single_file:
                self.log.warning(f"Using filled frame: '{first_file}'")
                full_input_path_single_file = first_file
                temp_data.first_sequence_frame = first_frame

        filename_suffix = output_def["filename_suffix"]

        output_ext = output_def.get("ext")
        # Use input extension if output definition do not specify it
        if output_ext is None:
            output_ext = os.path.splitext(full_input_path)[1]

        # TODO Define if extension should have dot or not
        if output_ext.startswith("."):
            output_ext = output_ext[1:]

        output_ext = output_ext.lower()

        # Store extension to representation
        new_repre["ext"] = output_ext

        self.log.debug("New representation ext: `{}`".format(output_ext))

        # Output is image file sequence with frames
        output_ext_is_image = bool(output_ext in self.image_exts)
        output_is_sequence = bool(
            output_ext_is_image
            and "sequence" in output_def["tags"]
        )
        if output_is_sequence:
            new_repre_files = []
            frame_start = temp_data.output_frame_start
            frame_end = temp_data.output_frame_end

            filename_base = "{}_{}".format(filename, filename_suffix)
            # Temporary template for frame filling. Example output:
            # "basename.%04d.exr" when `frame_end` == 1001
            repr_file = "{}.%{:0>2}d.{}".format(
                filename_base, len(str(frame_end)), output_ext
            )

            for frame in range(frame_start, frame_end + 1):
                new_repre_files.append(repr_file % frame)

            new_repre["sequence_file"] = repr_file
            full_output_path = os.path.join(
                dst_staging_dir, filename_base, repr_file
            )

        else:
            repr_file = "{}_{}.{}".format(
                filename, filename_suffix, output_ext
            )
            full_output_path = os.path.join(dst_staging_dir, repr_file)
            new_repre_files = repr_file

        # Store files to representation
        new_repre["files"] = new_repre_files

        # Make sure stagingDire exists
        dst_staging_dir = os.path.normpath(os.path.dirname(full_output_path))
        if not os.path.exists(dst_staging_dir):
            self.log.debug("Creating dir: {}".format(dst_staging_dir))
            os.makedirs(dst_staging_dir)

        # Store stagingDir to representation
        new_repre["stagingDir"] = dst_staging_dir

        # Store paths to temp data
        temp_data.full_input_path = full_input_path
        temp_data.full_input_path_single_file = full_input_path_single_file
        temp_data.full_output_path = full_output_path

        # Store information about output
        temp_data.output_ext_is_image = output_ext_is_image
        temp_data.output_is_sequence = output_is_sequence

        self.log.debug("Input path {}".format(full_input_path))
        self.log.debug("Output path {}".format(full_output_path))

    def audio_args(self, instance, temp_data: TempData, duration_seconds):
        """Prepares FFMpeg arguments for audio inputs."""
        audio_in_args = []
        audio_filters = []
        audio_out_args = []
        audio_inputs = instance.data.get("audio")
        if not audio_inputs:
            return audio_in_args, audio_filters, audio_out_args

        for audio in audio_inputs:
            offset_seconds = 0
            if offset_seconds > 0:
                audio_in_args.append(
                    "-ss {}".format(offset_seconds)
                )

            elif offset_seconds < 0:
                audio_in_args.append(
                    "-itsoffset {}".format(abs(offset_seconds))
                )

            # Audio duration is offset from `-ss`
            audio_duration = duration_seconds + offset_seconds

            # Set audio duration
            audio_in_args.append("-to {:0.10f}".format(audio_duration))

            # Ignore video data from audio input
            audio_in_args.append("-vn")

            # Add audio input path
            audio_in_args.append("-i {}".format(
                path_to_subprocess_arg(audio["filename"])
            ))

        # NOTE: These were changed from input to output arguments.
        # NOTE: value in "-ac" was hardcoded to 2, changed to audio inputs len.
        # Need to merge audio if there are more than 1 input.
        if len(audio_inputs) > 1:
            audio_out_args.append("-filter_complex amerge")
            audio_out_args.append("-ac {}".format(len(audio_inputs)))

        return audio_in_args, audio_filters, audio_out_args

    def get_letterbox_filters(
        self,
        letter_box_def,
        output_width,
        output_height
    ):
        output = []

        ratio = letter_box_def["ratio"]
        fill_color = letter_box_def["fill_color"]
        f_red, f_green, f_blue, f_alpha = fill_color
        fill_color_hex = "{0:0>2X}{1:0>2X}{2:0>2X}".format(
            f_red, f_green, f_blue
        )
        fill_color_alpha = f_alpha

        line_thickness = letter_box_def["line_thickness"]
        line_color = letter_box_def["line_color"]
        l_red, l_green, l_blue, l_alpha = line_color
        line_color_hex = "{0:0>2X}{1:0>2X}{2:0>2X}".format(
            l_red, l_green, l_blue
        )
        line_color_alpha = l_alpha

        # test ratios and define if pillar or letter boxes
        output_ratio = float(output_width) / float(output_height)
        self.log.debug("Output ratio: {} LetterBox ratio: {}".format(
            output_ratio, ratio
        ))
        pillar = output_ratio > ratio
        need_mask = format(output_ratio, ".3f") != format(ratio, ".3f")
        if not need_mask:
            return []

        if not pillar:
            if fill_color_alpha > 0:
                top_box = (
                    "drawbox=0:0:{width}"
                    ":round(({height}-({width}/{ratio}))/2)"
                    ":t=fill:c={color}@{alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    color=fill_color_hex,
                    alpha=fill_color_alpha
                )

                bottom_box = (
                    "drawbox=0"
                    ":{height}-round(({height}-({width}/{ratio}))/2)"
                    ":{width}"
                    ":round(({height}-({width}/{ratio}))/2)"
                    ":t=fill:c={color}@{alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    color=fill_color_hex,
                    alpha=fill_color_alpha
                )
                output.extend([top_box, bottom_box])

            if line_color_alpha > 0 and line_thickness > 0:
                top_line = (
                    "drawbox=0"
                    ":round(({height}-({width}/{ratio}))/2)-{l_thick}"
                    ":{width}:{l_thick}:t=fill:c={l_color}@{l_alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    l_thick=line_thickness,
                    l_color=line_color_hex,
                    l_alpha=line_color_alpha
                )
                bottom_line = (
                    "drawbox=0"
                    ":{height}-round(({height}-({width}/{ratio}))/2)"
                    ":{width}:{l_thick}:t=fill:c={l_color}@{l_alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    l_thick=line_thickness,
                    l_color=line_color_hex,
                    l_alpha=line_color_alpha
                )
                output.extend([top_line, bottom_line])

        else:
            if fill_color_alpha > 0:
                left_box = (
                    "drawbox=0:0"
                    ":round(({width}-({height}*{ratio}))/2)"
                    ":{height}"
                    ":t=fill:c={color}@{alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    color=fill_color_hex,
                    alpha=fill_color_alpha
                )

                right_box = (
                    "drawbox="
                    "{width}-round(({width}-({height}*{ratio}))/2)"
                    ":0"
                    ":round(({width}-({height}*{ratio}))/2)"
                    ":{height}"
                    ":t=fill:c={color}@{alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    color=fill_color_hex,
                    alpha=fill_color_alpha
                )
                output.extend([left_box, right_box])

            if line_color_alpha > 0 and line_thickness > 0:
                left_line = (
                    "drawbox=round(({width}-({height}*{ratio}))/2)"
                    ":0:{l_thick}:{height}:t=fill:c={l_color}@{l_alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    l_thick=line_thickness,
                    l_color=line_color_hex,
                    l_alpha=line_color_alpha
                )

                right_line = (
                    "drawbox={width}-round(({width}-({height}*{ratio}))/2)"
                    ":0:{l_thick}:{height}:t=fill:c={l_color}@{l_alpha}"
                ).format(
                    width=output_width,
                    height=output_height,
                    ratio=ratio,
                    l_thick=line_thickness,
                    l_color=line_color_hex,
                    l_alpha=line_color_alpha
                )
                output.extend([left_line, right_line])

        return output

    def rescaling_filters(self, temp_data: TempData, output_def, new_repre):
        """Prepare vieo filters based on tags in new representation.

        It is possible to add letterboxes to output video or rescale to
        different resolution.

        During this preparation "resolutionWidth" and "resolutionHeight" are
        set to new representation.
        """
        filters = []

        # if reformat input video file is already reforamted from upstream
        reformat_in_baking = (
            "reformatted" in new_repre["tags"]
            # Backwards compatibility
            or "reformated" in new_repre["tags"]
        )
        self.log.debug("reformat_in_baking: `{}`".format(reformat_in_baking))

        # NOTE Skipped using instance's resolution
        full_input_path_single_file = temp_data.full_input_path_single_file
        try:
            streams = get_ffprobe_streams(
                full_input_path_single_file, self.log
            )
        except Exception as exc:
            raise AssertionError((
                "FFprobe couldn't read information about input file: \"{}\"."
                " Error message: {}"
            ).format(full_input_path_single_file, str(exc)))

        # Try to find first stream with defined 'width' and 'height'
        # - this is to avoid order of streams where audio can be as first
        # - there may be a better way (checking `codec_type`?)
        input_width = None
        input_height = None
        output_width = None
        output_height = None
        for stream in streams:
            if "width" in stream and "height" in stream:
                input_width = int(stream["width"])
                input_height = int(stream["height"])
                break

        # Get instance data
        pixel_aspect = temp_data.pixel_aspect
        if reformat_in_baking:
            self.log.debug((
                "Using resolution from input. It is already "
                "reformatted from upstream process"
            ))
            pixel_aspect = 1
            output_width = input_width
            output_height = input_height

        # Raise exception of any stream didn't define input resolution
        if input_width is None:
            raise AssertionError((
                "FFprobe couldn't read resolution from input file: \"{}\""
            ).format(full_input_path_single_file))

        # collect source values to be potentially used in burnins later
        if "source_resolution_width" not in new_repre:
            new_repre["source_resolution_width"] = input_width
        if "source_resolution_height" not in new_repre:
            new_repre["source_resolution_height"] = input_height

        # NOTE Setting only one of `width` or `height` is not allowed
        # - settings value can't have None but has value of 0
        output_width = output_def["width"] or output_width or None
        output_height = output_def["height"] or output_height or None

        # Force to use input resolution if output resolution was not defined
        #   in settings. Resolution from instance is not used when
        #   'use_input_res' is set to 'True'.
        use_input_res = False

        # Overscan color
        overscan_color_value = "black"
        overscan_color = output_def.get("overscan_color")
        if overscan_color:
            if len(overscan_color) == 3:
                bg_red, bg_green, bg_blue = overscan_color
            else:
                # Backwards compatibility
                bg_red, bg_green, bg_blue, _ = overscan_color

            overscan_color_value = "#{0:0>2X}{1:0>2X}{2:0>2X}".format(
                bg_red, bg_green, bg_blue
            )
        self.log.debug("Overscan color: `{}`".format(overscan_color_value))

        # Scale input to have proper pixel aspect ratio
        # - scale width by the pixel aspect ratio
        scale_pixel_aspect = output_def.get("scale_pixel_aspect", True)
        if scale_pixel_aspect and pixel_aspect != 1:
            # Change input width after pixel aspect
            input_width = int(input_width * pixel_aspect)
            use_input_res = True
            filters.append((
                "scale={}x{}:flags=lanczos".format(input_width, input_height)
            ))

        # Convert overscan value video filters
        overscan_crop = output_def.get("overscan_crop")
        overscan = OverscanCrop(
            input_width, input_height, overscan_crop, overscan_color_value
        )
        overscan_crop_filters = overscan.video_filters()
        # Add overscan filters to filters if are any and modify input
        #   resolution by it's values
        if overscan_crop_filters:
            filters.extend(overscan_crop_filters)
            # Change input resolution after overscan crop
            input_width = overscan.width()
            input_height = overscan.height()
            use_input_res = True

        # Make sure input width and height is not an odd number
        input_width_is_odd = bool(input_width % 2 != 0)
        input_height_is_odd = bool(input_height % 2 != 0)
        if input_width_is_odd or input_height_is_odd:
            # Add padding to input and make sure this filter is at first place
            filters.append("pad=width=ceil(iw/2)*2:height=ceil(ih/2)*2")

            # Change input width or height as first filter will change them
            if input_width_is_odd:
                self.log.info((
                    "Converting input width from odd to even number. {} -> {}"
                ).format(input_width, input_width + 1))
                input_width += 1

            if input_height_is_odd:
                self.log.info((
                    "Converting input height from odd to even number. {} -> {}"
                ).format(input_height, input_height + 1))
                input_height += 1

        self.log.debug("pixel_aspect: `{}`".format(pixel_aspect))
        self.log.debug("input_width: `{}`".format(input_width))
        self.log.debug("input_height: `{}`".format(input_height))

        # Use instance resolution if output definition has not set it
        #   - use instance resolution only if there were not scale changes
        #       that may massivelly affect output 'use_input_res'
        if not use_input_res and output_width is None or output_height is None:
            output_width = temp_data.resolution_width
            output_height = temp_data.resolution_height

        # Use source's input resolution instance does not have set it.
        if output_width is None or output_height is None:
            self.log.debug("Using resolution from input.")
            output_width = input_width
            output_height = input_height

        output_width = int(output_width)
        output_height = int(output_height)

        # Make sure output width and height is not an odd number
        # When this can happen:
        # - if output definition has set width and height with odd number
        # - `instance.data` contain width and height with odd number
        if output_width % 2 != 0:
            self.log.warning((
                "Converting output width from odd to even number. {} -> {}"
            ).format(output_width, output_width + 1))
            output_width += 1

        if output_height % 2 != 0:
            self.log.warning((
                "Converting output height from odd to even number. {} -> {}"
            ).format(output_height, output_height + 1))
            output_height += 1

        self.log.debug(
            "Output resolution is {}x{}".format(output_width, output_height)
        )

        letter_box_def = output_def["letter_box"]
        letter_box_enabled = letter_box_def["enabled"]

        # Skip processing if resolution is same as input's and letterbox is
        # not set
        if (
            output_width == input_width
            and output_height == input_height
            and not letter_box_enabled
        ):
            self.log.debug(
                "Output resolution is same as input's"
                " and \"letter_box\" key is not set. Skipping reformat part."
            )
            new_repre["resolutionWidth"] = input_width
            new_repre["resolutionHeight"] = input_height
            return filters

        # scaling none square pixels and 1920 width
        if input_height != output_height or input_width != output_width:
            filters.extend([
                (
                    "scale={}x{}"
                    ":flags=lanczos"
                    ":force_original_aspect_ratio=decrease"
                ).format(output_width, output_height),
                "pad={}:{}:(ow-iw)/2:(oh-ih)/2:{}".format(
                    output_width, output_height,
                    overscan_color_value
                ),
                "setsar=1"
            ])

        # letter_box
        if letter_box_enabled:
            filters.extend(
                self.get_letterbox_filters(
                    letter_box_def,
                    output_width,
                    output_height
                )
            )

        new_repre["resolutionWidth"] = output_width
        new_repre["resolutionHeight"] = output_height

        return filters

    def lut_filters(self, new_repre, instance, input_args):
        """Add lut file to output ffmpeg filters."""
        filters = []
        # baking lut file application
        lut_path = instance.data.get("lutPath")
        if not lut_path or "bake-lut" not in new_repre["tags"]:
            return filters

        # Prepare path for ffmpeg argument
        lut_path = lut_path.replace("\\", "/").replace(":", "\\:")

        # Remove gamma from input arguments
        if "-gamma" in input_args:
            input_args.remove("-gamme")

        # Prepare filters
        filters.append("lut3d=file='{}'".format(lut_path))
        # QUESTION hardcoded colormatrix?
        filters.append("colormatrix=bt601:bt709")

        self.log.info("Added Lut to ffmpeg command.")

        return filters

    def families_from_instance(self, instance):
        """Returns all families of entered instance."""
        families = []
        family = instance.data.get("family")
        if family:
            families.append(family)

        for family in (instance.data.get("families") or tuple()):
            if family not in families:
                families.append(family)
        return families

    def families_filter_validation(self, families, output_families_filter):
        """Determines if entered families intersect with families filters.

        All family values are lowered to avoid unexpected results.
        """

        families_filter_lower = set(family.lower() for family in
                                    output_families_filter
                                    # Exclude empty filter values
                                    if family)
        if not families_filter_lower:
            return True
        return any(family.lower() in families_filter_lower
                   for family in families)

    def filter_output_defs(self, profile, product_name, families):
        """Return outputs matching input instance families.

        Output definitions without families filter are marked as valid.

        Args:
            profile (dict): Profile from presets matching current context.
            families (list): All families of current instance.
            product_name (str): Product name.

        Returns:
            dict[str, Any]: Containing all output definitions matching entered
                families.
        """
        filtered_outputs = {}
        outputs = profile.get("outputs")
        if not outputs:
            return filtered_outputs

        for output_def in outputs:
            filename_suffix = output_def["name"]
            output_filters = output_def.get("filter")
            # If no filter on output preset, skip filtering and add output
            # profile for farther processing
            if not output_filters:
                filtered_outputs[filename_suffix] = output_def
                continue

            families_filters = output_filters.get("families")
            if not self.families_filter_validation(families, families_filters):
                continue

            # Subsets name filters
            product_name_filters = [
                name_filter
                for name_filter in output_filters.get("product_names", [])
                # Skip empty strings
                if name_filter
            ]
            if product_name and product_name_filters:
                match = False
                for product_name_filter in product_name_filters:
                    compiled = re.compile(product_name_filter)
                    if compiled.search(product_name):
                        match = True
                        break

                if not match:
                    continue

            filtered_outputs[filename_suffix] = output_def

        return filtered_outputs

    def filter_outputs_by_custom_tags(self, outputs, custom_tags):
        """Filter output definitions by entered representation custom_tags.

        Output definitions without custom_tags filter are marked as invalid,
        only in case representation is having any custom_tags defined.

        Args:
            outputs (list): Contain list of output definitions from presets.
            custom_tags (list): Custom Tags of processed representation.

        Returns:
            list: Containing all output definitions matching entered tags.
        """

        filtered_outputs = []
        repre_c_tags_low = [tag.lower() for tag in (custom_tags or [])]
        for output_def in outputs:
            tag_filters = output_def.get("filter", {}).get("custom_tags")

            if not custom_tags and not tag_filters:
                # Definition is valid if both tags are empty
                valid = True

            elif not custom_tags or not tag_filters:
                # Invalid if one is empty
                valid = False

            else:
                # Check if output definition tags are in representation tags
                valid = False
                # lower all filter tags
                tag_filters_low = [tag.lower() for tag in tag_filters]
                # check if any repre tag is not in filter tags
                for tag in repre_c_tags_low:
                    if tag in tag_filters_low:
                        valid = True
                        break

            if valid:
                filtered_outputs.append(output_def)

        self.log.debug("__ filtered_outputs: {}".format(
            [_o["filename_suffix"] for _o in filtered_outputs]
        ))

        return filtered_outputs

    def add_video_filter_args(self, args, inserting_arg):
        """
        Fixing video filter arguments to be one long string

        Args:
            args (list): list of string arguments
            inserting_arg (str): string argument we want to add
                                 (without flag `-vf`)

        Returns:
            str: long joined argument to be added back to list of arguments

        """
        # find all video format settings
        vf_settings = [p for p in args
                       for v in ["-filter:v", "-vf"]
                       if v in p]
        self.log.debug("_ vf_settings: `{}`".format(vf_settings))

        # remove them from output args list
        for p in vf_settings:
            self.log.debug("_ remove p: `{}`".format(p))
            args.remove(p)
            self.log.debug("_ args: `{}`".format(args))

        # strip them from all flags
        vf_fixed = [p.replace("-vf ", "").replace("-filter:v ", "")
                    for p in vf_settings]

        self.log.debug("_ vf_fixed: `{}`".format(vf_fixed))
        vf_fixed.insert(0, inserting_arg)
        self.log.debug("_ vf_fixed: `{}`".format(vf_fixed))
        # create new video filter setting
        vf_back = "-vf " + ",".join(vf_fixed)

        return vf_back

add_video_filter_args(args, inserting_arg)

Fixing video filter arguments to be one long string

Parameters:

Name Type Description Default
args list

list of string arguments

required
inserting_arg str

string argument we want to add (without flag -vf)

required

Returns:

Name Type Description
str

long joined argument to be added back to list of arguments

Source code in client/ayon_core/plugins/publish/extract_review.py
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
def add_video_filter_args(self, args, inserting_arg):
    """
    Fixing video filter arguments to be one long string

    Args:
        args (list): list of string arguments
        inserting_arg (str): string argument we want to add
                             (without flag `-vf`)

    Returns:
        str: long joined argument to be added back to list of arguments

    """
    # find all video format settings
    vf_settings = [p for p in args
                   for v in ["-filter:v", "-vf"]
                   if v in p]
    self.log.debug("_ vf_settings: `{}`".format(vf_settings))

    # remove them from output args list
    for p in vf_settings:
        self.log.debug("_ remove p: `{}`".format(p))
        args.remove(p)
        self.log.debug("_ args: `{}`".format(args))

    # strip them from all flags
    vf_fixed = [p.replace("-vf ", "").replace("-filter:v ", "")
                for p in vf_settings]

    self.log.debug("_ vf_fixed: `{}`".format(vf_fixed))
    vf_fixed.insert(0, inserting_arg)
    self.log.debug("_ vf_fixed: `{}`".format(vf_fixed))
    # create new video filter setting
    vf_back = "-vf " + ",".join(vf_fixed)

    return vf_back

audio_args(instance, temp_data, duration_seconds)

Prepares FFMpeg arguments for audio inputs.

Source code in client/ayon_core/plugins/publish/extract_review.py
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
def audio_args(self, instance, temp_data: TempData, duration_seconds):
    """Prepares FFMpeg arguments for audio inputs."""
    audio_in_args = []
    audio_filters = []
    audio_out_args = []
    audio_inputs = instance.data.get("audio")
    if not audio_inputs:
        return audio_in_args, audio_filters, audio_out_args

    for audio in audio_inputs:
        offset_seconds = 0
        if offset_seconds > 0:
            audio_in_args.append(
                "-ss {}".format(offset_seconds)
            )

        elif offset_seconds < 0:
            audio_in_args.append(
                "-itsoffset {}".format(abs(offset_seconds))
            )

        # Audio duration is offset from `-ss`
        audio_duration = duration_seconds + offset_seconds

        # Set audio duration
        audio_in_args.append("-to {:0.10f}".format(audio_duration))

        # Ignore video data from audio input
        audio_in_args.append("-vn")

        # Add audio input path
        audio_in_args.append("-i {}".format(
            path_to_subprocess_arg(audio["filename"])
        ))

    # NOTE: These were changed from input to output arguments.
    # NOTE: value in "-ac" was hardcoded to 2, changed to audio inputs len.
    # Need to merge audio if there are more than 1 input.
    if len(audio_inputs) > 1:
        audio_out_args.append("-filter_complex amerge")
        audio_out_args.append("-ac {}".format(len(audio_inputs)))

    return audio_in_args, audio_filters, audio_out_args

families_filter_validation(families, output_families_filter)

Determines if entered families intersect with families filters.

All family values are lowered to avoid unexpected results.

Source code in client/ayon_core/plugins/publish/extract_review.py
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
def families_filter_validation(self, families, output_families_filter):
    """Determines if entered families intersect with families filters.

    All family values are lowered to avoid unexpected results.
    """

    families_filter_lower = set(family.lower() for family in
                                output_families_filter
                                # Exclude empty filter values
                                if family)
    if not families_filter_lower:
        return True
    return any(family.lower() in families_filter_lower
               for family in families)

families_from_instance(instance)

Returns all families of entered instance.

Source code in client/ayon_core/plugins/publish/extract_review.py
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
def families_from_instance(self, instance):
    """Returns all families of entered instance."""
    families = []
    family = instance.data.get("family")
    if family:
        families.append(family)

    for family in (instance.data.get("families") or tuple()):
        if family not in families:
            families.append(family)
    return families

ffmpeg_full_args(input_args, video_filters, audio_filters, output_args)

Post processing of collected FFmpeg arguments.

Just verify that output arguments does not contain video or audio filters which may cause issues because of duplicated argument entry. Filters found in output arguments are moved to list they belong to.

Parameters:

Name Type Description Default
input_args list

All collected ffmpeg arguments with inputs.

required
video_filters list

All collected video filters.

required
audio_filters list

All collected audio filters.

required
output_args list

All collected ffmpeg output arguments with output filepath.

required

Returns:

Name Type Description
list

Containing all arguments ready to run in subprocess.

Source code in client/ayon_core/plugins/publish/extract_review.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def ffmpeg_full_args(
    self, input_args, video_filters, audio_filters, output_args
):
    """Post processing of collected FFmpeg arguments.

    Just verify that output arguments does not contain video or audio
    filters which may cause issues because of duplicated argument entry.
    Filters found in output arguments are moved to list they belong to.

    Args:
        input_args (list): All collected ffmpeg arguments with inputs.
        video_filters (list): All collected video filters.
        audio_filters (list): All collected audio filters.
        output_args (list): All collected ffmpeg output arguments with
            output filepath.

    Returns:
        list: Containing all arguments ready to run in subprocess.
    """
    output_args = self.split_ffmpeg_args(output_args)

    video_args_dentifiers = ["-vf", "-filter:v"]
    audio_args_dentifiers = ["-af", "-filter:a"]
    for arg in tuple(output_args):
        for identifier in video_args_dentifiers:
            if arg.startswith("{} ".format(identifier)):
                output_args.remove(arg)
                arg = arg.replace(identifier, "").strip()
                video_filters.append(arg)

        for identifier in audio_args_dentifiers:
            if arg.startswith("{} ".format(identifier)):
                output_args.remove(arg)
                arg = arg.replace(identifier, "").strip()
                audio_filters.append(arg)

    all_args = [
        subprocess.list2cmdline(get_ffmpeg_tool_args("ffmpeg"))
    ]
    all_args.extend(input_args)
    if video_filters:
        all_args.append("-filter:v")
        all_args.append("\"{}\"".format(",".join(video_filters)))

    if audio_filters:
        all_args.append("-filter:a")
        all_args.append("\"{}\"".format(",".join(audio_filters)))

    all_args.extend(output_args)

    return all_args

fill_sequence_gaps_from_existing(collection, staging_dir, start_frame, end_frame)

Fill missing files in sequence by duplicating existing ones.

This will take nearest frame file and copy it with so as to fill gaps in sequence. Last existing file there is is used to for the hole ahead.

Parameters:

Name Type Description Default
staging_dir str

Path to staging directory.

required
start_frame int

Sequence start (no matter what files are there)

required
end_frame int

Sequence end (no matter what files are there)

required

Returns:

Type Description
dict[int, str]

dict[int, str] of added files. Those should be cleaned after work is done.

Raises:

Type Description
KnownPublishError

if more than one collection is obtained.

Source code in client/ayon_core/plugins/publish/extract_review.py
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
def fill_sequence_gaps_from_existing(
    self,
    collection,
    staging_dir: str,
    start_frame: int,
    end_frame: int
) -> dict[int, str]:
    """Fill missing files in sequence by duplicating existing ones.

    This will take nearest frame file and copy it with so as to fill
    gaps in sequence. Last existing file there is is used to for the
    hole ahead.

    Args:
        collection (clique.collection)
        staging_dir (str): Path to staging directory.
        start_frame (int): Sequence start (no matter what files are there)
        end_frame (int): Sequence end (no matter what files are there)

    Returns:
        dict[int, str] of added files. Those should be cleaned after work
            is done.

    Raises:
        KnownPublishError: if more than one collection is obtained.
    """

    # Prepare which hole is filled with what frame
    #   - the frame is filled only with already existing frames
    prev_frame = next(iter(collection.indexes))
    hole_frame_to_nearest = {}
    for frame in range(int(start_frame), int(end_frame) + 1):
        if frame in collection.indexes:
            prev_frame = frame
        else:
            # Use previous frame as source for hole
            hole_frame_to_nearest[frame] = prev_frame

    # Calculate paths
    added_files = {}
    col_format = collection.format("{head}{padding}{tail}")
    for hole_frame, src_frame in hole_frame_to_nearest.items():
        hole_fpath = os.path.join(staging_dir, col_format % hole_frame)
        src_fpath = os.path.join(staging_dir, col_format % src_frame)
        if not os.path.isfile(src_fpath):
            raise KnownPublishError(
                "Missing previously detected file: {}".format(src_fpath))

        speedcopy.copyfile(src_fpath, hole_fpath)
        added_files[hole_frame] = hole_fpath

    return added_files

fill_sequence_gaps_with_blanks(collection, staging_dir, start_frame, end_frame, resolution_width, resolution_height, extension, temp_data)

Fills missing files by blank frame.

Source code in client/ayon_core/plugins/publish/extract_review.py
1057
1058
1059
1060
1061
1062
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
def fill_sequence_gaps_with_blanks(
    self,
    collection: str,
    staging_dir: str,
    start_frame: int,
    end_frame: int,
    resolution_width: int,
    resolution_height: int,
    extension: str,
    temp_data: TempData
) -> Optional[dict[int, str]]:
    """Fills missing files by blank frame."""

    blank_frame_path = None

    added_files = {}

    col_format = collection.format("{head}{padding}{tail}")
    for frame in range(start_frame, end_frame + 1):
        if frame in collection.indexes:
            continue
        hole_fpath = os.path.join(staging_dir, col_format % frame)
        if blank_frame_path is None:
            blank_frame_path = self._create_blank_frame(
                staging_dir, extension, resolution_width, resolution_height
            )
            temp_data.paths_to_remove.append(blank_frame_path)
        speedcopy.copyfile(blank_frame_path, hole_fpath)
        added_files[frame] = hole_fpath

    return added_files

filter_output_defs(profile, product_name, families)

Return outputs matching input instance families.

Output definitions without families filter are marked as valid.

Parameters:

Name Type Description Default
profile dict

Profile from presets matching current context.

required
families list

All families of current instance.

required
product_name str

Product name.

required

Returns:

Type Description

dict[str, Any]: Containing all output definitions matching entered families.

Source code in client/ayon_core/plugins/publish/extract_review.py
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
def filter_output_defs(self, profile, product_name, families):
    """Return outputs matching input instance families.

    Output definitions without families filter are marked as valid.

    Args:
        profile (dict): Profile from presets matching current context.
        families (list): All families of current instance.
        product_name (str): Product name.

    Returns:
        dict[str, Any]: Containing all output definitions matching entered
            families.
    """
    filtered_outputs = {}
    outputs = profile.get("outputs")
    if not outputs:
        return filtered_outputs

    for output_def in outputs:
        filename_suffix = output_def["name"]
        output_filters = output_def.get("filter")
        # If no filter on output preset, skip filtering and add output
        # profile for farther processing
        if not output_filters:
            filtered_outputs[filename_suffix] = output_def
            continue

        families_filters = output_filters.get("families")
        if not self.families_filter_validation(families, families_filters):
            continue

        # Subsets name filters
        product_name_filters = [
            name_filter
            for name_filter in output_filters.get("product_names", [])
            # Skip empty strings
            if name_filter
        ]
        if product_name and product_name_filters:
            match = False
            for product_name_filter in product_name_filters:
                compiled = re.compile(product_name_filter)
                if compiled.search(product_name):
                    match = True
                    break

            if not match:
                continue

        filtered_outputs[filename_suffix] = output_def

    return filtered_outputs

filter_outputs_by_custom_tags(outputs, custom_tags)

Filter output definitions by entered representation custom_tags.

Output definitions without custom_tags filter are marked as invalid, only in case representation is having any custom_tags defined.

Parameters:

Name Type Description Default
outputs list

Contain list of output definitions from presets.

required
custom_tags list

Custom Tags of processed representation.

required

Returns:

Name Type Description
list

Containing all output definitions matching entered tags.

Source code in client/ayon_core/plugins/publish/extract_review.py
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
def filter_outputs_by_custom_tags(self, outputs, custom_tags):
    """Filter output definitions by entered representation custom_tags.

    Output definitions without custom_tags filter are marked as invalid,
    only in case representation is having any custom_tags defined.

    Args:
        outputs (list): Contain list of output definitions from presets.
        custom_tags (list): Custom Tags of processed representation.

    Returns:
        list: Containing all output definitions matching entered tags.
    """

    filtered_outputs = []
    repre_c_tags_low = [tag.lower() for tag in (custom_tags or [])]
    for output_def in outputs:
        tag_filters = output_def.get("filter", {}).get("custom_tags")

        if not custom_tags and not tag_filters:
            # Definition is valid if both tags are empty
            valid = True

        elif not custom_tags or not tag_filters:
            # Invalid if one is empty
            valid = False

        else:
            # Check if output definition tags are in representation tags
            valid = False
            # lower all filter tags
            tag_filters_low = [tag.lower() for tag in tag_filters]
            # check if any repre tag is not in filter tags
            for tag in repre_c_tags_low:
                if tag in tag_filters_low:
                    valid = True
                    break

        if valid:
            filtered_outputs.append(output_def)

    self.log.debug("__ filtered_outputs: {}".format(
        [_o["filename_suffix"] for _o in filtered_outputs]
    ))

    return filtered_outputs

input_is_sequence(repre)

Deduce from representation data if input is sequence.

Source code in client/ayon_core/plugins/publish/extract_review.py
637
638
639
640
641
642
643
644
def input_is_sequence(self, repre):
    """Deduce from representation data if input is sequence."""
    # TODO GLOBAL ISSUE - Find better way how to find out if input
    #  is sequence. Issues (in theory):
    #   - there may be multiple files ant not be sequence
    #   - remainders are not checked at all
    #   - there can be more than one collection
    return isinstance(repre["files"], (list, tuple))

input_output_paths(new_repre, output_def, temp_data)

Deduce input nad output file paths based on entered data.

Input may be sequence of images, video file or single image file and same can be said about output, this method helps to find out what their paths are.

It is validated that output directory exist and creates if not.

During process are set "files", "stagingDir", "ext" and "sequence_file" (if output is sequence) keys to new representation.

Source code in client/ayon_core/plugins/publish/extract_review.py
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
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
def input_output_paths(self, new_repre, output_def, temp_data: TempData):
    """Deduce input nad output file paths based on entered data.

    Input may be sequence of images, video file or single image file and
    same can be said about output, this method helps to find out what
    their paths are.

    It is validated that output directory exist and creates if not.

    During process are set "files", "stagingDir", "ext" and
    "sequence_file" (if output is sequence) keys to new representation.
    """

    repre = temp_data.origin_repre
    src_staging_dir = repre["stagingDir"]
    dst_staging_dir = new_repre["stagingDir"]

    if temp_data.input_is_sequence:
        collections = clique.assemble(repre["files"])[0]
        full_input_path = os.path.join(
            src_staging_dir,
            collections[0].format("{head}{padding}{tail}")
        )

        filename = collections[0].format("{head}")
        if filename.endswith("."):
            filename = filename[:-1]

        # Make sure to have full path to one input file
        full_input_path_single_file = os.path.join(
            src_staging_dir, repre["files"][0]
        )

    else:
        full_input_path = os.path.join(
            src_staging_dir, repre["files"]
        )
        filename = os.path.splitext(repre["files"])[0]

        # Make sure to have full path to one input file
        full_input_path_single_file = full_input_path

    filled_files = temp_data.filled_files
    if filled_files:
        first_frame, first_file = next(iter(filled_files.items()))
        if first_file < full_input_path_single_file:
            self.log.warning(f"Using filled frame: '{first_file}'")
            full_input_path_single_file = first_file
            temp_data.first_sequence_frame = first_frame

    filename_suffix = output_def["filename_suffix"]

    output_ext = output_def.get("ext")
    # Use input extension if output definition do not specify it
    if output_ext is None:
        output_ext = os.path.splitext(full_input_path)[1]

    # TODO Define if extension should have dot or not
    if output_ext.startswith("."):
        output_ext = output_ext[1:]

    output_ext = output_ext.lower()

    # Store extension to representation
    new_repre["ext"] = output_ext

    self.log.debug("New representation ext: `{}`".format(output_ext))

    # Output is image file sequence with frames
    output_ext_is_image = bool(output_ext in self.image_exts)
    output_is_sequence = bool(
        output_ext_is_image
        and "sequence" in output_def["tags"]
    )
    if output_is_sequence:
        new_repre_files = []
        frame_start = temp_data.output_frame_start
        frame_end = temp_data.output_frame_end

        filename_base = "{}_{}".format(filename, filename_suffix)
        # Temporary template for frame filling. Example output:
        # "basename.%04d.exr" when `frame_end` == 1001
        repr_file = "{}.%{:0>2}d.{}".format(
            filename_base, len(str(frame_end)), output_ext
        )

        for frame in range(frame_start, frame_end + 1):
            new_repre_files.append(repr_file % frame)

        new_repre["sequence_file"] = repr_file
        full_output_path = os.path.join(
            dst_staging_dir, filename_base, repr_file
        )

    else:
        repr_file = "{}_{}.{}".format(
            filename, filename_suffix, output_ext
        )
        full_output_path = os.path.join(dst_staging_dir, repr_file)
        new_repre_files = repr_file

    # Store files to representation
    new_repre["files"] = new_repre_files

    # Make sure stagingDire exists
    dst_staging_dir = os.path.normpath(os.path.dirname(full_output_path))
    if not os.path.exists(dst_staging_dir):
        self.log.debug("Creating dir: {}".format(dst_staging_dir))
        os.makedirs(dst_staging_dir)

    # Store stagingDir to representation
    new_repre["stagingDir"] = dst_staging_dir

    # Store paths to temp data
    temp_data.full_input_path = full_input_path
    temp_data.full_input_path_single_file = full_input_path_single_file
    temp_data.full_output_path = full_output_path

    # Store information about output
    temp_data.output_ext_is_image = output_ext_is_image
    temp_data.output_is_sequence = output_is_sequence

    self.log.debug("Input path {}".format(full_input_path))
    self.log.debug("Output path {}".format(full_output_path))

lut_filters(new_repre, instance, input_args)

Add lut file to output ffmpeg filters.

Source code in client/ayon_core/plugins/publish/extract_review.py
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
def lut_filters(self, new_repre, instance, input_args):
    """Add lut file to output ffmpeg filters."""
    filters = []
    # baking lut file application
    lut_path = instance.data.get("lutPath")
    if not lut_path or "bake-lut" not in new_repre["tags"]:
        return filters

    # Prepare path for ffmpeg argument
    lut_path = lut_path.replace("\\", "/").replace(":", "\\:")

    # Remove gamma from input arguments
    if "-gamma" in input_args:
        input_args.remove("-gamme")

    # Prepare filters
    filters.append("lut3d=file='{}'".format(lut_path))
    # QUESTION hardcoded colormatrix?
    filters.append("colormatrix=bt601:bt709")

    self.log.info("Added Lut to ffmpeg command.")

    return filters

prepare_temp_data(instance, repre, output_def)

Prepare dictionary with values used across extractor's process.

All data are collected from instance, context, origin representation and output definition.

There are few required keys in Instance data: "frameStart", "frameEnd" and "fps".

Parameters:

Name Type Description Default
instance Instance

Currently processed instance.

required
repre dict

Representation from which new representation was copied.

required
output_def dict

Definition of output of this plugin.

required

Returns:

Name Type Description
TempData TempData

All data which are used across methods during process. Their values should not change during process but new keys with values may be added.

Source code in client/ayon_core/plugins/publish/extract_review.py
646
647
648
649
650
651
652
653
654
655
656
657
658
659
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
def prepare_temp_data(self, instance, repre, output_def) -> TempData:
    """Prepare dictionary with values used across extractor's process.

    All data are collected from instance, context, origin representation
    and output definition.

    There are few required keys in Instance data: "frameStart", "frameEnd"
    and "fps".

    Args:
        instance (Instance): Currently processed instance.
        repre (dict): Representation from which new representation was
            copied.
        output_def (dict): Definition of output of this plugin.

    Returns:
        TempData: All data which are used across methods during process.
            Their values should not change during process but new keys
            with values may be added.
    """

    frame_start = instance.data["frameStart"]
    frame_end = instance.data["frameEnd"]

    # Try to get handles from instance
    handle_start = instance.data.get("handleStart")
    handle_end = instance.data.get("handleEnd")
    # If even one of handle values is not set on instance use
    # handles from context
    if handle_start is None or handle_end is None:
        handle_start = instance.context.data["handleStart"]
        handle_end = instance.context.data["handleEnd"]

    frame_start_handle = frame_start - handle_start
    frame_end_handle = frame_end + handle_end

    # Change output frames when output should be without handles
    without_handles = bool("no-handles" in output_def["tags"])
    if without_handles:
        output_frame_start = frame_start
        output_frame_end = frame_end
    else:
        output_frame_start = frame_start_handle
        output_frame_end = frame_end_handle

    handles_are_set = handle_start > 0 or handle_end > 0

    with_audio = True
    if (
        # Check if has `no-audio` tag
        "no-audio" in output_def["tags"]
        # Check if instance has ny audio in data
        or not instance.data.get("audio")
    ):
        with_audio = False

    input_is_sequence = self.input_is_sequence(repre)
    input_allow_bg = False
    first_sequence_frame = None

    if input_is_sequence and repre["files"]:
        # Calculate first frame that should be used
        cols, _ = clique.assemble(repre["files"])
        input_frames = list(sorted(cols[0].indexes))
        first_sequence_frame = input_frames[0]
        # WARNING: This is an issue as we don't know if first frame
        #   is with or without handles!
        # - handle start is added but how do not know if we should
        output_duration = (output_frame_end - output_frame_start) + 1
        if (
            without_handles
            and len(input_frames) - handle_start >= output_duration
        ):
            first_sequence_frame += handle_start

        ext = os.path.splitext(repre["files"][0])[1].replace(".", "")
        if ext.lower() in self.alpha_exts:
            input_allow_bg = True
    else:
        ext = os.path.splitext(repre["files"])[1].replace(".", "")

    return TempData(
        fps=float(instance.data["fps"]),
        frame_start=frame_start,
        frame_end=frame_end,
        handle_start=handle_start,
        handle_end=handle_end,
        frame_start_handle=frame_start_handle,
        frame_end_handle=frame_end_handle,
        output_frame_start=int(output_frame_start),
        output_frame_end=int(output_frame_end),
        pixel_aspect=instance.data.get("pixelAspect", 1),
        resolution_width=instance.data.get("resolutionWidth"),
        resolution_height=instance.data.get("resolutionHeight"),
        origin_repre=repre,
        input_is_sequence=input_is_sequence,
        first_sequence_frame=first_sequence_frame,
        input_allow_bg=input_allow_bg,
        with_audio=with_audio,
        without_handles=without_handles,
        handles_are_set=handles_are_set,
        input_ext=ext,
        explicit_input_paths=[],  # absolute paths to rendered files
        paths_to_remove=[]
    )

rescaling_filters(temp_data, output_def, new_repre)

Prepare vieo filters based on tags in new representation.

It is possible to add letterboxes to output video or rescale to different resolution.

During this preparation "resolutionWidth" and "resolutionHeight" are set to new representation.

Source code in client/ayon_core/plugins/publish/extract_review.py
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
def rescaling_filters(self, temp_data: TempData, output_def, new_repre):
    """Prepare vieo filters based on tags in new representation.

    It is possible to add letterboxes to output video or rescale to
    different resolution.

    During this preparation "resolutionWidth" and "resolutionHeight" are
    set to new representation.
    """
    filters = []

    # if reformat input video file is already reforamted from upstream
    reformat_in_baking = (
        "reformatted" in new_repre["tags"]
        # Backwards compatibility
        or "reformated" in new_repre["tags"]
    )
    self.log.debug("reformat_in_baking: `{}`".format(reformat_in_baking))

    # NOTE Skipped using instance's resolution
    full_input_path_single_file = temp_data.full_input_path_single_file
    try:
        streams = get_ffprobe_streams(
            full_input_path_single_file, self.log
        )
    except Exception as exc:
        raise AssertionError((
            "FFprobe couldn't read information about input file: \"{}\"."
            " Error message: {}"
        ).format(full_input_path_single_file, str(exc)))

    # Try to find first stream with defined 'width' and 'height'
    # - this is to avoid order of streams where audio can be as first
    # - there may be a better way (checking `codec_type`?)
    input_width = None
    input_height = None
    output_width = None
    output_height = None
    for stream in streams:
        if "width" in stream and "height" in stream:
            input_width = int(stream["width"])
            input_height = int(stream["height"])
            break

    # Get instance data
    pixel_aspect = temp_data.pixel_aspect
    if reformat_in_baking:
        self.log.debug((
            "Using resolution from input. It is already "
            "reformatted from upstream process"
        ))
        pixel_aspect = 1
        output_width = input_width
        output_height = input_height

    # Raise exception of any stream didn't define input resolution
    if input_width is None:
        raise AssertionError((
            "FFprobe couldn't read resolution from input file: \"{}\""
        ).format(full_input_path_single_file))

    # collect source values to be potentially used in burnins later
    if "source_resolution_width" not in new_repre:
        new_repre["source_resolution_width"] = input_width
    if "source_resolution_height" not in new_repre:
        new_repre["source_resolution_height"] = input_height

    # NOTE Setting only one of `width` or `height` is not allowed
    # - settings value can't have None but has value of 0
    output_width = output_def["width"] or output_width or None
    output_height = output_def["height"] or output_height or None

    # Force to use input resolution if output resolution was not defined
    #   in settings. Resolution from instance is not used when
    #   'use_input_res' is set to 'True'.
    use_input_res = False

    # Overscan color
    overscan_color_value = "black"
    overscan_color = output_def.get("overscan_color")
    if overscan_color:
        if len(overscan_color) == 3:
            bg_red, bg_green, bg_blue = overscan_color
        else:
            # Backwards compatibility
            bg_red, bg_green, bg_blue, _ = overscan_color

        overscan_color_value = "#{0:0>2X}{1:0>2X}{2:0>2X}".format(
            bg_red, bg_green, bg_blue
        )
    self.log.debug("Overscan color: `{}`".format(overscan_color_value))

    # Scale input to have proper pixel aspect ratio
    # - scale width by the pixel aspect ratio
    scale_pixel_aspect = output_def.get("scale_pixel_aspect", True)
    if scale_pixel_aspect and pixel_aspect != 1:
        # Change input width after pixel aspect
        input_width = int(input_width * pixel_aspect)
        use_input_res = True
        filters.append((
            "scale={}x{}:flags=lanczos".format(input_width, input_height)
        ))

    # Convert overscan value video filters
    overscan_crop = output_def.get("overscan_crop")
    overscan = OverscanCrop(
        input_width, input_height, overscan_crop, overscan_color_value
    )
    overscan_crop_filters = overscan.video_filters()
    # Add overscan filters to filters if are any and modify input
    #   resolution by it's values
    if overscan_crop_filters:
        filters.extend(overscan_crop_filters)
        # Change input resolution after overscan crop
        input_width = overscan.width()
        input_height = overscan.height()
        use_input_res = True

    # Make sure input width and height is not an odd number
    input_width_is_odd = bool(input_width % 2 != 0)
    input_height_is_odd = bool(input_height % 2 != 0)
    if input_width_is_odd or input_height_is_odd:
        # Add padding to input and make sure this filter is at first place
        filters.append("pad=width=ceil(iw/2)*2:height=ceil(ih/2)*2")

        # Change input width or height as first filter will change them
        if input_width_is_odd:
            self.log.info((
                "Converting input width from odd to even number. {} -> {}"
            ).format(input_width, input_width + 1))
            input_width += 1

        if input_height_is_odd:
            self.log.info((
                "Converting input height from odd to even number. {} -> {}"
            ).format(input_height, input_height + 1))
            input_height += 1

    self.log.debug("pixel_aspect: `{}`".format(pixel_aspect))
    self.log.debug("input_width: `{}`".format(input_width))
    self.log.debug("input_height: `{}`".format(input_height))

    # Use instance resolution if output definition has not set it
    #   - use instance resolution only if there were not scale changes
    #       that may massivelly affect output 'use_input_res'
    if not use_input_res and output_width is None or output_height is None:
        output_width = temp_data.resolution_width
        output_height = temp_data.resolution_height

    # Use source's input resolution instance does not have set it.
    if output_width is None or output_height is None:
        self.log.debug("Using resolution from input.")
        output_width = input_width
        output_height = input_height

    output_width = int(output_width)
    output_height = int(output_height)

    # Make sure output width and height is not an odd number
    # When this can happen:
    # - if output definition has set width and height with odd number
    # - `instance.data` contain width and height with odd number
    if output_width % 2 != 0:
        self.log.warning((
            "Converting output width from odd to even number. {} -> {}"
        ).format(output_width, output_width + 1))
        output_width += 1

    if output_height % 2 != 0:
        self.log.warning((
            "Converting output height from odd to even number. {} -> {}"
        ).format(output_height, output_height + 1))
        output_height += 1

    self.log.debug(
        "Output resolution is {}x{}".format(output_width, output_height)
    )

    letter_box_def = output_def["letter_box"]
    letter_box_enabled = letter_box_def["enabled"]

    # Skip processing if resolution is same as input's and letterbox is
    # not set
    if (
        output_width == input_width
        and output_height == input_height
        and not letter_box_enabled
    ):
        self.log.debug(
            "Output resolution is same as input's"
            " and \"letter_box\" key is not set. Skipping reformat part."
        )
        new_repre["resolutionWidth"] = input_width
        new_repre["resolutionHeight"] = input_height
        return filters

    # scaling none square pixels and 1920 width
    if input_height != output_height or input_width != output_width:
        filters.extend([
            (
                "scale={}x{}"
                ":flags=lanczos"
                ":force_original_aspect_ratio=decrease"
            ).format(output_width, output_height),
            "pad={}:{}:(ow-iw)/2:(oh-ih)/2:{}".format(
                output_width, output_height,
                overscan_color_value
            ),
            "setsar=1"
        ])

    # letter_box
    if letter_box_enabled:
        filters.extend(
            self.get_letterbox_filters(
                letter_box_def,
                output_width,
                output_height
            )
        )

    new_repre["resolutionWidth"] = output_width
    new_repre["resolutionHeight"] = output_height

    return filters

split_ffmpeg_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.

Source code in client/ayon_core/plugins/publish/extract_review.py
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def split_ffmpeg_args(self, 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.
    """
    splitted_args = []
    for arg in in_args:
        sub_args = arg.split(" -")
        if len(sub_args) == 1:
            if arg and arg not in splitted_args:
                splitted_args.append(arg)
            continue

        for idx, arg in enumerate(sub_args):
            if idx != 0:
                arg = "-" + arg

            if arg and arg not in splitted_args:
                splitted_args.append(arg)
    return splitted_args

OverscanCrop

Helper class to read overscan string and calculate output resolution.

It is possible to enter single value for both width and height, or two values for width and height. Overscan string may have a few variants. Each variant define output size for input size.

Example

For input size: 2200px

String Output Description
"" 2200px Empty string does nothing.
"10%" 220px Explicit percent size.
"-10%" 1980px Relative percent size (decrease).
"+10%" 2420px Relative percent size (increase).
"-10%+" 2000px Relative percent size to output size.
"300px" 300px Explicit output size cropped or expanded.
"-300px" 1900px Relative pixel size (decrease).
"+300px" 2500px Relative pixel size (increase).
"300" 300px Value without "%" and "px" is used as has "px".

Value without sign (+/-) in is always explicit and value with sign is relative. Output size for "200px" and "+200px" are not the same. Values "0", "0px" or "0%" are ignored.

All values that cause output resolution smaller than 1 pixel are invalid.

Value "-10%+" is a special case which says that input's resolution is bigger by 10% than expected output.

It is possible to combine these variants to define different output for width and height.

Resolution: 2000px 1000px

String Output
"100px 120px" 2100px 1120px
"-10% -200px" 1800px 800px
Source code in client/ayon_core/plugins/publish/extract_review.py
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
class OverscanCrop:
    """Helper class to read overscan string and calculate output resolution.

    It is possible to enter single value for both width and height, or
    two values for width and height. Overscan string may have a few variants.
    Each variant define output size for input size.

    ### Example
    For input size: 2200px

    | String   | Output | Description                                     |
    |----------|--------|-------------------------------------------------|
    | ""       | 2200px | Empty string does nothing.                      |
    | "10%"    | 220px  | Explicit percent size.                          |
    | "-10%"   | 1980px | Relative percent size (decrease).               |
    | "+10%"   | 2420px | Relative percent size (increase).               |
    | "-10%+"  | 2000px | Relative percent size to output size.           |
    | "300px"  | 300px  | Explicit output size cropped or expanded.       |
    | "-300px" | 1900px | Relative pixel size (decrease).                 |
    | "+300px" | 2500px | Relative pixel size (increase).                 |
    | "300"    | 300px  | Value without "%" and "px" is used as has "px". |

    Value without sign (+/-) in is always explicit and value with sign is
    relative. Output size for "200px" and "+200px" are not the same.
    Values "0", "0px" or "0%" are ignored.

    All values that cause output resolution smaller than 1 pixel are invalid.

    Value "-10%+" is a special case which says that input's resolution is
    bigger by 10% than expected output.

    It is possible to combine these variants to define different output for
    width and height.

    Resolution: 2000px 1000px

    | String        | Output        |
    |---------------|---------------|
    | "100px 120px" | 2100px 1120px |
    | "-10% -200px" | 1800px 800px  |
    """

    item_regex = re.compile(r"([\+\-])?([0-9]+)(.+)?")
    relative_source_regex = re.compile(r"%([\+\-])")

    def __init__(
        self, input_width, input_height, string_value, overscan_color=None
    ):
        # Make sure that is not None
        string_value = string_value or ""

        self.input_width = input_width
        self.input_height = input_height
        self.overscan_color = overscan_color

        width, height = self._convert_string_to_values(string_value)
        self._width_value = width
        self._height_value = height

        self._string_value = string_value

    def __str__(self):
        return "{}".format(self._string_value)

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

    def width(self):
        """Calculated width."""
        return self._width_value.size_for(self.input_width)

    def height(self):
        """Calculated height."""
        return self._height_value.size_for(self.input_height)

    def video_filters(self):
        """FFmpeg video filters to achieve expected result.

        Filter may be empty, use "crop" filter, "pad" filter or combination of
        "crop" and "pad".

        Returns:
            list: FFmpeg video filters.
        """
        # crop=width:height:x:y - explicit start x, y position
        # crop=width:height     - x, y are related to center by width/height
        # pad=width:height:x:y  - explicit start x, y position
        # pad=width:height      - x, y are set to 0 by default

        width = self.width()
        height = self.height()

        output = []
        if self.input_width == width and self.input_height == height:
            return output

        # Make sure resolution has odd numbers
        if width % 2 == 1:
            width -= 1

        if height % 2 == 1:
            height -= 1

        if width <= self.input_width and height <= self.input_height:
            output.append("crop={}:{}".format(width, height))

        elif width >= self.input_width and height >= self.input_height:
            output.append(
                "pad={}:{}:(iw-ow)/2:(ih-oh)/2:{}".format(
                    width, height, self.overscan_color
                )
            )

        elif width > self.input_width and height < self.input_height:
            output.append("crop=iw:{}".format(height))
            output.append("pad={}:ih:(iw-ow)/2:(ih-oh)/2:{}".format(
                width, self.overscan_color
            ))

        elif width < self.input_width and height > self.input_height:
            output.append("crop={}:ih".format(width))
            output.append("pad=iw:{}:(iw-ow)/2:(ih-oh)/2:{}".format(
                height, self.overscan_color
            ))

        return output

    def _convert_string_to_values(self, orig_string_value):
        string_value = orig_string_value.strip().lower()
        if not string_value:
            return [PixValueRelative(0), PixValueRelative(0)]

        # Replace "px" (and spaces before) with single space
        string_value = re.sub(r"([ ]+)?px", " ", string_value)
        string_value = re.sub(r"([ ]+)%", "%", string_value)
        # Make sure +/- sign at the beginning of string is next to number
        string_value = re.sub(r"^([\+\-])[ ]+", r"\g<1>", string_value)
        # Make sure +/- sign in the middle has zero spaces before number under
        #   which belongs
        string_value = re.sub(
            r"[ ]([\+\-])[ ]+([0-9])",
            r" \g<1>\g<2>",
            string_value
        )
        string_parts = [
            part
            for part in string_value.split(" ")
            if part
        ]

        error_msg = "Invalid string for rescaling \"{}\"".format(
            orig_string_value
        )
        if 1 > len(string_parts) > 2:
            raise ValueError(error_msg)

        output = []
        for item in string_parts:
            groups = self.item_regex.findall(item)
            if not groups:
                raise ValueError(error_msg)

            relative_sign, value, ending = groups[0]
            if not relative_sign:
                if not ending:
                    output.append(PixValueExplicit(value))
                else:
                    output.append(PercentValueExplicit(value))
            else:
                source_sign_group = self.relative_source_regex.findall(ending)
                if not ending:
                    output.append(PixValueRelative(int(relative_sign + value)))

                elif source_sign_group:
                    source_sign = source_sign_group[0]
                    output.append(PercentValueRelativeSource(
                        float(relative_sign + value), source_sign
                    ))
                else:
                    output.append(
                        PercentValueRelative(float(relative_sign + value))
                    )

        if len(output) == 1:
            width = output.pop(0)
            height = width.copy()
        else:
            width, height = output

        return width, height

height()

Calculated height.

Source code in client/ayon_core/plugins/publish/extract_review.py
2079
2080
2081
def height(self):
    """Calculated height."""
    return self._height_value.size_for(self.input_height)

video_filters()

FFmpeg video filters to achieve expected result.

Filter may be empty, use "crop" filter, "pad" filter or combination of "crop" and "pad".

Returns:

Name Type Description
list

FFmpeg video filters.

Source code in client/ayon_core/plugins/publish/extract_review.py
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
def video_filters(self):
    """FFmpeg video filters to achieve expected result.

    Filter may be empty, use "crop" filter, "pad" filter or combination of
    "crop" and "pad".

    Returns:
        list: FFmpeg video filters.
    """
    # crop=width:height:x:y - explicit start x, y position
    # crop=width:height     - x, y are related to center by width/height
    # pad=width:height:x:y  - explicit start x, y position
    # pad=width:height      - x, y are set to 0 by default

    width = self.width()
    height = self.height()

    output = []
    if self.input_width == width and self.input_height == height:
        return output

    # Make sure resolution has odd numbers
    if width % 2 == 1:
        width -= 1

    if height % 2 == 1:
        height -= 1

    if width <= self.input_width and height <= self.input_height:
        output.append("crop={}:{}".format(width, height))

    elif width >= self.input_width and height >= self.input_height:
        output.append(
            "pad={}:{}:(iw-ow)/2:(ih-oh)/2:{}".format(
                width, height, self.overscan_color
            )
        )

    elif width > self.input_width and height < self.input_height:
        output.append("crop=iw:{}".format(height))
        output.append("pad={}:ih:(iw-ow)/2:(ih-oh)/2:{}".format(
            width, self.overscan_color
        ))

    elif width < self.input_width and height > self.input_height:
        output.append("crop={}:ih".format(width))
        output.append("pad=iw:{}:(iw-ow)/2:(ih-oh)/2:{}".format(
            height, self.overscan_color
        ))

    return output

width()

Calculated width.

Source code in client/ayon_core/plugins/publish/extract_review.py
2075
2076
2077
def width(self):
    """Calculated width."""
    return self._width_value.size_for(self.input_width)

TempData

Temporary data used across extractor's process.

Source code in client/ayon_core/plugins/publish/extract_review.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class TempData:
    """Temporary data used across extractor's process."""
    def __init__(
        self,
        fps: float,
        frame_start: int,
        frame_end: int,
        handle_start: int,
        handle_end: int,
        frame_start_handle: int,
        frame_end_handle: int,
        output_frame_start: int,
        output_frame_end: int,
        pixel_aspect: float,
        resolution_width: int,
        resolution_height: int,
        origin_repre: dict[str, Any],
        input_is_sequence: bool,
        first_sequence_frame: int,
        input_allow_bg: bool,
        with_audio: bool,
        without_handles: bool,
        handles_are_set: bool,
        input_ext: str,
        explicit_input_paths: list[str],
        paths_to_remove: list[str],

        # Set later
        full_output_path: str = "",
        filled_files: dict[int, str] = None,
        output_ext_is_image: bool = True,
        output_is_sequence: bool = True,
    ):
        if filled_files is None:
            filled_files = {}
        self.fps = fps
        self.frame_start = frame_start
        self.frame_end = frame_end
        self.handle_start = handle_start
        self.handle_end = handle_end
        self.frame_start_handle = frame_start_handle
        self.frame_end_handle = frame_end_handle
        self.output_frame_start = output_frame_start
        self.output_frame_end = output_frame_end
        self.pixel_aspect = pixel_aspect
        self.resolution_width = resolution_width
        self.resolution_height = resolution_height
        self.origin_repre = origin_repre
        self.input_is_sequence = input_is_sequence
        self.first_sequence_frame = first_sequence_frame
        self.input_allow_bg = input_allow_bg
        self.with_audio = with_audio
        self.without_handles = without_handles
        self.handles_are_set = handles_are_set
        self.input_ext = input_ext
        self.explicit_input_paths = explicit_input_paths
        self.paths_to_remove = paths_to_remove

        self.full_output_path = full_output_path
        self.filled_files = filled_files
        self.output_ext_is_image = output_ext_is_image
        self.output_is_sequence = output_is_sequence

frame_to_timecode(frame, fps)

Convert a frame number and FPS to editorial timecode (HH:MM:SS:FF).

Unlike ayon_core.pipeline.editorial.frames_to_timecode this does not rely on the opentimelineio package, so it can be used across hosts that do not have it available.

Parameters:

Name Type Description Default
frame int

The frame number to be converted.

required
fps float

The frames per second of the video.

required

Returns:

Name Type Description
str str

The timecode in HH:MM:SS:FF format.

Source code in client/ayon_core/plugins/publish/extract_review.py
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 frame_to_timecode(frame: int, fps: float) -> str:
    """Convert a frame number and FPS to editorial timecode (HH:MM:SS:FF).

    Unlike `ayon_core.pipeline.editorial.frames_to_timecode` this does not
    rely on the `opentimelineio` package, so it can be used across hosts that
    do not have it available.

    Args:
        frame (int): The frame number to be converted.
        fps (float): The frames per second of the video.

    Returns:
        str: The timecode in HH:MM:SS:FF format.
    """
    # Calculate total seconds
    total_seconds = frame / fps

    # Extract hours, minutes, and seconds
    hours = int(total_seconds // 3600)
    minutes = int((total_seconds % 3600) // 60)
    seconds = int(total_seconds % 60)

    # Adjust for non-integer FPS by rounding the remaining frames appropriately
    remaining_frames = round((total_seconds - int(total_seconds)) * fps)

    # Format and return the timecode
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}:{remaining_frames:02d}"