Skip to content

api

resolve api

ClipLoader

Source code in client/ayon_resolve/api/plugin.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
class ClipLoader:

    active_bin = None
    data = {}

    def __init__(self, loader_obj, context, **options):
        """ Initialize object

        Arguments:
            loader_obj (ayon_core.pipeline.load.LoaderPlugin): plugin object
            context (dict): loader plugin context
            options (dict)[optional]: possible keys:
                projectBinPath: "path/to/binItem"

        """
        self.__dict__.update(loader_obj.__dict__)
        self.context = context
        self.active_project = lib.get_current_project()

        # try to get value from options or evaluate key value for `handles`
        self.with_handles = options.get("handles") is True

        # try to get value from options or evaluate key value for `load_to`
        self.new_timeline = (
            options.get("newTimeline") or
            options.get("load_to") == "New timeline"
        )
        # try to get value from options or evaluate key value for `load_how`
        self.sequential_load = (
            options.get("sequentially") or
            options.get("load_how") == "Sequentially in order"
        )

        assert self._populate_data(), str(
            "Cannot Load selected data, look into database "
            "or call your supervisor")

        # inject asset data to representation dict
        self._get_folder_attributes()

        # add active components to class
        if self.new_timeline:
            loader_cls = loader_obj.__class__
            if loader_cls.timeline:
                # if multiselection is set then use options sequence
                self.active_timeline = loader_cls.timeline
            else:
                # create new sequence
                self.active_timeline = lib.get_new_timeline(
                    "{}_{}".format(
                        self.data["timeline_basename"],
                        str(uuid.uuid4())[:8]
                    )
                )
                loader_cls.timeline = self.active_timeline

        else:
            self.active_timeline = (
                    lib.get_current_timeline() or lib.get_new_timeline()
            )

    def _populate_data(self):
        """ Gets context and convert it to self.data
        data structure:
            {
                "name": "assetName_productName_representationName"
                "binPath": "projectBinPath",
            }
        """
        # create name
        folder_entity = self.context["folder"]
        product_name = self.context["product"]["name"]
        repre_entity = self.context["representation"]

        folder_name = folder_entity["name"]
        folder_path = folder_entity["path"]
        representation_name = repre_entity["name"]

        self.data["clip_name"] = "_".join([
            folder_name,
            product_name,
            representation_name
        ])
        self.data["versionAttributes"] = self.context["version"]["attrib"]

        self.data["timeline_basename"] = "timeline_{}_{}".format(
            product_name, representation_name)

        # solve project bin structure path
        hierarchy = "Loader{}".format(folder_path)

        self.data["binPath"] = hierarchy

        return True

    def _get_folder_attributes(self):
        """ Get all available asset data

        joint `data` key with asset.data dict into the representation

        """

        self.data["folderAttributes"] = copy.deepcopy(
            self.context["folder"]["attrib"]
        )

    def load(self, files):
        """Load clip into timeline

        Arguments:
            files (list[str]): list of files to load into timeline
        """
        # create project bin for the media to be imported into
        self.active_bin = lib.create_bin(self.data["binPath"])

        # create clip media
        media_pool_item = lib.create_media_pool_item(
            files,
            self.active_bin
        )
        _clip_property = media_pool_item.GetClipProperty
        source_in = int(_clip_property("Start"))
        source_out = int(_clip_property("End"))
        source_duration = int(_clip_property("Frames"))

        # Trim clip start if slate is present
        if "slate" in self.data["versionAttributes"]["families"]:
            source_in += 1
            source_duration = source_out - source_in + 1

        if not self.with_handles:
            # Load file without the handles of the source media
            # We remove the handles from the source in and source out
            # so that the handles are excluded in the timeline

            # get version data frame data from db
            version_attributes = self.data["versionAttributes"]
            frame_start = version_attributes.get("frameStart")
            frame_end = version_attributes.get("frameEnd")

            # The version data usually stored the frame range + handles of the
            # media however certain representations may be shorter because they
            # exclude those handles intentionally. Unfortunately the
            # representation does not store that in the database currently;
            # so we should compensate for those cases. If the media is shorter
            # than the frame range specified in the database we assume it is
            # without handles and thus we do not need to remove the handles
            # from source and out
            if frame_start is not None and frame_end is not None:
                # Version has frame range data, so we can compare media length
                handle_start = version_attributes.get("handleStart", 0)
                handle_end = version_attributes.get("handleEnd", 0)
                frame_start_handle = frame_start - handle_start
                frame_end_handle = frame_end + handle_end
                database_frame_duration = int(
                    frame_end_handle - frame_start_handle + 1
                )
                if source_duration >= database_frame_duration:
                    source_in += handle_start
                    source_out -= handle_end

        # get timeline in
        timeline_start = self.active_timeline.GetStartFrame()
        if self.sequential_load:
            # set timeline start frame
            timeline_in = int(timeline_start)
        else:
            # set timeline start frame + original clip in frame
            timeline_in = int(
                timeline_start + self.data["folderAttributes"]["clipIn"])

        # make track item from source in bin as item
        timeline_item = lib.create_timeline_item(
            media_pool_item,
            self.active_timeline,
            timeline_in,
            source_in,
            source_out,
        )

        print("Loading clips: `{}`".format(self.data["clip_name"]))
        return timeline_item

    def update(self, timeline_item, files):
        # create project bin for the media to be imported into
        self.active_bin = lib.create_bin(self.data["binPath"])

        # create mediaItem in active project bin
        # create clip media
        media_pool_item = lib.create_media_pool_item(
            files,
            self.active_bin
        )
        _clip_property = media_pool_item.GetClipProperty

        # Read trimming from timeline item
        timeline_item_in = timeline_item.GetLeftOffset()
        timeline_item_len = timeline_item.GetDuration()
        timeline_item_out = timeline_item_in + timeline_item_len

        lib.swap_clips(
            timeline_item,
            media_pool_item,
            timeline_item_in,
            timeline_item_out
        )

        print("Loading clips: `{}`".format(self.data["clip_name"]))
        return timeline_item

__init__(loader_obj, context, **options)

Initialize object

Parameters:

Name Type Description Default
loader_obj LoaderPlugin

plugin object

required
context dict

loader plugin context

required
options dict)[optional]

possible keys: projectBinPath: "path/to/binItem"

{}
Source code in client/ayon_resolve/api/plugin.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
def __init__(self, loader_obj, context, **options):
    """ Initialize object

    Arguments:
        loader_obj (ayon_core.pipeline.load.LoaderPlugin): plugin object
        context (dict): loader plugin context
        options (dict)[optional]: possible keys:
            projectBinPath: "path/to/binItem"

    """
    self.__dict__.update(loader_obj.__dict__)
    self.context = context
    self.active_project = lib.get_current_project()

    # try to get value from options or evaluate key value for `handles`
    self.with_handles = options.get("handles") is True

    # try to get value from options or evaluate key value for `load_to`
    self.new_timeline = (
        options.get("newTimeline") or
        options.get("load_to") == "New timeline"
    )
    # try to get value from options or evaluate key value for `load_how`
    self.sequential_load = (
        options.get("sequentially") or
        options.get("load_how") == "Sequentially in order"
    )

    assert self._populate_data(), str(
        "Cannot Load selected data, look into database "
        "or call your supervisor")

    # inject asset data to representation dict
    self._get_folder_attributes()

    # add active components to class
    if self.new_timeline:
        loader_cls = loader_obj.__class__
        if loader_cls.timeline:
            # if multiselection is set then use options sequence
            self.active_timeline = loader_cls.timeline
        else:
            # create new sequence
            self.active_timeline = lib.get_new_timeline(
                "{}_{}".format(
                    self.data["timeline_basename"],
                    str(uuid.uuid4())[:8]
                )
            )
            loader_cls.timeline = self.active_timeline

    else:
        self.active_timeline = (
                lib.get_current_timeline() or lib.get_new_timeline()
        )

load(files)

Load clip into timeline

Parameters:

Name Type Description Default
files list[str]

list of files to load into timeline

required
Source code in client/ayon_resolve/api/plugin.py
127
128
129
130
131
132
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
def load(self, files):
    """Load clip into timeline

    Arguments:
        files (list[str]): list of files to load into timeline
    """
    # create project bin for the media to be imported into
    self.active_bin = lib.create_bin(self.data["binPath"])

    # create clip media
    media_pool_item = lib.create_media_pool_item(
        files,
        self.active_bin
    )
    _clip_property = media_pool_item.GetClipProperty
    source_in = int(_clip_property("Start"))
    source_out = int(_clip_property("End"))
    source_duration = int(_clip_property("Frames"))

    # Trim clip start if slate is present
    if "slate" in self.data["versionAttributes"]["families"]:
        source_in += 1
        source_duration = source_out - source_in + 1

    if not self.with_handles:
        # Load file without the handles of the source media
        # We remove the handles from the source in and source out
        # so that the handles are excluded in the timeline

        # get version data frame data from db
        version_attributes = self.data["versionAttributes"]
        frame_start = version_attributes.get("frameStart")
        frame_end = version_attributes.get("frameEnd")

        # The version data usually stored the frame range + handles of the
        # media however certain representations may be shorter because they
        # exclude those handles intentionally. Unfortunately the
        # representation does not store that in the database currently;
        # so we should compensate for those cases. If the media is shorter
        # than the frame range specified in the database we assume it is
        # without handles and thus we do not need to remove the handles
        # from source and out
        if frame_start is not None and frame_end is not None:
            # Version has frame range data, so we can compare media length
            handle_start = version_attributes.get("handleStart", 0)
            handle_end = version_attributes.get("handleEnd", 0)
            frame_start_handle = frame_start - handle_start
            frame_end_handle = frame_end + handle_end
            database_frame_duration = int(
                frame_end_handle - frame_start_handle + 1
            )
            if source_duration >= database_frame_duration:
                source_in += handle_start
                source_out -= handle_end

    # get timeline in
    timeline_start = self.active_timeline.GetStartFrame()
    if self.sequential_load:
        # set timeline start frame
        timeline_in = int(timeline_start)
    else:
        # set timeline start frame + original clip in frame
        timeline_in = int(
            timeline_start + self.data["folderAttributes"]["clipIn"])

    # make track item from source in bin as item
    timeline_item = lib.create_timeline_item(
        media_pool_item,
        self.active_timeline,
        timeline_in,
        source_in,
        source_out,
    )

    print("Loading clips: `{}`".format(self.data["clip_name"]))
    return timeline_item

PublishableClip

Convert a track item to publishable instance

Parameters:

Name Type Description Default
timeline_item TrackItem

hiero track item object

required
kwargs optional

additional data needed for rename=True (presets)

required

Returns:

Type Description

hiero.core.TrackItem: hiero track item object with openpype tag

Source code in client/ayon_resolve/api/plugin.py
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
class PublishableClip:
    """
    Convert a track item to publishable instance

    Args:
        timeline_item (hiero.core.TrackItem): hiero track item object
        kwargs (optional): additional data needed for rename=True (presets)

    Returns:
        hiero.core.TrackItem: hiero track item object with openpype tag
    """
    tag_data = {}
    types = {
        "shot": "shot",
        "folder": "folder",
        "episode": "episode",
        "sequence": "sequence",
        "track": "sequence",
    }

    # parents search pattern
    parents_search_pattern = r"\{([a-z]*?)\}"

    # default templates for non-ui use
    rename_default = False
    hierarchy_default = "{_folder_}/{_sequence_}/{_track_}"
    clip_name_default = "shot_{_trackIndex_:0>3}_{_clipIndex_:0>4}"
    variant_default = "<track_name>"
    review_source_default = None
    product_type_default = "plate"
    count_from_default = 10
    count_steps_default = 10
    vertical_sync_default = False
    driving_layer_default = ""

    # Define which keys of the pre create data should also be 'tag data'
    tag_keys = {
        # renameHierarchy
        "hierarchy",
        # hierarchyData
        "folder", "episode", "sequence", "track", "shot",
        # publish settings
        "audio", "sourceResolution",
        # shot attributes
        "workfileFrameStart", "handleStart", "handleEnd"
    }

    def __init__(
            self,
            timeline_item_data: dict,
            vertical_clip_match: dict = None,
            vertical_clip_used: dict = None,
            pre_create_data: dict = None,
            media_pool_folder: str = None,
            rename_index: int = 0,
            data: dict = None,
        ):
        """ Initialize object

        Args:
            timeline_item_data (dict): timeline item data
            pre_create_data (dict): pre create data
            media_pool_folder (str): media pool folder
            rename_index (int): rename index
            data (dict): additional data

        """
        self.vertical_clip_match = vertical_clip_match 
        self.vertical_clip_used = vertical_clip_used

        self.rename_index = rename_index
        self.tag_data = data or {}

        # get main parent objects
        self.timeline_item_data = timeline_item_data
        self.timeline_item = timeline_item_data["clip"]["item"]
        timeline_name = timeline_item_data["timeline"].GetName()
        self.timeline_name = str(timeline_name).replace(" ", "_")

        # track item (clip) main attributes
        self.ti_name = self.timeline_item.GetName()
        self.ti_index = int(timeline_item_data["clip"]["index"])

        # get track name and index
        track_name = timeline_item_data["track"]["name"]
        self.track_name = str(track_name).replace(" ", "_")  # TODO clarify
        self.track_index = int(timeline_item_data["track"]["index"])

        # adding ui inputs if any
        self.pre_create_data = pre_create_data or {}

        # adding media pool folder if any
        self.media_pool_folder = media_pool_folder

        # populate default data before we get other attributes
        self._populate_timeline_item_default_data()

        # use all populated default data to create all important attributes
        self._populate_attributes()

        # create parents with correct types
        self._create_parents()

    def convert(self):
        """ Convert track item to publishable instance.

        Returns:
            timeline_item (resolve.TimelineItem): timeline item with imprinted
                data in marker
        """
        # solve track item data and add them to tag data
        self._convert_to_tag_data()

        # if track name is in review track name and also if driving track name
        # is not in review track name: skip tag creation
        if (
            self.track_name in self.reviewable_source and
            self.hero_track not in self.reviewable_source
        ):
            return

        # deal with clip name
        new_name = self.tag_data.pop("newClipName")

        if self.rename:
            self.tag_data["asset"] = new_name
        else:
            self.tag_data["asset"] = self.ti_name

        # AYON unique identifier
        folder_path = "/{}/{}".format(
            self.tag_data["hierarchy"],
            self.tag_data["asset"],
        )
        self.tag_data["folderPath"] = folder_path

        if not constants.AYON_MARKER_WORKFLOW:
            # create compound clip workflow
            lib.create_compound_clip(
                self.timeline_item_data,
                self.tag_data["asset"],
                self.media_pool_folder
            )

            # add timeline_item_data selection to tag
            self.tag_data.update({
                "track_data": self.timeline_item_data["track"]
            })

        return self.timeline_item

    def _populate_timeline_item_default_data(self):
        """ Populate default formatting data from track item. """

        self.timeline_item_default_data = {
            "_folder_": "shots",
            "_sequence_": self.timeline_name,
            "_track_": self.track_name,
            "_clip_": self.ti_name,
            "_trackIndex_": self.track_index,
            "_clipIndex_": self.ti_index
        }

    def _populate_attributes(self):
        """ Populate main object attributes. """
        # track item frame range and parent track name for vertical sync check
        self.clip_in = int(self.timeline_item.GetStart())
        self.clip_out = int(self.timeline_item.GetEnd())

        # define ui inputs if non gui mode was used
        self.shot_num = self.ti_index

        # publisher ui attribute inputs or default values if gui was not used
        def get(key):
            """Shorthand access for code readability"""
            return self.pre_create_data.get(key)

        self.rename = get("clipRename") or self.rename_default
        self.clip_name = get("clipName") or self.clip_name_default
        self.hierarchy = get("hierarchy") or self.hierarchy_default
        self.count_from = get("countFrom") or self.count_from_default
        self.count_steps = get("countSteps") or self.count_steps_default
        self.variant = get("clip_variant") or self.variant_default
        self.product_type = get("productType") or self.product_type_default
        self.vertical_sync = get("vSyncOn") or self.vertical_sync_default
        self.hero_track = get("vSyncTrack") or self.driving_layer_default
        self.hero_track = self.hero_track.replace(" ", "_")
        self.review_source = (
            get("reviewableSource") or self.review_source_default)

        self.hierarchy_data = {
            key: get(key) or self.timeline_item_default_data[key]
            for key in ["folder", "episode", "sequence", "track", "shot"]
        }

        # build subset name from layer name
        if self.variant == "<track_name>":
            self.variant = self.track_name

        # create subset for publishing
        # TODO: Use creator `get_subset_name` to correctly define name
        self.product_name = self.product_type + self.variant.capitalize()

    def _replace_hash_to_expression(self, name, text):
        """ Replace hash with number in correct padding. """
        _spl = text.split("#")
        _len = (len(_spl) - 1)
        _repl = "{{{0}:0>{1}}}".format(name, _len)
        new_text = text.replace(("#" * _len), _repl)
        return new_text

    def _convert_to_tag_data(self):
        """Convert internal data to tag data.

        Populating the tag data into internal variable self.tag_data
        """
        # define vertical sync attributes
        hero_track = True
        self.reviewable_source = ""

        if (
            self.vertical_sync
            and self.track_name not in self.hero_track
        ):
            hero_track = False

        # increasing steps by index of rename iteration
        self.count_steps *= self.rename_index

        hierarchy_formatting_data = {}
        _data = self.timeline_item_default_data.copy()
        if self.pre_create_data:

            # adding tag metadata from ui
            for _key, _value in self.pre_create_data.items():
                if _key in self.tag_keys:
                    self.tag_data[_key] = _value

            # backward compatibility for reviewableSource (2024.12.02)
            if "reviewTrack" in self.pre_create_data:
                _value = self.tag_data.pop("reviewTrack")
                self.tag_data["reviewableSource"] = _value

            # driving layer is set as positive match
            if hero_track or self.vertical_sync:
                # mark review track
                if self.review_source and (
                    self.review_source != self.review_source_default
                ):
                    # if review track is defined and not the same as default
                    self.reviewable_source = self.review_source

                # shot num calculate
                if self.rename_index == 0:
                    self.shot_num = self.count_from
                else:
                    self.shot_num = self.count_from + self.count_steps

            # clip name sequence number
            _data.update({"shot": self.shot_num})

            # solve # in test to pythonic expression
            for _key, _value in self.hierarchy_data.items():
                if "#" not in _value:
                    continue
                self.hierarchy_data[_key] = self._replace_hash_to_expression(
                    _key, _value
                )

            # fill up pythonic expresisons in hierarchy data
            for _key, _value in self.hierarchy_data.items():
                hierarchy_formatting_data[_key] = _value.format(**_data)
        else:
            # if no gui mode then just pass default data
            hierarchy_formatting_data = self.hierarchy_data

        tag_instance_data = self._solve_tag_hierarchy_data(
            hierarchy_formatting_data
        )

        tag_instance_data.update({"heroTrack": True})
        if hero_track and self.vertical_sync:
            self.vertical_clip_match.update(
                {
                    (self.clip_in, self.clip_out): tag_instance_data
                }
            )

        if not hero_track and self.vertical_sync:
            # driving layer is set as negative match
            for (hero_in, hero_out), hero_data in self.vertical_clip_match.items():  # noqa
                """Iterate over all clips in vertical sync match

                If clip frame range is outside of hero clip frame range
                then skip this clip and do not add to hierarchical shared
                metadata to them.
                """
                if self.clip_in < hero_in or self.clip_out > hero_out:
                    continue

                _distrib_data = copy.deepcopy(hero_data)
                _distrib_data["heroTrack"] = False

                # form used clip unique key
                data_product_name = hero_data["productName"]
                new_clip_name = hero_data["newClipName"]

                # get used names list for duplicity check
                used_names_list = self.vertical_clip_used.setdefault(
                    f"{new_clip_name}{data_product_name}", [])

                clip_product_name = self.product_name
                variant = self.variant

                # in case track name and product name is the same then add
                if self.variant == self.track_name:
                    clip_product_name = self.product_name

                # add track index in case duplicity of names in hero data
                # INFO: this is for case where hero clip product name
                #    is the same as current clip product name
                if clip_product_name in data_product_name:
                    clip_product_name = (
                        f"{clip_product_name}{self.track_index}")
                    variant = f"{variant}{self.track_index}"

                # in case track clip product name had been already used
                # then add product name with clip index
                if clip_product_name in used_names_list:
                    clip_product_name = (
                        f"{clip_product_name}{self.rename_index}")
                    variant = f"{variant}{self.rename_index}"

                _distrib_data["productName"] = clip_product_name
                _distrib_data["variant"] = variant
                # assign data to return hierarchy data to tag
                tag_instance_data = _distrib_data

                # add used product name to used list to avoid duplicity
                used_names_list.append(clip_product_name)
                break

        # add data to return data dict
        self.tag_data.update(tag_instance_data)

        # add uuid to tag data
        self.tag_data["uuid"] = str(uuid.uuid4())

        # add review track only to hero track
        if hero_track and self.reviewable_source:
            self.tag_data["reviewTrack"] = self.reviewable_source
        else:
            self.tag_data["reviewTrack"] = None

        # add only review related data if reviewable source is set
        if self.reviewable_source:
            review_switch = True
            reviewable_source = self.reviewable_source

            if self.vertical_sync and not hero_track:
                review_switch = False
                reviewable_source = False

            if review_switch:
                self.tag_data["review"] = True
            else:
                self.tag_data.pop("review", None)

            self.tag_data["reviewableSource"] = reviewable_source


    def _solve_tag_hierarchy_data(self, hierarchy_formatting_data):
        """ Solve tag data from hierarchy data and templates. """
        # fill up clip name and hierarchy keys
        hierarchy_filled = self.hierarchy.format(**hierarchy_formatting_data)
        clip_name_filled = self.clip_name.format(**hierarchy_formatting_data)

        return {
            "newClipName": clip_name_filled,
            "hierarchy": hierarchy_filled,
            "parents": self.parents,
            "hierarchyData": hierarchy_formatting_data,
            "productName": self.product_name,
            "productType": self.product_type
        }

    def _convert_to_entity(self, key):
        """ Converting input key to key with type. """
        # convert to entity type
        folder_type = self.types.get(key)

        assert folder_type, "Missing folder type for `{}`".format(
            key
        )

        return {
            "folder_type": folder_type,
            "entity_name": self.hierarchy_data[key].format(
                **self.timeline_item_default_data
            )
        }

    def _create_parents(self):
        """ Create parents and return it in list. """
        self.parents = []

        pattern = re.compile(self.parents_search_pattern)
        par_split = [pattern.findall(t).pop()
                     for t in self.hierarchy.split("/")]

        for key in par_split:
            parent = self._convert_to_entity(key)
            self.parents.append(parent)

__init__(timeline_item_data, vertical_clip_match=None, vertical_clip_used=None, pre_create_data=None, media_pool_folder=None, rename_index=0, data=None)

Initialize object

Parameters:

Name Type Description Default
timeline_item_data dict

timeline item data

required
pre_create_data dict

pre create data

None
media_pool_folder str

media pool folder

None
rename_index int

rename index

0
data dict

additional data

None
Source code in client/ayon_resolve/api/plugin.py
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
def __init__(
        self,
        timeline_item_data: dict,
        vertical_clip_match: dict = None,
        vertical_clip_used: dict = None,
        pre_create_data: dict = None,
        media_pool_folder: str = None,
        rename_index: int = 0,
        data: dict = None,
    ):
    """ Initialize object

    Args:
        timeline_item_data (dict): timeline item data
        pre_create_data (dict): pre create data
        media_pool_folder (str): media pool folder
        rename_index (int): rename index
        data (dict): additional data

    """
    self.vertical_clip_match = vertical_clip_match 
    self.vertical_clip_used = vertical_clip_used

    self.rename_index = rename_index
    self.tag_data = data or {}

    # get main parent objects
    self.timeline_item_data = timeline_item_data
    self.timeline_item = timeline_item_data["clip"]["item"]
    timeline_name = timeline_item_data["timeline"].GetName()
    self.timeline_name = str(timeline_name).replace(" ", "_")

    # track item (clip) main attributes
    self.ti_name = self.timeline_item.GetName()
    self.ti_index = int(timeline_item_data["clip"]["index"])

    # get track name and index
    track_name = timeline_item_data["track"]["name"]
    self.track_name = str(track_name).replace(" ", "_")  # TODO clarify
    self.track_index = int(timeline_item_data["track"]["index"])

    # adding ui inputs if any
    self.pre_create_data = pre_create_data or {}

    # adding media pool folder if any
    self.media_pool_folder = media_pool_folder

    # populate default data before we get other attributes
    self._populate_timeline_item_default_data()

    # use all populated default data to create all important attributes
    self._populate_attributes()

    # create parents with correct types
    self._create_parents()

convert()

Convert track item to publishable instance.

Returns:

Name Type Description
timeline_item TimelineItem

timeline item with imprinted data in marker

Source code in client/ayon_resolve/api/plugin.py
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
def convert(self):
    """ Convert track item to publishable instance.

    Returns:
        timeline_item (resolve.TimelineItem): timeline item with imprinted
            data in marker
    """
    # solve track item data and add them to tag data
    self._convert_to_tag_data()

    # if track name is in review track name and also if driving track name
    # is not in review track name: skip tag creation
    if (
        self.track_name in self.reviewable_source and
        self.hero_track not in self.reviewable_source
    ):
        return

    # deal with clip name
    new_name = self.tag_data.pop("newClipName")

    if self.rename:
        self.tag_data["asset"] = new_name
    else:
        self.tag_data["asset"] = self.ti_name

    # AYON unique identifier
    folder_path = "/{}/{}".format(
        self.tag_data["hierarchy"],
        self.tag_data["asset"],
    )
    self.tag_data["folderPath"] = folder_path

    if not constants.AYON_MARKER_WORKFLOW:
        # create compound clip workflow
        lib.create_compound_clip(
            self.timeline_item_data,
            self.tag_data["asset"],
            self.media_pool_folder
        )

        # add timeline_item_data selection to tag
        self.tag_data.update({
            "track_data": self.timeline_item_data["track"]
        })

    return self.timeline_item

ResolveCreator

Bases: Creator

Resolve Creator class wrapper

Source code in client/ayon_resolve/api/plugin.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
class ResolveCreator(Creator):
    """ Resolve Creator class wrapper"""

    marker_color = "Purple"
    presets = {}

    def apply_settings(self, project_settings):
        resolve_create_settings = (
            project_settings.get("resolve", {}).get("create")
        )
        self.presets = resolve_create_settings.get(
            self.__class__.__name__, {}
        )

    def create(self, subset_name, instance_data, pre_create_data):
        # adding basic current context resolve objects
        self.project = lib.get_current_resolve_project()
        self.timeline = lib.get_current_timeline()

        if pre_create_data.get("use_selection", False):
            self.selected = lib.get_current_timeline_items(filter=True)
        else:
            self.selected = lib.get_current_timeline_items(filter=False)

ResolveHost

Bases: HostBase, IWorkfileHost, ILoadHost, IPublishHost

Source code in client/ayon_resolve/api/pipeline.py
 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
102
103
104
105
106
107
108
class ResolveHost(HostBase, IWorkfileHost, ILoadHost, IPublishHost):
    name = "resolve"

    def install(self):
        """Install resolve-specific functionality of avalon-core.

        This is where you install menus and register families, data
        and loaders into resolve.

        It is called automatically when installing via `api.install(resolve)`.

        See the Maya equivalent for inspiration on how to implement this.

        """

        log.info("ayon_resolve installed")

        pyblish.register_host(self.name)
        pyblish.register_plugin_path(PUBLISH_PATH)
        print("Registering DaVinci Resolve plug-ins..")

        register_loader_plugin_path(LOAD_PATH)
        register_creator_plugin_path(CREATE_PATH)
        register_inventory_action_path(INVENTORY_PATH)

        # register callback for switching publishable
        pyblish.register_callback("instanceToggled",
                                  on_pyblish_instance_toggled)

        get_resolve_module()

    def open_workfile(self, filepath):
        return open_file(filepath)

    def save_workfile(self, filepath=None):
        return save_file(filepath)

    def work_root(self, session):
        return work_root(session)

    def get_current_workfile(self):
        return current_file()

    def workfile_has_unsaved_changes(self):
        return has_unsaved_changes()

    def get_workfile_extensions(self):
        return file_extensions()

    def get_containers(self):
        return ls()

    def get_context_data(self):
        # TODO: implement to support persisting context attributes
        return {}

    def update_context_data(self, data, changes):
        # TODO: implement to support persisting context attributes
        pass

install()

Install resolve-specific functionality of avalon-core.

This is where you install menus and register families, data and loaders into resolve.

It is called automatically when installing via api.install(resolve).

See the Maya equivalent for inspiration on how to implement this.

Source code in client/ayon_resolve/api/pipeline.py
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
def install(self):
    """Install resolve-specific functionality of avalon-core.

    This is where you install menus and register families, data
    and loaders into resolve.

    It is called automatically when installing via `api.install(resolve)`.

    See the Maya equivalent for inspiration on how to implement this.

    """

    log.info("ayon_resolve installed")

    pyblish.register_host(self.name)
    pyblish.register_plugin_path(PUBLISH_PATH)
    print("Registering DaVinci Resolve plug-ins..")

    register_loader_plugin_path(LOAD_PATH)
    register_creator_plugin_path(CREATE_PATH)
    register_inventory_action_path(INVENTORY_PATH)

    # register callback for switching publishable
    pyblish.register_callback("instanceToggled",
                              on_pyblish_instance_toggled)

    get_resolve_module()

TimelineItemLoader

Bases: LoaderPlugin

A basic SequenceLoader for Resolve

This will implement the basic behavior for a loader to inherit from that will containerize the reference and will implement the remove and update logic.

Source code in client/ayon_resolve/api/plugin.py
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
class TimelineItemLoader(LoaderPlugin):
    """A basic SequenceLoader for Resolve

    This will implement the basic behavior for a loader to inherit from that
    will containerize the reference and will implement the `remove` and
    `update` logic.

    """

    options = [
        qargparse.Boolean(
            "handles",
            label="Include handles",
            default=0,
            help="Load with handles or without?"
        ),
        qargparse.Choice(
            "load_to",
            label="Where to load clips",
            items=[
                "Current timeline",
                "New timeline"
            ],
            default=0,
            help="Where do you want clips to be loaded?"
        ),
        qargparse.Choice(
            "load_how",
            label="How to load clips",
            items=[
                "Original timing",
                "Sequentially in order"
            ],
            default="Original timing",
            help="Would you like to place it at original timing?"
        )
    ]

    def load(
        self,
        context,
        name=None,
        namespace=None,
        options=None
    ):
        pass

    def update(self, container, context):
        """Update an existing `container`
        """
        pass

    def remove(self, container):
        """Remove an existing `container`
        """
        pass

remove(container)

Remove an existing container

Source code in client/ayon_resolve/api/plugin.py
284
285
286
287
def remove(self, container):
    """Remove an existing `container`
    """
    pass

update(container, context)

Update an existing container

Source code in client/ayon_resolve/api/plugin.py
279
280
281
282
def update(self, container, context):
    """Update an existing `container`
    """
    pass

containerise(timeline_item, name, namespace, context, loader=None, data=None)

Bundle Resolve's object into an assembly and imprint it with metadata

Containerization enables a tracking of version, author and origin for loaded assets.

Parameters:

Name Type Description Default
timeline_item TimelineItem

The object to containerise

required
name str

Name of resulting assembly

required
namespace str

Namespace under which to host container

required
context dict

Asset information

required
loader str

Name of node used to produce this container.

None

Returns:

Name Type Description
timeline_item TimelineItem

containerized object

Source code in client/ayon_resolve/api/pipeline.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def containerise(timeline_item,
                 name,
                 namespace,
                 context,
                 loader=None,
                 data=None):
    """Bundle Resolve's object into an assembly and imprint it with metadata

    Containerization enables a tracking of version, author and origin
    for loaded assets.

    Arguments:
        timeline_item (resolve.TimelineItem): The object to containerise
        name (str): Name of resulting assembly
        namespace (str): Namespace under which to host container
        context (dict): Asset information
        loader (str, optional): Name of node used to produce this container.

    Returns:
        timeline_item (resolve.TimelineItem): containerized object

    """

    data_imprint = OrderedDict({
        "schema": "openpype:container-2.0",
        "id": AVALON_CONTAINER_ID,
        "name": str(name),
        "namespace": str(namespace),
        "loader": str(loader),
        "representation": context["representation"]["id"],
    })

    if data:
        data_imprint.update(data)

    lib.set_timeline_item_ayon_tag(timeline_item, data_imprint)

    return timeline_item

create_bin(name, root=None, set_as_current=True)

Create media pool's folder.

Return folder object and if the name does not exist it will create a new. If the input name is with forward or backward slashes then it will create all parents and return the last child bin object

Parameters:

Name Type Description Default
name str

name of folder / bin, or hierarchycal name "parent/name"

required
root resolve.Folder)[optional]

root folder / bin object

None
set_as_current resolve.Folder)[optional]

Whether to set the resulting bin as current folder or not.

True

Returns:

Name Type Description
object object

resolve.Folder

Source code in client/ayon_resolve/api/lib.py
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
def create_bin(name: str,
               root: object = None,
               set_as_current: bool = True) -> object:
    """
    Create media pool's folder.

    Return folder object and if the name does not exist it will create a new.
    If the input name is with forward or backward slashes then it will create
    all parents and return the last child bin object

    Args:
        name (str): name of folder / bin, or hierarchycal name "parent/name"
        root (resolve.Folder)[optional]: root folder / bin object
        set_as_current (resolve.Folder)[optional]: Whether to set the
            resulting bin as current folder or not.

    Returns:
        object: resolve.Folder
    """
    # get all variables
    media_pool = get_current_resolve_project().GetMediaPool()
    root_bin = root or media_pool.GetRootFolder()

    # create hierarchy of bins in case there is slash in name
    if "/" in name.replace("\\", "/"):
        child_bin = None
        for bname in name.split("/"):
            child_bin = create_bin(bname,
                                   root=child_bin or root_bin,
                                   set_as_current=set_as_current)
        if child_bin:
            return child_bin
    else:
        # Find existing folder or create it
        for subfolder in root_bin.GetSubFolderList():
            if subfolder.GetName() == name:
                created_bin = subfolder
                break
        else:
            created_bin = media_pool.AddSubFolder(root_bin, name)

        if set_as_current:
            media_pool.SetCurrentFolder(created_bin)

        return created_bin

create_compound_clip(clip_data, name, folder)

Convert timeline object into nested timeline object

Parameters:

Name Type Description Default
clip_data dict

timeline item object packed into dict with project, timeline (sequence)

required
folder Folder

media pool folder object,

required
name str

name for compound clip

required

Returns:

Type Description

resolve.MediaPoolItem: media pool item with compound clip timeline(cct)

Source code in client/ayon_resolve/api/lib.py
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
def create_compound_clip(clip_data, name, folder):
    """
    Convert timeline object into nested timeline object

    Args:
        clip_data (dict): timeline item object packed into dict
                          with project, timeline (sequence)
        folder (resolve.MediaPool.Folder): media pool folder object,
        name (str): name for compound clip

    Returns:
        resolve.MediaPoolItem: media pool item with compound clip timeline(cct)
    """
    # get basic objects form data
    resolve_project = clip_data["project"]
    timeline = clip_data["timeline"]
    clip = clip_data["clip"]

    # get details of objects
    clip_item = clip["item"]

    mp = resolve_project.GetMediaPool()

    # get clip attributes
    clip_attributes = get_clip_attributes(clip_item)

    mp_item = clip_item.GetMediaPoolItem()
    _mp_props = mp_item.GetClipProperty

    mp_first_frame = int(_mp_props("Start"))
    mp_last_frame = int(_mp_props("End"))

    # initialize basic source timing for otio
    ci_l_offset = clip_item.GetLeftOffset()
    ci_duration = clip_item.GetDuration()
    rate = float(_mp_props("FPS"))

    # source rational times
    mp_in_rc = otio.opentime.RationalTime((ci_l_offset), rate)
    mp_out_rc = otio.opentime.RationalTime((ci_l_offset + ci_duration - 1), rate)

    # get frame in and out for clip swapping
    in_frame = otio.opentime.to_frames(mp_in_rc)
    out_frame = otio.opentime.to_frames(mp_out_rc)

    # keep original sequence
    tl_origin = timeline

    # Set current folder to input media_pool_folder:
    mp.SetCurrentFolder(folder)

    # check if clip doesn't exist already:
    clips = folder.GetClipList()
    cct = next((c for c in clips
                if c.GetName() in name), None)

    if cct:
        print(f"Compound clip exists: {cct}")
    else:
        # Create empty timeline in current folder and give name:
        cct = mp.CreateEmptyTimeline(name)

        # check if clip doesn't exist already:
        clips = folder.GetClipList()
        cct = next((c for c in clips
                    if c.GetName() in name), None)
        print(f"Compound clip created: {cct}")

        with maintain_current_timeline(cct, tl_origin):
            # Add input clip to the current timeline:
            mp.AppendToTimeline([{
                "mediaPoolItem": mp_item,
                "startFrame": mp_first_frame,
                "endFrame": mp_last_frame
            }])

    # Add collected metadata and attributes to the compound clip:
    if mp_item.GetMetadata(constants.AYON_TAG_NAME):
        clip_attributes[constants.AYON_TAG_NAME] = mp_item.GetMetadata(
            constants.AYON_TAG_NAME)[constants.AYON_TAG_NAME]

    # stringify
    clip_attributes = json.dumps(clip_attributes)

    # add attributes to metadata
    for k, v in mp_item.GetMetadata().items():
        cct.SetMetadata(k, v)

    # add metadata to cct
    cct.SetMetadata(constants.AYON_TAG_NAME, clip_attributes)

    # reset start timecode of the compound clip
    cct.SetClipProperty("Start TC", _mp_props("Start TC"))

    # swap clips on timeline
    swap_clips(clip_item, cct, in_frame, out_frame)

    cct.SetClipColor("Pink")
    return cct

create_media_pool_item(files, root=None)

Create media pool item.

Parameters:

Name Type Description Default
files list

absolute path to a file

required
root resolve.Folder)[optional]

root folder / bin object

None

Returns:

Name Type Description
object object

resolve.MediaPoolItem

Source code in client/ayon_resolve/api/lib.py
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
def create_media_pool_item(files: list,
                           root: object = None) -> object:
    """ Create media pool item.

    Args:
        files (list): absolute path to a file
        root (resolve.Folder)[optional]: root folder / bin object

    Returns:
        object: resolve.MediaPoolItem
    """
    # get all variables
    resolve_project = get_current_resolve_project()
    media_pool = resolve_project.GetMediaPool()
    root_bin = root or media_pool.GetRootFolder()

    # make sure files list is not empty and first available file exists
    filepath = next((f for f in files if os.path.isfile(f)), None)
    if not filepath:
        raise FileNotFoundError("No file found in input files list")

    # try to search in bin if the clip does not exist
    existing_mpi = get_media_pool_item(filepath, root_bin)

    if existing_mpi:
        return existing_mpi

    # add media to media-pool
    media_pool_items = media_pool.ImportMedia(files)

    if not media_pool_items:
        return False

    # return only first found
    return media_pool_items.pop()

create_timeline_item(media_pool_item, timeline=None, timeline_in=None, source_start=None, source_end=None)

Add media pool item to current or defined timeline.

Parameters:

Name Type Description Default
media_pool_item MediaPoolItem

resolve's object

required
timeline Optional[Timeline]

resolve's object

None
timeline_in Optional[int]

timeline input frame (sequence frame)

None
source_start Optional[int]

media source input frame (sequence frame)

None
source_end Optional[int]

media source output frame (sequence frame)

None

Returns:

Name Type Description
object object

resolve.TimelineItem

Source code in client/ayon_resolve/api/lib.py
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
def create_timeline_item(
        media_pool_item: object,
        timeline: object = None,
        timeline_in: int = None,
        source_start: int = None,
        source_end: int = None,
) -> object:
    """
    Add media pool item to current or defined timeline.

    Args:
        media_pool_item (resolve.MediaPoolItem): resolve's object
        timeline (Optional[resolve.Timeline]): resolve's object
        timeline_in (Optional[int]): timeline input frame (sequence frame)
        source_start (Optional[int]): media source input frame (sequence frame)
        source_end (Optional[int]): media source output frame (sequence frame)

    Returns:
        object: resolve.TimelineItem
    """
    # get all variables
    resolve_project = get_current_resolve_project()
    media_pool = resolve_project.GetMediaPool()
    clip_name = media_pool_item.GetClipProperty("File Name")
    timeline = timeline or get_current_timeline()

    # timing variables
    if all([
        timeline_in is not None,
        source_start is not None,
        source_end is not None
    ]):
        fps = timeline.GetSetting("timelineFrameRate")
        duration = source_end - source_start
        timecode_in = frames_to_timecode(timeline_in, fps)
        timecode_out = frames_to_timecode(timeline_in + duration, fps)
    else:
        timecode_in = None
        timecode_out = None

    # if timeline was used then switch it to current timeline
    with maintain_current_timeline(timeline):
        # Add input mediaPoolItem to clip data
        clip_data = {
            "mediaPoolItem": media_pool_item,
        }

        if source_start:
            clip_data["startFrame"] = source_start
        if source_end:
            clip_data["endFrame"] = source_end
        if timecode_in:
            # Note: specifying a recordFrame will fail to place the timeline
            #  item if there's already an existing clip at that time on the
            #  active track.
            clip_data["recordFrame"] = timeline_in

        # add to timeline
        output_timeline_item = media_pool.AppendToTimeline([clip_data])[0]

        # Adding the item may fail whilst Resolve will still return a
        # TimelineItem instance - however all `Get*` calls return None
        # Hence, we check whether the result is valid
        if output_timeline_item.GetDuration() is None:
            output_timeline_item = None

    assert output_timeline_item, AssertionError((
        "Clip name '{}' wasn't created on the timeline: '{}' \n\n"
        "Please check if correct track position is activated, \n"
        "or if a clip is not already at the timeline in \n"
        "position: '{}' out: '{}'. \n\n"
        "Clip data: {}"
    ).format(
        clip_name, timeline.GetName(), timecode_in, timecode_out, clip_data
    ))
    return output_timeline_item

export_timeline_otio(timeline)

Export timeline as otio.

Parameters:

Name Type Description Default
timeline Timeline

resolve's timeline

required

Returns:

Name Type Description
otio_timeline Timeline

Otio timeline.

Source code in client/ayon_resolve/api/lib.py
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
def export_timeline_otio(timeline):
    """ Export timeline as otio.

    Args:
        timeline (resolve.Timeline): resolve's timeline

    Returns:
        otio_timeline (otio.Timeline): Otio timeline.
    """
    # DaVinci Resolve <= 18.5
    # Legacy export (slower) through AYON.
    if not hasattr(timeline, "Export"):
        return otio_export.create_otio_timeline(
            get_current_resolve_project(),
            timeline=timeline
        )

    # DaVinci Resolve >= 18.5
    # Force export through a temporary file (native)
    temp_otio_file = _get_otio_temp_file(timeline=timeline)
    export_timeline_otio_to_file(timeline, temp_otio_file)
    otio_timeline = otio.adapters.read_from_file(temp_otio_file)

    return otio_timeline

export_timeline_otio_to_file(timeline, filepath)

Export timeline as otio filepath.

Parameters:

Name Type Description Default
timeline Timeline

resolve's timeline

required
filepath str

otio file path

required

Returns:

Name Type Description
str

temporary otio filepath

Source code in client/ayon_resolve/api/lib.py
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
def export_timeline_otio_to_file(timeline, filepath):
    """Export timeline as otio filepath.

    Args:
        timeline (resolve.Timeline): resolve's timeline
        filepath (str): otio file path

    Returns:
        str: temporary otio filepath
    """
    try:
        from . import bmdvr

        if bmdvr.EXPORT_OTIO is None:
            raise AttributeError("Unsupported native Export OTIO")

        timeline.Export(filepath, bmdvr.EXPORT_OTIO)

    except Exception as error:
        log.debug(
            "Cannot use native OTIO export (%r)."
            "Default to AYON own implementation.",
            error
        )
        otio_timeline = otio_export.create_otio_timeline(
            get_current_resolve_project(),
            timeline=timeline
        )
        otio_export.write_to_file(otio_timeline, filepath)

get_any_timeline()

Get any timeline object.

Returns:

Type Description

object | None: resolve.Timeline

Source code in client/ayon_resolve/api/lib.py
189
190
191
192
193
194
195
196
197
198
def get_any_timeline():
    """Get any timeline object.

    Returns:
        object | None: resolve.Timeline
    """
    resolve_project = get_current_resolve_project()
    timeline_count = resolve_project.GetTimelineCount()
    if timeline_count > 0:
        return resolve_project.GetTimelineByIndex(1)

get_clip_resolution_from_media_pool(timeline_item_data)

Return the clip resolution from media pool data.

Parameters:

Name Type Description Default
timeline_item_data dict

Timeline item to investigate.

required

Returns:

Name Type Description
resolution_info dict

The parsed resolution data.

Source code in client/ayon_resolve/api/lib.py
 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
def get_clip_resolution_from_media_pool(timeline_item_data):
    """Return the clip resolution from media pool data.

    Args:
        timeline_item_data (dict): Timeline item to investigate.

    Returns:
        resolution_info (dict): The parsed resolution data.
    """
    clip_item = timeline_item_data["clip"]["item"]
    media_pool_item = clip_item.GetMediaPoolItem()
    clip_properties = media_pool_item.GetClipProperty()

    try:
        width, height = clip_properties["Resolution"].split("x")
    except (KeyError, ValueError):
        width = height = None

    try:
        clip_par = clip_properties["PAR"]  # Pixel Aspect Resolution
        pixel_aspect = constants.PAR_VALUES[clip_par]

    except (KeyError, ValueError):  # Unknown or undetected PAR
        pixel_aspect = 1.0

    return {"width": width, "height": height, "pixelAspect": pixel_aspect}

get_current_resolve_project()

Get current resolve project object.

Returns:

Type Description

resolve.Project

Source code in client/ayon_resolve/api/lib.py
154
155
156
157
158
159
160
161
def get_current_resolve_project():
    """Get current resolve project object.

    Returns:
        resolve.Project
    """
    project_manager = get_project_manager()
    return project_manager.GetCurrentProject()

get_current_timeline(new=False)

Get current timeline object.

Parameters:

Name Type Description Default
new bool)[optional]

[DEPRECATED] if True it will create new timeline if none exists

False

Returns:

Type Description

object | None: resolve.Timeline

Source code in client/ayon_resolve/api/lib.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def get_current_timeline(new=False):
    """Get current timeline object.

    Args:
        new (bool)[optional]: [DEPRECATED] if True it will create
            new timeline if none exists

    Returns:
        object | None: resolve.Timeline
    """
    resolve_project = get_current_resolve_project()
    timeline = resolve_project.GetCurrentTimeline()

    # return current timeline if any
    if timeline:
        return timeline

    # TODO: [deprecated] and will be removed in future
    if new:
        return get_new_timeline()

get_current_timeline_items(filter=False, track_type=None, track_name=None, selecting_color=None)

Get all available current timeline track items

Source code in client/ayon_resolve/api/lib.py
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
def get_current_timeline_items(
        filter: bool = False,
        track_type: str = None,
        track_name: str = None,
        selecting_color: str = None) -> List[Dict[str, Any]]:
    """Get all available current timeline track items"""
    track_type = track_type or "video"
    selecting_color = selecting_color or constants.SELECTED_CLIP_COLOR
    resolve_project = get_current_resolve_project()

    # get timeline anyhow
    timeline = get_current_timeline() or get_any_timeline()
    if not timeline:
        return []

    selected_clips = []

    # get all tracks count filtered by track type
    selected_track_count = timeline.GetTrackCount(track_type)

    # loop all tracks and get items
    _clips = {}
    for track_index in range(1, (int(selected_track_count) + 1)):
        _track_name = timeline.GetTrackName(track_type, track_index)

        # filter out all unmatched track names
        if track_name and _track_name not in track_name:
            continue

        timeline_items = timeline.GetItemListInTrack(track_type, track_index)
        _clips[track_index] = timeline_items

        _data = {
            "project": resolve_project,
            "timeline": timeline,
            "track": {
                "name": _track_name,
                "index": track_index,
                "type": track_type}
        }
        # get track item object and its color
        for clip_index, ti in enumerate(_clips[track_index]):
            data = _data.copy()
            data["clip"] = {
                "item": ti,
                "index": clip_index
            }
            ti_color = ti.GetClipColor()
            if filter and selecting_color in ti_color or not filter:
                selected_clips.append(data)
    return selected_clips

get_media_pool_item(filepath, root=None)

Return clip if found in folder with use of input file path.

Parameters:

Name Type Description Default
filepath str

absolute path to a file

required
root resolve.Folder)[optional]

root folder / bin object

None

Returns:

Name Type Description
object object

resolve.MediaPoolItem

Source code in client/ayon_resolve/api/lib.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def get_media_pool_item(filepath, root: object = None) -> object:
    """
    Return clip if found in folder with use of input file path.

    Args:
        filepath (str): absolute path to a file
        root (resolve.Folder)[optional]: root folder / bin object

    Returns:
        object: resolve.MediaPoolItem
    """
    resolve_project = get_current_resolve_project()
    media_pool = resolve_project.GetMediaPool()
    root = root or media_pool.GetRootFolder()
    fname = os.path.basename(filepath)

    for _mpi in root.GetClipList():
        _mpi_name = _mpi.GetClipProperty("File Name")
        _mpi_name = get_reformated_path(_mpi_name, first=True)
        if fname in _mpi_name:
            return _mpi
    return None

get_new_timeline(timeline_name=None)

Get new timeline object.

Parameters:

Name Type Description Default
timeline_name str

New timeline name.

None

Returns:

Name Type Description
object

resolve.Timeline

Source code in client/ayon_resolve/api/lib.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def get_new_timeline(timeline_name: str = None):
    """Get new timeline object.

    Arguments:
        timeline_name (str): New timeline name.

    Returns:
        object: resolve.Timeline
    """
    resolve_project = get_current_resolve_project()
    media_pool = resolve_project.GetMediaPool()
    new_timeline = media_pool.CreateEmptyTimeline(
        timeline_name or constants.AYON_TIMELINE_NAME)
    resolve_project.SetCurrentTimeline(new_timeline)
    return new_timeline

get_otio_clip_instance_data(otio_timeline, timeline_item_data)

Return otio objects for timeline, track and clip

Parameters:

Name Type Description Default
timeline_item_data dict

timeline_item_data from list returned by resolve.get_current_timeline_items()

required
otio_timeline Timeline

otio object

required

Returns:

Name Type Description
dict

otio clip object

Source code in client/ayon_resolve/api/lib.py
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
def get_otio_clip_instance_data(otio_timeline, timeline_item_data):
    """
    Return otio objects for timeline, track and clip

    Args:
        timeline_item_data (dict): timeline_item_data from list returned by
                                resolve.get_current_timeline_items()
        otio_timeline (otio.schema.Timeline): otio object

    Returns:
        dict: otio clip object

    """

    timeline_item = timeline_item_data["clip"]["item"]
    track_name = timeline_item_data["track"]["name"]
    timeline_range = create_otio_time_range_from_timeline_item_data(
        timeline_item_data)

    try:  # opentimelineio >= 0.16.0
        all_clips = otio_timeline.find_clips()
    except AttributeError:  # legacy
        all_clips = otio_timeline.each_clip()

    for otio_clip in all_clips:
        track_name = otio_clip.parent().name
        parent_range = otio_clip.range_in_parent()
        if track_name not in track_name:
            continue
        if otio_clip.name not in timeline_item.GetName():
            continue
        if is_overlapping_otio_ranges(
                parent_range, timeline_range, strict=True):

            # add pypedata marker to otio_clip metadata
            for marker in otio_clip.markers:
                if constants.AYON_MARKER_NAME in marker.name:
                    otio_clip.metadata.update(marker.metadata)
            return {"otioClip": otio_clip}

    return None

get_project_manager()

Get project manager object.

Returns:

Type Description

resolve.ProjectManager

Source code in client/ayon_resolve/api/lib.py
129
130
131
132
133
134
135
136
137
138
139
def get_project_manager():
    """Get project manager object.

    Returns:
        resolve.ProjectManager
    """
    from . import bmdvr, project_manager
    if not project_manager:
        project_manager = bmdvr.GetProjectManager()

    return project_manager

get_publish_attribute(timeline_item)

Get Publish attribute from marker on timeline item

Attribute

timeline_item (resolve.TimelineItem): resolve's object

Source code in client/ayon_resolve/api/lib.py
661
662
663
664
665
666
667
668
def get_publish_attribute(timeline_item):
    """ Get Publish attribute from marker on timeline item

    Attribute:
        timeline_item (resolve.TimelineItem): resolve's object
    """
    tag_data = get_timeline_item_ayon_tag(timeline_item)
    return tag_data["publish"]

get_pype_clip_metadata(clip)

Get AYON metadata created by creator plugin

Attributes:

Name Type Description
clip TimelineItem

resolve's object

Returns:

Name Type Description
dict

hierarchy, orig clip attributes

Source code in client/ayon_resolve/api/lib.py
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def get_pype_clip_metadata(clip):
    """
    Get AYON metadata created by creator plugin

    Attributes:
        clip (resolve.TimelineItem): resolve's object

    Returns:
        dict: hierarchy, orig clip attributes
    """
    mp_item = clip.GetMediaPoolItem()
    metadata = mp_item.GetMetadata()

    return metadata.get(constants.AYON_TAG_NAME)

get_reformated_path(path, padded=False, first=False)

Return fixed python expression path

Parameters:

Name Type Description Default
path str

path url or simple file name

required

Returns:

Name Type Description
type

string with reformatted path

Example

get_reformated_path("plate.[0001-1008].exr") > plate.%04d.exr

Source code in client/ayon_resolve/api/lib.py
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
def get_reformated_path(path, padded=False, first=False):
    """
    Return fixed python expression path

    Args:
        path (str): path url or simple file name

    Returns:
        type: string with reformatted path

    Example:
        get_reformated_path("plate.[0001-1008].exr") > plate.%04d.exr

    """
    first_frame_pattern = re.compile(r"\[(\d+)\-\d+\]")

    if "[" in path:
        padding_pattern = r"(\d+)(?=-)"
        padding = len(re.findall(padding_pattern, path).pop())
        num_pattern = r"(\[\d+\-\d+\])"
        if padded:
            path = re.sub(num_pattern, f"%0{padding}d", path)
        elif first:
            first_frame = re.findall(first_frame_pattern, path, flags=0)
            if len(first_frame) >= 1:
                first_frame = first_frame[0]
            path = re.sub(num_pattern, first_frame, path)
        else:
            path = re.sub(num_pattern, "%d", path)
    return path

get_timeline_item(media_pool_item, timeline=None)

Returns clips related to input mediaPoolItem.

Parameters:

Name Type Description Default
media_pool_item MediaPoolItem

resolve's object

required
timeline resolve.Timeline)[optional]

resolve's object

None

Returns:

Name Type Description
object object

resolve.TimelineItem

Source code in client/ayon_resolve/api/lib.py
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
def get_timeline_item(media_pool_item: object,
                      timeline: object = None) -> object:
    """
    Returns clips related to input mediaPoolItem.

    Args:
        media_pool_item (resolve.MediaPoolItem): resolve's object
        timeline (resolve.Timeline)[optional]: resolve's object

    Returns:
        object: resolve.TimelineItem
    """
    clip_name = media_pool_item.GetClipProperty("File Name")
    output_timeline_item = None
    timeline = timeline or get_current_timeline()

    with maintain_current_timeline(timeline):
        # search the timeline for the added clip

        for ti_data in get_current_timeline_items():
            ti_clip_item = ti_data["clip"]["item"]
            ti_media_pool_item = ti_clip_item.GetMediaPoolItem()

            # Skip items that do not have a media pool item, like for example
            # an "Adjustment Clip" or a "Fusion Composition" from the effects
            # toolbox
            if not ti_media_pool_item:
                continue

            if clip_name in ti_media_pool_item.GetClipProperty("File Name"):
                output_timeline_item = ti_clip_item

    return output_timeline_item

get_timeline_item_ayon_tag(timeline_item)

Get ayon track item tag created by creator or loader plugin.

Attributes:

Name Type Description
trackItem TimelineItem

resolve object

Returns:

Name Type Description
dict

ayon tag data

Source code in client/ayon_resolve/api/lib.py
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
def get_timeline_item_ayon_tag(timeline_item):
    """
    Get ayon track item tag created by creator or loader plugin.

    Attributes:
        trackItem (resolve.TimelineItem): resolve object

    Returns:
        dict: ayon tag data
    """
    return_tag = None

    if constants.AYON_MARKER_WORKFLOW:
        return_tag = get_ayon_marker(timeline_item)
    else:
        media_pool_item = timeline_item.GetMediaPoolItem()

        # get all tags from track item
        _tags = media_pool_item.GetMetadata()
        if not _tags:
            return None
        for key, data in _tags.items():
            # return only correct tag defined by global name
            if key in constants.AYON_TAG_NAME:
                return_tag = json.loads(data)

    return return_tag

get_timeline_item_by_name(name)

Get timeline item by name.

Parameters:

Name Type Description Default
name str

name of timeline item

required

Returns:

Name Type Description
object object

resolve.TimelineItem

Source code in client/ayon_resolve/api/lib.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def get_timeline_item_by_name(name: str) -> object:
    """Get timeline item by name.

    Args:
        name (str): name of timeline item

    Returns:
        object: resolve.TimelineItem
    """
    for _ti_data in get_current_timeline_items():
        _ti_clip = _ti_data["clip"]["item"]
        tag_data = get_timeline_item_pype_tag(_ti_clip)
        tag_name = tag_data.get("namespace")
        if not tag_name:
            continue
        if tag_name in name:
            return _ti_clip
    return None

imprint(timeline_item, data=None)

Adding Ayon data into a timeline item track item tag.

Also including publish attribute into tag.

Parameters:

Name Type Description Default
timeline_item TimelineItem

resolve's object

required
data dict

Any data which needs to be imprinted

None

Examples:

data = { 'asset': 'sq020sh0280', 'family': 'render', 'subset': 'subsetMain' }

Source code in client/ayon_resolve/api/lib.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def imprint(timeline_item, data=None):
    """
    Adding `Ayon data` into a timeline item track item tag.

    Also including publish attribute into tag.

    Arguments:
        timeline_item (resolve.TimelineItem): resolve's object
        data (dict): Any data which needs to be imprinted

    Examples:
        data = {
            'asset': 'sq020sh0280',
            'family': 'render',
            'subset': 'subsetMain'
        }
    """
    data = data or {}

    set_timeline_item_ayon_tag(timeline_item, data)

    # add publish attribute
    set_publish_attribute(timeline_item, True)

ls()

List available containers.

This function is used by the Container Manager in Nuke. You'll need to implement a for-loop that then yields one Container at a time.

See the container.json schema for details on how it should look, and the Maya equivalent, which is in avalon.maya.pipeline

Source code in client/ayon_resolve/api/pipeline.py
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
def ls():
    """List available containers.

    This function is used by the Container Manager in Nuke. You'll
    need to implement a for-loop that then *yields* one Container at
    a time.

    See the `container.json` schema for details on how it should look,
    and the Maya equivalent, which is in `avalon.maya.pipeline`
    """

    # Media Pool instances from Load Media loader
    for clip in lib.iter_all_media_pool_clips():
        data = clip.GetMetadata(constants.AYON_TAG_NAME)
        if not data:
            continue

        try:
            data = json.loads(data)
        except json.JSONDecodeError:
            log.warning(
                f"Failed to parse json data from media pool item: "
                f"{clip.GetName()}"
            )
            continue

        # treat data as container
        # There might be cases where clip's metadata are having additional
        # because it needs to store 'load' and 'publish' data. In that case
        # we need to get only 'load' data
        if data.get("load"):
            data = data["load"]

        # If not all required data, skip it
        required = ['schema', 'id', 'loader', 'representation']
        if not all(key in data for key in required):
            continue

        container = {key: data[key] for key in required}
        container["objectName"] = clip.GetName()  # Get path in folders
        container["namespace"] = clip.GetName()
        container["name"] = clip.GetUniqueId()
        container["_item"] = clip
        yield container

    # Timeline instances from Load Clip loader
    # get all track items from current timeline
    all_timeline_items = lib.get_current_timeline_items(filter=False)

    for timeline_item_data in all_timeline_items:
        timeline_item = timeline_item_data["clip"]["item"]
        container = parse_container(timeline_item)
        if container:
            yield container

maintain_current_timeline(to_timeline, from_timeline=None)

Maintain current timeline selection during context

Attributes:

Name Type Description
from_timeline resolve.Timeline)[optional]

Example: >>> print(from_timeline.GetName()) timeline1 >>> print(to_timeline.GetName()) timeline2

>>> with maintain_current_timeline(to_timeline):
...     print(get_current_timeline().GetName())
timeline2

>>> print(get_current_timeline().GetName())
timeline1
Source code in client/ayon_resolve/api/lib.py
 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
102
@contextlib.contextmanager
def maintain_current_timeline(to_timeline: object,
                              from_timeline: object = None):
    """Maintain current timeline selection during context

    Attributes:
        from_timeline (resolve.Timeline)[optional]:
    Example:
        >>> print(from_timeline.GetName())
        timeline1
        >>> print(to_timeline.GetName())
        timeline2

        >>> with maintain_current_timeline(to_timeline):
        ...     print(get_current_timeline().GetName())
        timeline2

        >>> print(get_current_timeline().GetName())
        timeline1
    """
    project = get_current_resolve_project()
    working_timeline = from_timeline or project.GetCurrentTimeline()

    # search timeline withing project timelines in case the
    # to_timeline is MediaPoolItem
    # Note: this is a hacky way of identifying if object is timeline since
    #   mediapool item is not having AddTrack attribute. API is not providing
    #   any other way to identify the object type. And hasattr is returning
    #   false info.
    if "AddTrack" not in dir(to_timeline):
        tcount = project.GetTimelineCount()
        for idx in range(0, int(tcount)):
            timeline = project.GetTimelineByIndex(idx + 1)
            if timeline.GetName() == to_timeline.GetName():
                to_timeline = timeline
                break

    try:
        # switch to the input timeline
        result = project.SetCurrentTimeline(to_timeline)
        if not result:
            raise ValueError(f"Failed to switch to timeline: {to_timeline}")

        current_timeline = project.GetCurrentTimeline()
        yield current_timeline
    finally:
        # put the original working timeline to context
        project.SetCurrentTimeline(working_timeline)

maintained_selection()

Maintain selection during context

Example

with maintained_selection(): ... node['selected'].setValue(True) print(node['selected'].value()) False

Source code in client/ayon_resolve/api/pipeline.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
@contextlib.contextmanager
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> with maintained_selection():
        ...     node['selected'].setValue(True)
        >>> print(node['selected'].value())
        False
    """
    try:
        # do the operation
        yield
    finally:
        pass

open_file(filepath)

Loading project

Source code in client/ayon_resolve/api/workio.py
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
def open_file(filepath):
    """
    Loading project
    """

    from . import bmdvr

    project_manager = get_project_manager()
    page = bmdvr.GetCurrentPage()
    if page is not None:
        # Save current project only if Resolve has an active page, otherwise
        # we consider Resolve being in a pre-launch state (no open UI yet)
        resolve_project = get_current_resolve_project()
        print(f"Saving current resolve project: {resolve_project}")
        project_manager.SaveProject()

    file = os.path.basename(filepath)
    fname, _ = os.path.splitext(file)

    try:
        # load project from input path
        resolve_project = project_manager.LoadProject(fname)
        log.info(f"Project {resolve_project.GetName()} opened...")

    except AttributeError:
        log.warning((f"Project with name `{fname}` does not exist! It will "
                     f"be imported from {filepath} and then loaded..."))
        if project_manager.ImportProject(filepath):
            # load project from input path
            resolve_project = project_manager.LoadProject(fname)
            log.info(f"Project imported/loaded {resolve_project.GetName()}...")
            return True
        return False
    return True

set_project_manager_to_folder_name(folder_name)

Sets context of Project manager to given folder by name.

Searching for folder by given name from root folder to nested. If no existing folder by name it will create one in root folder.

Parameters:

Name Type Description Default
folder_name str

name of searched folder

required

Returns:

Name Type Description
bool

True if success

Raises:

Type Description
Exception

Cannot create folder in root

Source code in client/ayon_resolve/api/lib.py
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
def set_project_manager_to_folder_name(folder_name):
    """
    Sets context of Project manager to given folder by name.

    Searching for folder by given name from root folder to nested.
    If no existing folder by name it will create one in root folder.

    Args:
        folder_name (str): name of searched folder

    Returns:
        bool: True if success

    Raises:
        Exception: Cannot create folder in root

    """
    # initialize project manager
    project_manager = get_project_manager()

    set_folder = False

    # go back to root folder
    if project_manager.GotoRootFolder():
        log.info(f"Testing existing folder: {folder_name}")
        folders = _convert_resolve_list_type(
            project_manager.GetFoldersInCurrentFolder())
        log.info(f"Testing existing folders: {folders}")
        # get me first available folder object
        # with the same name as in `folder_name` else return False
        if next((f for f in folders if f in folder_name), False):
            log.info(f"Found existing folder: {folder_name}")
            set_folder = project_manager.OpenFolder(folder_name)

    if set_folder:
        return True

    # if folder by name is not existent then create one
    # go back to root folder
    log.info(f"Folder `{folder_name}` not found and will be created")
    if project_manager.GotoRootFolder():
        try:
            # create folder by given name
            project_manager.CreateFolder(folder_name)
            project_manager.OpenFolder(folder_name)
            return True
        except NameError as e:
            log.error((f"Folder with name `{folder_name}` cannot be created!"
                       f"Error: {e}"))
            return False

set_publish_attribute(timeline_item, value)

Set Publish attribute to marker on timeline item

Attribute

timeline_item (resolve.TimelineItem): resolve's object

Source code in client/ayon_resolve/api/lib.py
649
650
651
652
653
654
655
656
657
658
def set_publish_attribute(timeline_item, value):
    """ Set Publish attribute to marker on timeline item

    Attribute:
        timeline_item (resolve.TimelineItem): resolve's object
    """
    tag_data = get_timeline_item_ayon_tag(timeline_item)
    tag_data["publish"] = value
    # set data to the publish attribute
    set_timeline_item_ayon_tag(timeline_item, tag_data)

set_timeline_item_ayon_tag(timeline_item, data=None)

Set ayon track item tag to input timeline_item.

Attributes:

Name Type Description
trackItem TimelineItem

resolve api object

Returns:

Name Type Description
dict

json loaded data

Source code in client/ayon_resolve/api/lib.py
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
def set_timeline_item_ayon_tag(timeline_item, data=None):
    """
    Set ayon track item tag to input timeline_item.

    Attributes:
        trackItem (resolve.TimelineItem): resolve api object

    Returns:
        dict: json loaded data
    """
    data = data or {}

    # get available ayon tag if any
    tag_data = get_timeline_item_ayon_tag(timeline_item)

    if constants.AYON_MARKER_WORKFLOW:
        # delete tag as it is not updatable
        if tag_data:
            delete_ayon_marker(timeline_item)

        tag_data.update(data)
        set_ayon_marker(timeline_item, tag_data)
    else:
        if tag_data:
            media_pool_item = timeline_item.GetMediaPoolItem()
            # it not tag then create one
            tag_data.update(data)
            media_pool_item.SetMetadata(
                constants.AYON_TAG_NAME, json.dumps(tag_data))
        else:
            tag_data = data
            # if ayon tag available then update with input data
            # add it to the input track item
            timeline_item.SetMetadata(
                constants.AYON_TAG_NAME, json.dumps(tag_data))

    return tag_data

swap_clips(from_clip, to_clip, to_in_frame, to_out_frame)

Swapping clips on timeline in timelineItem

It will add take and activate it to the frame range which is inputted

Parameters:

Name Type Description Default
to_clip_name str

name of to_clip

required
to_in_frame float

cut in frame, usually GetLeftOffset()

required
to_out_frame float

cut out frame, usually left offset plus duration

required

Returns:

Name Type Description
bool

True if successfully replaced

Source code in client/ayon_resolve/api/lib.py
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
def swap_clips(from_clip, to_clip, to_in_frame, to_out_frame):
    """
    Swapping clips on timeline in timelineItem

    It will add take and activate it to the frame range which is inputted

    Args:
        from_clip (resolve.TimelineItem)
        to_clip (resolve.mediaPoolItem)
        to_clip_name (str): name of to_clip
        to_in_frame (float): cut in frame, usually `GetLeftOffset()`
        to_out_frame (float): cut out frame, usually left offset plus duration

    Returns:
        bool: True if successfully replaced

    """
    # copy ACES input transform from timeline clip to new media item
    mediapool_item_from_timeline = from_clip.GetMediaPoolItem()
    _idt = mediapool_item_from_timeline.GetClipProperty('IDT')
    to_clip.SetClipProperty('IDT', _idt)

    _clip_prop = to_clip.GetClipProperty
    to_clip_name = _clip_prop("File Name")
    # add clip item as take to timeline
    take = from_clip.AddTake(
        to_clip,
        float(to_in_frame),
        float(to_out_frame)
    )

    if not take:
        return False

    for take_index in range(1, (int(from_clip.GetTakesCount()) + 1)):
        take_item = from_clip.GetTakeByIndex(take_index)
        take_mp_item = take_item["mediaPoolItem"]
        if to_clip_name in take_mp_item.GetName():
            from_clip.SelectTakeByIndex(take_index)
            from_clip.FinalizeTake()
            return True
    return False

update_container(timeline_item, data=None)

Update container data to input timeline_item's ayon marker data.

Parameters:

Name Type Description Default
timeline_item TimelineItem

A containerized track item.

required
data dict)[optional]

dictionary with data to be updated

None

Returns:

Name Type Description
bool

True if container was updated correctly

Source code in client/ayon_resolve/api/pipeline.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def update_container(timeline_item, data=None):
    """Update container data to input timeline_item's ayon marker data.

    Args:
        timeline_item (resolve.TimelineItem): A containerized track item.
        data (dict)[optional]: dictionary with data to be updated

    Returns:
        bool: True if container was updated correctly

    """
    data = data or {}

    container = lib.get_timeline_item_ayon_tag(timeline_item)

    for _key, _value in container.items():
        try:
            container[_key] = data[_key]
        except KeyError:
            pass

    log.info("Updating container: `{}`".format(timeline_item))
    return bool(lib.set_timeline_item_ayon_tag(timeline_item, container))