Merge pull request #932 from pypeclub/feature/914-dv-resolve-loading-and-updating-image-seqeunce

Resolve - loading and updating clips
This commit is contained in:
Milan Kolar 2021-02-16 20:06:57 +01:00 committed by GitHub
commit bab3a2a45c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 1524 additions and 601 deletions

View file

@ -1 +1,26 @@
#### Basic setup
- Install [latest DaVinci Resolve](https://sw.blackmagicdesign.com/DaVinciResolve/v16.2.8/DaVinci_Resolve_Studio_16.2.8_Windows.zip?Key-Pair-Id=APKAJTKA3ZJMJRQITVEA&Signature=EcFuwQFKHZIBu2zDj5LTCQaQDXcKOjhZY7Fs07WGw24xdDqfwuALOyKu+EVzDX2Tik0cWDunYyV0r7hzp+mHmczp9XP4YaQXHdyhD/2BGWDgiMsiTQbNkBgbfy5MsAMFY8FHCl724Rxm8ke1foWeUVyt/Cdkil+ay+9sL72yFhaSV16sncko1jCIlCZeMkHhbzqPwyRuqLGmxmp8ey9KgBhI3wGFFPN201VMaV+RHrpX+KAfaR6p6dwo3FrPbRHK9TvMI1RA/1lJ3fVtrkDW69LImIKAWmIxgcStUxR9/taqLOD66FNiflHd1tufHv3FBa9iYQsjb3VLMPx7OCwLyg==&Expires=1608308139)
- add absolute path to ffmpeg into pype settings
![image](https://user-images.githubusercontent.com/40640033/102630786-43294f00-414d-11eb-98de-f0ae51f62077.png)
- install Python 3.6 into `%LOCALAPPDATA%/Programs/Python/Python36` (only respected path by Resolve)
- install OpenTimelineIO for 3.6 `%LOCALAPPDATA%\Programs\Python\Python36\python.exe -m pip install git+https://github.com/PixarAnimationStudios/OpenTimelineIO.git@5aa24fbe89d615448876948fe4b4900455c9a3e8` and move builded files from `%LOCALAPPDATA%/Programs/Python/Python36/Lib/site-packages/opentimelineio/cxx-libs/bin and lib` to `%LOCALAPPDATA%/Programs/Python/Python36/Lib/site-packages/opentimelineio/`. I was building it on Win10 machine with Visual Studio Community 2019 and
![image](https://user-images.githubusercontent.com/40640033/102792588-ffcb1c80-43a8-11eb-9c6b-bf2114ed578e.png) with installed CMake in PATH.
- install PySide2 for 3.6 `%LOCALAPPDATA%\Programs\Python\Python36\python.exe -m pip install PySide2`
- make sure Resovle Fusion (Fusion Tab/menu/Fusion/Fusion Setings) is set to Python 3.6
![image](https://user-images.githubusercontent.com/40640033/102631545-280b0f00-414e-11eb-89fc-98ac268d209d.png)
#### Editorial setup
This is how it looks on my testing project timeline
![image](https://user-images.githubusercontent.com/40640033/102637638-96ec6600-4156-11eb-9656-6e8e3ce4baf8.png)
Notice I had renamed tracks to `main` (holding metadata markers) and `review` used for generating review data with ffmpeg confersion to jpg sequence.
1. you need to start Pype menu from Resolve/EditTab/Menu/Workspace/Scripts/**PYPE_MENU**
2. then select any clips in `main` track and change their color to `Chocolate`
3. in Pype Menu select `Create`
4. in Creator select `Create Publishable Clip [New]` (temporary name)
5. set `Rename clips` to True, Master Track to `main` and Use review track to `review` as in picture
![image](https://user-images.githubusercontent.com/40640033/102643773-0d419600-4160-11eb-919e-9c2be0aecab8.png)
6. after you hit `ok` all clips are colored to `ping` and marked with pype metadata tag
7. git `Publish` on pype menu and see that all had been collected correctly. That is the last step for now as rest is Work in progress. Next steps will follow.

View file

@ -0,0 +1,461 @@
Updated as of 20 October 2020
-----------------------------
In this package, you will find a brief introduction to the Scripting API for DaVinci Resolve Studio. Apart from this README.txt file, this package contains folders containing the basic import
modules for scripting access (DaVinciResolve.py) and some representative examples.
From v16.2.0 onwards, the nodeIndex parameters accepted by SetLUT() and SetCDL() are 1-based instead of 0-based, i.e. 1 <= nodeIndex <= total number of nodes.
Overview
--------
As with Blackmagic Design Fusion scripts, user scripts written in Lua and Python programming languages are supported. By default, scripts can be invoked from the Console window in the Fusion page,
or via command line. This permission can be changed in Resolve Preferences, to be only from Console, or to be invoked from the local network. Please be aware of the security implications when
allowing scripting access from outside of the Resolve application.
Prerequisites
-------------
DaVinci Resolve scripting requires one of the following to be installed (for all users):
Lua 5.1
Python 2.7 64-bit
Python 3.6 64-bit
Using a script
--------------
DaVinci Resolve needs to be running for a script to be invoked.
For a Resolve script to be executed from an external folder, the script needs to know of the API location.
You may need to set the these environment variables to allow for your Python installation to pick up the appropriate dependencies as shown below:
Mac OS X:
RESOLVE_SCRIPT_API="/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting"
RESOLVE_SCRIPT_LIB="/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"
PYTHONPATH="$PYTHONPATH:$RESOLVE_SCRIPT_API/Modules/"
Windows:
RESOLVE_SCRIPT_API="%PROGRAMDATA%\Blackmagic Design\DaVinci Resolve\Support\Developer\Scripting"
RESOLVE_SCRIPT_LIB="C:\Program Files\Blackmagic Design\DaVinci Resolve\fusionscript.dll"
PYTHONPATH="%PYTHONPATH%;%RESOLVE_SCRIPT_API%\Modules\"
Linux:
RESOLVE_SCRIPT_API="/opt/resolve/Developer/Scripting"
RESOLVE_SCRIPT_LIB="/opt/resolve/libs/Fusion/fusionscript.so"
PYTHONPATH="$PYTHONPATH:$RESOLVE_SCRIPT_API/Modules/"
(Note: For standard ISO Linux installations, the path above may need to be modified to refer to /home/resolve instead of /opt/resolve)
As with Fusion scripts, Resolve scripts can also be invoked via the menu and the Console.
On startup, DaVinci Resolve scans the subfolders in the directories shown below and enumerates the scripts found in the Workspace application menu under Scripts.
Place your script under Utility to be listed in all pages, under Comp or Tool to be available in the Fusion page or under folders for individual pages (Edit, Color or Deliver). Scripts under Deliver are additionally listed under render jobs.
Placing your script here and invoking it from the menu is the easiest way to use scripts.
Mac OS X:
- All users: /Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts
- Specific user: /Users/<UserName>/Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts
Windows:
- All users: %PROGRAMDATA%\Blackmagic Design\DaVinci Resolve\Fusion\Scripts
- Specific user: %APPDATA%\Roaming\Blackmagic Design\DaVinci Resolve\Support\Fusion\Scripts
Linux:
- All users: /opt/resolve/Fusion/Scripts (or /home/resolve/Fusion/Scripts/ depending on installation)
- Specific user: $HOME/.local/share/DaVinciResolve/Fusion/Scripts
The interactive Console window allows for an easy way to execute simple scripting commands, to query or modify properties, and to test scripts. The console accepts commands in Python 2.7, Python 3.6
and Lua and evaluates and executes them immediately. For more information on how to use the Console, please refer to the DaVinci Resolve User Manual.
This example Python script creates a simple project:
#!/usr/bin/env python
import DaVinciResolveScript as dvr_script
resolve = dvr_script.scriptapp("Resolve")
fusion = resolve.Fusion()
projectManager = resolve.GetProjectManager()
projectManager.CreateProject("Hello World")
The resolve object is the fundamental starting point for scripting via Resolve. As a native object, it can be inspected for further scriptable properties - using table iteration and "getmetatable"
in Lua and dir, help etc in Python (among other methods). A notable scriptable object above is fusion - it allows access to all existing Fusion scripting functionality.
Running DaVinci Resolve in headless mode
----------------------------------------
DaVinci Resolve can be launched in a headless mode without the user interface using the -nogui command line option. When DaVinci Resolve is launched using this option, the user interface is disabled.
However, the various scripting APIs will continue to work as expected.
Basic Resolve API
-----------------
Some commonly used API functions are described below (*). As with the resolve object, each object is inspectable for properties and functions.
Resolve
Fusion() --> Fusion # Returns the Fusion object. Starting point for Fusion scripts.
GetMediaStorage() --> MediaStorage # Returns the media storage object to query and act on media locations.
GetProjectManager() --> ProjectManager # Returns the project manager object for currently open database.
OpenPage(pageName) --> None # Switches to indicated page in DaVinci Resolve. Input can be one of ("media", "cut", "edit", "fusion", "color", "fairlight", "deliver").
GetProductName() --> string # Returns product name.
GetVersion() --> [version fields] # Returns list of product version fields in [major, minor, patch, build, suffix] format.
GetVersionString() --> string # Returns product version in "major.minor.patch[suffix].build" format.
ProjectManager
CreateProject(projectName) --> Project # Creates and returns a project if projectName (string) is unique, and None if it is not.
DeleteProject(projectName) --> Bool # Delete project in the current folder if not currently loaded
LoadProject(projectName) --> Project # Loads and returns the project with name = projectName (string) if there is a match found, and None if there is no matching Project.
GetCurrentProject() --> Project # Returns the currently loaded Resolve project.
SaveProject() --> Bool # Saves the currently loaded project with its own name. Returns True if successful.
CloseProject(project) --> Bool # Closes the specified project without saving.
CreateFolder(folderName) --> Bool # Creates a folder if folderName (string) is unique.
DeleteFolder(folderName) --> Bool # Deletes the specified folder if it exists. Returns True in case of success.
GetProjectListInCurrentFolder() --> [project names...] # Returns a list of project names in current folder.
GetFolderListInCurrentFolder() --> [folder names...] # Returns a list of folder names in current folder.
GotoRootFolder() --> Bool # Opens root folder in database.
GotoParentFolder() --> Bool # Opens parent folder of current folder in database if current folder has parent.
GetCurrentFolder() --> string # Returns the current folder name.
OpenFolder(folderName) --> Bool # Opens folder under given name.
ImportProject(filePath) --> Bool # Imports a project from the file path provided. Returns True if successful.
ExportProject(projectName, filePath, withStillsAndLUTs=True) --> Bool # Exports project to provided file path, including stills and LUTs if withStillsAndLUTs is True (enabled by default). Returns True in case of success.
RestoreProject(filePath) --> Bool # Restores a project from the file path provided. Returns True if successful.
GetCurrentDatabase() --> {dbInfo} # Returns a dictionary (with keys 'DbType', 'DbName' and optional 'IpAddress') corresponding to the current database connection
GetDatabaseList() --> [{dbInfo}] # Returns a list of dictionary items (with keys 'DbType', 'DbName' and optional 'IpAddress') corresponding to all the databases added to Resolve
SetCurrentDatabase({dbInfo}) --> Bool # Switches current database connection to the database specified by the keys below, and closes any open project.
# 'DbType': 'Disk' or 'PostgreSQL' (string)
# 'DbName': database name (string)
# 'IpAddress': IP address of the PostgreSQL server (string, optional key - defaults to '127.0.0.1')
Project
GetMediaPool() --> MediaPool # Returns the Media Pool object.
GetTimelineCount() --> int # Returns the number of timelines currently present in the project.
GetTimelineByIndex(idx) --> Timeline # Returns timeline at the given index, 1 <= idx <= project.GetTimelineCount()
GetCurrentTimeline() --> Timeline # Returns the currently loaded timeline.
SetCurrentTimeline(timeline) --> Bool # Sets given timeline as current timeline for the project. Returns True if successful.
GetName() --> string # Returns project name.
SetName(projectName) --> Bool # Sets project name if given projectname (string) is unique.
GetPresetList() --> [presets...] # Returns a list of presets and their information.
SetPreset(presetName) --> Bool # Sets preset by given presetName (string) into project.
AddRenderJob() --> string # Adds a render job based on current render settings to the render queue. Returns a unique job id (string) for the new render job.
DeleteRenderJob(jobId) --> Bool # Deletes render job for input job id (string).
DeleteAllRenderJobs() --> Bool # Deletes all render jobs in the queue.
GetRenderJobList() --> [render jobs...] # Returns a list of render jobs and their information.
GetRenderPresetList() --> [presets...] # Returns a list of render presets and their information.
StartRendering(jobId1, jobId2, ...) --> Bool # Starts rendering jobs indicated by the input job ids.
StartRendering([jobIds...], isInteractiveMode=False) --> Bool # Starts rendering jobs indicated by the input job ids.
# The optional "isInteractiveMode", when set, enables error feedback in the UI during rendering.
StartRendering(isInteractiveMode=False) --> Bool # Starts rendering all queued render jobs.
# The optional "isInteractiveMode", when set, enables error feedback in the UI during rendering.
StopRendering() --> None # Stops any current render processes.
IsRenderingInProgress() --> Bool # Returns True if rendering is in progress.
LoadRenderPreset(presetName) --> Bool # Sets a preset as current preset for rendering if presetName (string) exists.
SaveAsNewRenderPreset(presetName) --> Bool # Creates new render preset by given name if presetName(string) is unique.
SetRenderSettings({settings}) --> Bool # Sets given settings for rendering. Settings is a dict, with support for the keys:
# "SelectAllFrames": Bool
# "MarkIn": int
# "MarkOut": int
# "TargetDir": string
# "CustomName": string
# "UniqueFilenameStyle": 0 - Prefix, 1 - Suffix.
# "ExportVideo": Bool
# "ExportAudio": Bool
# "FormatWidth": int
# "FormatHeight": int
# "FrameRate": float (examples: 23.976, 24)
# "PixelAspectRatio": string (for SD resolution: "16_9" or "4_3") (other resolutions: "square" or "cinemascope")
# "VideoQuality" possible values for current codec (if applicable):
# 0 (int) - will set quality to automatic
# [1 -> MAX] (int) - will set input bit rate
# ["Least", "Low", "Medium", "High", "Best"] (String) - will set input quality level
# "AudioCodec": string (example: "aac")
# "AudioBitDepth": int
# "AudioSampleRate": int
# "ColorSpaceTag" : string (example: "Same as Project", "AstroDesign")
# "GammaTag" : string (example: "Same as Project", "ACEScct")
GetRenderJobStatus(jobId) --> {status info} # Returns a dict with job status and completion percentage of the job by given jobId (string).
GetSetting(settingName) --> string # Returns value of project setting (indicated by settingName, string). Check the section below for more information.
SetSetting(settingName, settingValue) --> Bool # Sets the project setting (indicated by settingName, string) to the value (settingValue, string). Check the section below for more information.
GetRenderFormats() --> {render formats..} # Returns a dict (format -> file extension) of available render formats.
GetRenderCodecs(renderFormat) --> {render codecs...} # Returns a dict (codec description -> codec name) of available codecs for given render format (string).
GetCurrentRenderFormatAndCodec() --> {format, codec} # Returns a dict with currently selected format 'format' and render codec 'codec'.
SetCurrentRenderFormatAndCodec(format, codec) --> Bool # Sets given render format (string) and render codec (string) as options for rendering.
GetCurrentRenderMode() --> int # Returns the render mode: 0 - Individual clips, 1 - Single clip.
SetCurrentRenderMode(renderMode) --> Bool # Sets the render mode. Specify renderMode = 0 for Individual clips, 1 for Single clip.
GetRenderResolutions(format, codec) --> [{Resolution}] # Returns list of resolutions applicable for the given render format (string) and render codec (string). Returns full list of resolutions if no argument is provided. Each element in the list is a dictionary with 2 keys "Width" and "Height".
RefreshLUTList() --> Bool # Refreshes LUT List
MediaStorage
GetMountedVolumeList() --> [paths...] # Returns list of folder paths corresponding to mounted volumes displayed in Resolves Media Storage.
GetSubFolderList(folderPath) --> [paths...] # Returns list of folder paths in the given absolute folder path.
GetFileList(folderPath) --> [paths...] # Returns list of media and file listings in the given absolute folder path. Note that media listings may be logically consolidated entries.
RevealInStorage(path) --> None # Expands and displays given file/folder path in Resolves Media Storage.
AddItemListToMediaPool(item1, item2, ...) --> [clips...] # Adds specified file/folder paths from Media Storage into current Media Pool folder. Input is one or more file/folder paths. Returns a list of the MediaPoolItems created.
AddItemListToMediaPool([items...]) --> [clips...] # Adds specified file/folder paths from Media Storage into current Media Pool folder. Input is an array of file/folder paths. Returns a list of the MediaPoolItems created.
AddClipMattesToMediaPool(MediaPoolItem, [paths], stereoEye) --> Bool # Adds specified media files as mattes for the specified MediaPoolItem. StereoEye is an optional argument for specifying which eye to add the matte to for stereo clips ("left" or "right"). Returns True if successful.
AddTimelineMattesToMediaPool([paths]) --> [MediaPoolItems] # Adds specified media files as timeline mattes in current media pool folder. Returns a list of created MediaPoolItems.
MediaPool
GetRootFolder() --> Folder # Returns root Folder of Media Pool
AddSubFolder(folder, name) --> Folder # Adds new subfolder under specified Folder object with the given name.
CreateEmptyTimeline(name) --> Timeline # Adds new timeline with given name.
AppendToTimeline(clip1, clip2, ...) --> Bool # Appends specified MediaPoolItem objects in the current timeline. Returns True if successful.
AppendToTimeline([clips]) --> Bool # Appends specified MediaPoolItem objects in the current timeline. Returns True if successful.
AppendToTimeline([{clipInfo}, ...]) --> Bool # Appends list of clipInfos specified as dict of "mediaPoolItem", "startFrame" (int), "endFrame" (int).
CreateTimelineFromClips(name, clip1, clip2,...) --> Timeline # Creates new timeline with specified name, and appends the specified MediaPoolItem objects.
CreateTimelineFromClips(name, [clips]) --> Timeline # Creates new timeline with specified name, and appends the specified MediaPoolItem objects.
CreateTimelineFromClips(name, [{clipInfo}]) --> Timeline # Creates new timeline with specified name, appending the list of clipInfos specified as a dict of "mediaPoolItem", "startFrame" (int), "endFrame" (int).
ImportTimelineFromFile(filePath, {importOptions}) --> Timeline # Creates timeline based on parameters within given file and optional importOptions dict, with support for the keys:
# "timelineName": string, specifies the name of the timeline to be created
# "importSourceClips": Bool, specifies whether source clips should be imported, True by default
# "sourceClipsPath": string, specifies a filesystem path to search for source clips if the media is inaccessible in their original path and if "importSourceClips" is True
# "sourceClipsFolders": List of Media Pool folder objects to search for source clips if the media is not present in current folder and if "importSourceClips" is False
GetCurrentFolder() --> Folder # Returns currently selected Folder.
SetCurrentFolder(Folder) --> Bool # Sets current folder by given Folder.
DeleteClips([clips]) --> Bool # Deletes specified clips or timeline mattes in the media pool
DeleteFolders([subfolders]) --> Bool # Deletes specified subfolders in the media pool
MoveClips([clips], targetFolder) --> Bool # Moves specified clips to target folder.
MoveFolders([folders], targetFolder) --> Bool # Moves specified folders to target folder.
GetClipMatteList(MediaPoolItem) --> [paths] # Get mattes for specified MediaPoolItem, as a list of paths to the matte files.
GetTimelineMatteList(Folder) --> [MediaPoolItems] # Get mattes in specified Folder, as list of MediaPoolItems.
DeleteClipMattes(MediaPoolItem, [paths]) --> Bool # Delete mattes based on their file paths, for specified MediaPoolItem. Returns True on success.
RelinkClips([MediaPoolItem], folderPath) --> Bool # Update the folder location of specified media pool clips with the specified folder path.
UnlinkClips([MediaPoolItem]) --> Bool # Unlink specified media pool clips.
ImportMedia([items...]) --> [MediaPoolItems] # Imports specified file/folder paths into current Media Pool folder. Input is an array of file/folder paths. Returns a list of the MediaPoolItems created.
ExportMetadata(fileName, [clips]) --> Bool # Exports metadata of specified clips to 'fileName' in CSV format.
# If no clips are specified, all clips from media pool will be used.
Folder
GetClipList() --> [clips...] # Returns a list of clips (items) within the folder.
GetName() --> string # Returns the media folder name.
GetSubFolderList() --> [folders...] # Returns a list of subfolders in the folder.
MediaPoolItem
GetName() --> string # Returns the clip name.
GetMetadata(metadataType=None) --> string|dict # Returns the metadata value for the key 'metadataType'.
# If no argument is specified, a dict of all set metadata properties is returned.
SetMetadata(metadataType, metadataValue) --> Bool # Sets the given metadata to metadataValue (string). Returns True if successful.
GetMediaId() --> string # Returns the unique ID for the MediaPoolItem.
AddMarker(frameId, color, name, note, duration, --> Bool # Creates a new marker at given frameId position and with given marker information. 'customData' is optional and helps to attach user specific data to the marker.
customData)
GetMarkers() --> {markers...} # Returns a dict (frameId -> {information}) of all markers and dicts with their information.
# Example of output format: {96.0: {'color': 'Green', 'duration': 1.0, 'note': '', 'name': 'Marker 1', 'customData': ''}, ...}
# In the above example - there is one 'Green' marker at offset 96 (position of the marker)
GetMarkerByCustomData(customData) --> {markers...} # Returns marker {information} for the first matching marker with specified customData.
UpdateMarkerCustomData(frameId, customData) --> Bool # Updates customData (string) for the marker at given frameId position. CustomData is not exposed via UI and is useful for scripting developer to attach any user specific data to markers.
GetMarkerCustomData(frameId) --> string # Returns customData string for the marker at given frameId position.
DeleteMarkersByColor(color) --> Bool # Delete all markers of the specified color from the media pool item. "All" as argument deletes all color markers.
DeleteMarkerAtFrame(frameNum) --> Bool # Delete marker at frame number from the media pool item.
DeleteMarkerByCustomData(customData) --> Bool # Delete first matching marker with specified customData.
AddFlag(color) --> Bool # Adds a flag with given color (string).
GetFlagList() --> [colors...] # Returns a list of flag colors assigned to the item.
ClearFlags(color) --> Bool # Clears the flag of the given color if one exists. An "All" argument is supported and clears all flags.
GetClipColor() --> string # Returns the item color as a string.
SetClipColor(colorName) --> Bool # Sets the item color based on the colorName (string).
ClearClipColor() --> Bool # Clears the item color.
GetClipProperty(propertyName=None) --> string|dict # Returns the property value for the key 'propertyName'.
# If no argument is specified, a dict of all clip properties is returned. Check the section below for more information.
SetClipProperty(propertyName, propertyValue) --> Bool # Sets the given property to propertyValue (string). Check the section below for more information.
LinkProxyMedia(propertyName) --> Bool # Links proxy media (absolute path) with the current clip.
UnlinkProxyMedia() --> Bool # Unlinks any proxy media associated with clip.
ReplaceClip(filePath) --> Bool # Replaces the underlying asset and metadata of MediaPoolItem with the specified absolute clip path.
Timeline
GetName() --> string # Returns the timeline name.
SetName(timelineName) --> Bool # Sets the timeline name if timelineName (string) is unique. Returns True if successful.
GetStartFrame() --> int # Returns the frame number at the start of timeline.
GetEndFrame() --> int # Returns the frame number at the end of timeline.
GetTrackCount(trackType) --> int # Returns the number of tracks for the given track type ("audio", "video" or "subtitle").
GetItemListInTrack(trackType, index) --> [items...] # Returns a list of timeline items on that track (based on trackType and index). 1 <= index <= GetTrackCount(trackType).
AddMarker(frameId, color, name, note, duration, --> Bool # Creates a new marker at given frameId position and with given marker information. 'customData' is optional and helps to attach user specific data to the marker.
customData)
GetMarkers() --> {markers...} # Returns a dict (frameId -> {information}) of all markers and dicts with their information.
# Example: a value of {96.0: {'color': 'Green', 'duration': 1.0, 'note': '', 'name': 'Marker 1', 'customData': ''}, ...} indicates a single green marker at timeline offset 96
GetMarkerByCustomData(customData) --> {markers...} # Returns marker {information} for the first matching marker with specified customData.
UpdateMarkerCustomData(frameId, customData) --> Bool # Updates customData (string) for the marker at given frameId position. CustomData is not exposed via UI and is useful for scripting developer to attach any user specific data to markers.
GetMarkerCustomData(frameId) --> string # Returns customData string for the marker at given frameId position.
DeleteMarkersByColor(color) --> Bool # Deletes all timeline markers of the specified color. An "All" argument is supported and deletes all timeline markers.
DeleteMarkerAtFrame(frameNum) --> Bool # Deletes the timeline marker at the given frame number.
DeleteMarkerByCustomData(customData) --> Bool # Delete first matching marker with specified customData.
ApplyGradeFromDRX(path, gradeMode, item1, item2, ...)--> Bool # Loads a still from given file path (string) and applies grade to Timeline Items with gradeMode (int): 0 - "No keyframes", 1 - "Source Timecode aligned", 2 - "Start Frames aligned".
ApplyGradeFromDRX(path, gradeMode, [items]) --> Bool # Loads a still from given file path (string) and applies grade to Timeline Items with gradeMode (int): 0 - "No keyframes", 1 - "Source Timecode aligned", 2 - "Start Frames aligned".
GetCurrentTimecode() --> string # Returns a string timecode representation for the current playhead position, while on Cut, Edit, Color and Deliver pages.
GetCurrentVideoItem() --> item # Returns the current video timeline item.
GetCurrentClipThumbnailImage() --> {thumbnailData} # Returns a dict (keys "width", "height", "format" and "data") with data containing raw thumbnail image data (RGB 8-bit image data encoded in base64 format) for current media in the Color Page.
# An example of how to retrieve and interpret thumbnails is provided in 6_get_current_media_thumbnail.py in the Examples folder.
GetTrackName(trackType, trackIndex) --> string # Returns the track name for track indicated by trackType ("audio", "video" or "subtitle") and index. 1 <= trackIndex <= GetTrackCount(trackType).
SetTrackName(trackType, trackIndex, name) --> Bool # Sets the track name (string) for track indicated by trackType ("audio", "video" or "subtitle") and index. 1 <= trackIndex <= GetTrackCount(trackType).
DuplicateTimeline(timelineName) --> timeline # Duplicates the timeline and returns the created timeline, with the (optional) timelineName, on success.
CreateCompoundClip([timelineItems], {clipInfo}) --> timelineItem # Creates a compound clip of input timeline items with an optional clipInfo map: {"startTimecode" : "00:00:00:00", "name" : "Compound Clip 1"}. It returns the created timeline item.
CreateFusionClip([timelineItems]) --> timelineItem # Creates a Fusion clip of input timeline items. It returns the created timeline item.
Export(fileName, exportType, exportSubtype) --> Bool # Exports timeline to 'fileName' as per input exportType & exportSubtype format.
# exportType can be one of the following constants:
# resolve.EXPORT_AAF
# resolve.EXPORT_DRT
# resolve.EXPORT_EDL
# resolve.EXPORT_FCP_7_XML
# resolve.EXPORT_FCPXML_1_3
# resolve.EXPORT_FCPXML_1_4
# resolve.EXPORT_FCPXML_1_5
# resolve.EXPORT_FCPXML_1_6
# resolve.EXPORT_FCPXML_1_7
# resolve.EXPORT_FCPXML_1_8
# resolve.EXPORT_HDR_10_PROFILE_A
# resolve.EXPORT_HDR_10_PROFILE_B
# resolve.EXPORT_TEXT_CSV
# resolve.EXPORT_TEXT_TAB
# resolve.EXPORT_DOLBY_VISION_VER_2_9
# resolve.EXPORT_DOLBY_VISION_VER_4_0
# exportSubtype can be one of the following enums:
# resolve.EXPORT_NONE
# resolve.EXPORT_AAF_NEW
# resolve.EXPORT_AAF_EXISTING
# resolve.EXPORT_CDL
# resolve.EXPORT_SDL
# resolve.EXPORT_MISSING_CLIPS
# Please note that exportSubType is a required parameter for resolve.EXPORT_AAF and resolve.EXPORT_EDL. For rest of the exportType, exportSubtype is ignored.
# When exportType is resolve.EXPORT_AAF, valid exportSubtype values are resolve.EXPORT_AAF_NEW and resolve.EXPORT_AAF_EXISTING.
# When exportType is resolve.EXPORT_EDL, valid exportSubtype values are resolve.EXPORT_CDL, resolve.EXPORT_SDL, resolve.EXPORT_MISSING_CLIPS and resolve.EXPORT_NONE.
# Note: Replace 'resolve.' when using the constants above, if a different Resolve class instance name is used.
GetSetting(settingName) --> string # Returns value of timeline setting (indicated by settingName : string). Check the section below for more information.
SetSetting(settingName, settingValue) --> Bool # Sets timeline setting (indicated by settingName : string) to the value (settingValue : string). Check the section below for more information.
TimelineItem
GetName() --> string # Returns the item name.
GetDuration() --> int # Returns the item duration.
GetEnd() --> int # Returns the end frame position on the timeline.
GetFusionCompCount() --> int # Returns number of Fusion compositions associated with the timeline item.
GetFusionCompByIndex(compIndex) --> fusionComp # Returns the Fusion composition object based on given index. 1 <= compIndex <= timelineItem.GetFusionCompCount()
GetFusionCompNameList() --> [names...] # Returns a list of Fusion composition names associated with the timeline item.
GetFusionCompByName(compName) --> fusionComp # Returns the Fusion composition object based on given name.
GetLeftOffset() --> int # Returns the maximum extension by frame for clip from left side.
GetRightOffset() --> int # Returns the maximum extension by frame for clip from right side.
GetStart() --> int # Returns the start frame position on the timeline.
AddMarker(frameId, color, name, note, duration, --> Bool # Creates a new marker at given frameId position and with given marker information. 'customData' is optional and helps to attach user specific data to the marker.
customData)
GetMarkers() --> {markers...} # Returns a dict (frameId -> {information}) of all markers and dicts with their information.
# Example: a value of {96.0: {'color': 'Green', 'duration': 1.0, 'note': '', 'name': 'Marker 1', 'customData': ''}, ...} indicates a single green marker at clip offset 96
GetMarkerByCustomData(customData) --> {markers...} # Returns marker {information} for the first matching marker with specified customData.
UpdateMarkerCustomData(frameId, customData) --> Bool # Updates customData (string) for the marker at given frameId position. CustomData is not exposed via UI and is useful for scripting developer to attach any user specific data to markers.
GetMarkerCustomData(frameId) --> string # Returns customData string for the marker at given frameId position.
DeleteMarkersByColor(color) --> Bool # Delete all markers of the specified color from the timeline item. "All" as argument deletes all color markers.
DeleteMarkerAtFrame(frameNum) --> Bool # Delete marker at frame number from the timeline item.
DeleteMarkerByCustomData(customData) --> Bool # Delete first matching marker with specified customData.
AddFlag(color) --> Bool # Adds a flag with given color (string).
GetFlagList() --> [colors...] # Returns a list of flag colors assigned to the item.
ClearFlags(color) --> Bool # Clear flags of the specified color. An "All" argument is supported to clear all flags.
GetClipColor() --> string # Returns the item color as a string.
SetClipColor(colorName) --> Bool # Sets the item color based on the colorName (string).
ClearClipColor() --> Bool # Clears the item color.
AddFusionComp() --> fusionComp # Adds a new Fusion composition associated with the timeline item.
ImportFusionComp(path) --> fusionComp # Imports a Fusion composition from given file path by creating and adding a new composition for the item.
ExportFusionComp(path, compIndex) --> Bool # Exports the Fusion composition based on given index to the path provided.
DeleteFusionCompByName(compName) --> Bool # Deletes the named Fusion composition.
LoadFusionCompByName(compName) --> fusionComp # Loads the named Fusion composition as the active composition.
RenameFusionCompByName(oldName, newName) --> Bool # Renames the Fusion composition identified by oldName.
AddVersion(versionName, versionType) --> Bool # Adds a new color version for a video clipbased on versionType (0 - local, 1 - remote).
DeleteVersionByName(versionName, versionType) --> Bool # Deletes a color version by name and versionType (0 - local, 1 - remote).
LoadVersionByName(versionName, versionType) --> Bool # Loads a named color version as the active version. versionType: 0 - local, 1 - remote.
RenameVersionByName(oldName, newName, versionType)--> Bool # Renames the color version identified by oldName and versionType (0 - local, 1 - remote).
GetVersionNameList(versionType) --> [names...] # Returns a list of all color versions for the given versionType (0 - local, 1 - remote).
GetMediaPoolItem() --> MediaPoolItem # Returns the media pool item corresponding to the timeline item if one exists.
GetStereoConvergenceValues() --> {keyframes...} # Returns a dict (offset -> value) of keyframe offsets and respective convergence values.
GetStereoLeftFloatingWindowParams() --> {keyframes...} # For the LEFT eye -> returns a dict (offset -> dict) of keyframe offsets and respective floating window params. Value at particular offset includes the left, right, top and bottom floating window values.
GetStereoRightFloatingWindowParams() --> {keyframes...} # For the RIGHT eye -> returns a dict (offset -> dict) of keyframe offsets and respective floating window params. Value at particular offset includes the left, right, top and bottom floating window values.
SetLUT(nodeIndex, lutPath) --> Bool # Sets LUT on the node mapping the node index provided, 1 <= nodeIndex <= total number of nodes.
# The lutPath can be an absolute path, or a relative path (based off custom LUT paths or the master LUT path).
# The operation is successful for valid lut paths that Resolve has already discovered (see Project.RefreshLUTList).
SetCDL([CDL map]) --> Bool # Keys of map are: "NodeIndex", "Slope", "Offset", "Power", "Saturation", where 1 <= NodeIndex <= total number of nodes.
# Example python code - SetCDL({"NodeIndex" : "1", "Slope" : "0.5 0.4 0.2", "Offset" : "0.4 0.3 0.2", "Power" : "0.6 0.7 0.8", "Saturation" : "0.65"})
AddTake(mediaPoolItem, startFrame=0, endFrame)=0 --> Bool # Adds mediaPoolItem as a new take. Initializes a take selector for the timeline item if needed. By default, the whole clip is added. startFrame and endFrame can be specified as extents.
GetSelectedTakeIndex() --> int # Returns the index of the currently selected take, or 0 if the clip is not a take selector.
GetTakesCount() --> int # Returns the number of takes in take selector, or 0 if the clip is not a take selector.
GetTakeByIndex(idx) --> {takeInfo...} # Returns a dict (keys "startFrame", "endFrame" and "mediaPoolItem") with take info for specified index.
DeleteTakeByIndex(idx) --> Bool # Deletes a take by index, 1 <= idx <= number of takes.
SelectTakeByIndex(idx) --> Bool # Selects a take by index, 1 <= idx <= number of takes.
FinalizeTake() --> Bool # Finalizes take selection.
CopyGrades([tgtTimelineItems]) --> Bool # Copies the current grade to all the items in tgtTimelineItems list. Returns True on success and False if any error occured.
List and Dict Data Structures
-----------------------------
Beside primitive data types, Resolve's Python API mainly uses list and dict data structures. Lists are denoted by [ ... ] and dicts are denoted by { ... } above.
As Lua does not support list and dict data structures, the Lua API implements "list" as a table with indices, e.g. { [1] = listValue1, [2] = listValue2, ... }.
Similarly the Lua API implements "dict" as a table with the dictionary key as first element, e.g. { [dictKey1] = dictValue1, [dictKey2] = dictValue2, ... }.
Looking up Project and Clip properties
--------------------------------------
This section covers additional notes for the functions "Project:GetSetting", "Project:SetSetting", "Timeline:GetSetting", "Timeline:SetSetting", "MediaPoolItem:GetClipProperty" and
"MediaPoolItem:SetClipProperty". These functions are used to get and set properties otherwise available to the user through the Project Settings and the Clip Attributes dialogs.
The functions follow a key-value pair format, where each property is identified by a key (the settingName or propertyName parameter) and possesses a value (typically a text value). Keys and values are
designed to be easily correlated with parameter names and values in the Resolve UI. Explicitly enumerated values for some parameters are listed below.
Some properties may be read only - these include intrinsic clip properties like date created or sample rate, and properties that can be disabled in specific application contexts (e.g. custom colorspaces
in an ACES workflow, or output sizing parameters when behavior is set to match timeline)
Getting values:
Invoke "Project:GetSetting", "Timeline:GetSetting" or "MediaPoolItem:GetClipProperty" with the appropriate property key. To get a snapshot of all queryable properties (keys and values), you can call
"Project:GetSetting", "Timeline:GetSetting" or "MediaPoolItem:GetClipProperty" without parameters (or with a NoneType or a blank property key). Using specific keys to query individual properties will
be faster. Note that getting a property using an invalid key will return a trivial result.
Setting values:
Invoke "Project:SetSetting", "Timeline:SetSetting" or "MediaPoolItem:SetClipProperty" with the appropriate property key and a valid value. When setting a parameter, please check the return value to
ensure the success of the operation. You can troubleshoot the validity of keys and values by setting the desired result from the UI and checking property snapshots before and after the change.
The following Project properties have specifically enumerated values:
"superScale" - the property value is an enumerated integer between 0 and 3 with these meanings: 0=Auto, 1=no scaling, and 2, 3 and 4 represent the Super Scale multipliers 2x, 3x and 4x.
Affects:
• x = Project:GetSetting('superScale') and Project:SetSetting('superScale', x)
"timelineFrameRate" - the property value is one of the frame rates available to the user in project settings under "Timeline frame rate" option. Drop Frame can be configured for supported frame rates
by appending the frame rate with "DF", e.g. "29.97 DF" will enable drop frame and "29.97" will disable drop frame
Affects:
• x = Project:GetSetting('timelineFrameRate') and Project:SetSetting('timelineFrameRate', x)
The following Clip properties have specifically enumerated values:
"superScale" - the property value is an enumerated integer between 1 and 3 with these meanings: 1=no scaling, and 2, 3 and 4 represent the Super Scale multipliers 2x, 3x and 4x.
Affects:
• x = MediaPoolItem:GetClipProperty('Super Scale') and MediaPoolItem:SetClipProperty('Super Scale', x)
Deprecated Resolve API Functions
--------------------------------
The following API functions are deprecated.
ProjectManager
GetProjectsInCurrentFolder() --> {project names...} # Returns a dict of project names in current folder.
GetFoldersInCurrentFolder() --> {folder names...} # Returns a dict of folder names in current folder.
Project
GetPresets() --> {presets...} # Returns a dict of presets and their information.
GetRenderJobs() --> {render jobs...} # Returns a dict of render jobs and their information.
GetRenderPresets() --> {presets...} # Returns a dict of render presets and their information.
MediaStorage
GetMountedVolumes() --> {paths...} # Returns a dict of folder paths corresponding to mounted volumes displayed in Resolves Media Storage.
GetSubFolders(folderPath) --> {paths...} # Returns a dict of folder paths in the given absolute folder path.
GetFiles(folderPath) --> {paths...} # Returns a dict of media and file listings in the given absolute folder path. Note that media listings may be logically consolidated entries.
AddItemsToMediaPool(item1, item2, ...) --> {clips...} # Adds specified file/folder paths from Media Storage into current Media Pool folder. Input is one or more file/folder paths. Returns a dict of the MediaPoolItems created.
AddItemsToMediaPool([items...]) --> {clips...} # Adds specified file/folder paths from Media Storage into current Media Pool folder. Input is an array of file/folder paths. Returns a dict of the MediaPoolItems created.
Folder
GetClips() --> {clips...} # Returns a dict of clips (items) within the folder.
GetSubFolders() --> {folders...} # Returns a dict of subfolders in the folder.
MediaPoolItem
GetFlags() --> {colors...} # Returns a dict of flag colors assigned to the item.
Timeline
GetItemsInTrack(trackType, index) --> {items...} # Returns a dict of Timeline items on the video or audio track (based on trackType) at specified
TimelineItem
GetFusionCompNames() --> {names...} # Returns a dict of Fusion composition names associated with the timeline item.
GetFlags() --> {colors...} # Returns a dict of flag colors assigned to the item.
GetVersionNames(versionType) --> {names...} # Returns a dict of version names by provided versionType: 0 - local, 1 - remote.
Unsupported Resolve API Functions
---------------------------------
The following API (functions and paraameters) are no longer supported.
Project
StartRendering(index1, index2, ...) --> Bool # Please use unique job ids (string) instead of indices.
StartRendering([idxs...]) --> Bool # Please use unique job ids (string) instead of indices.
DeleteRenderJobByIndex(idx) --> Bool # Please use unique job ids (string) instead of indices.
GetRenderJobStatus(idx) --> {status info} # Please use unique job ids (string) instead of indices.
GetSetting and SetSetting --> {} # settingName "videoMonitorUseRec601For422SDI" is no longer supported.
# Please use "videoMonitorUseMatrixOverrideFor422SDI" and "videoMonitorMatrixOverrideFor422SDI" instead.

View file

@ -1,47 +1,56 @@
from .utils import (
from .api.utils import (
setup,
get_resolve_module
)
from .pipeline import (
from .api.pipeline import (
install,
uninstall,
ls,
containerise,
update_container,
publish,
launch_workfiles_app,
maintained_selection
)
from .lib import (
from .api.lib import (
maintain_current_timeline,
publish_clip_color,
get_project_manager,
get_current_project,
get_current_sequence,
get_current_timeline,
create_bin,
get_media_pool_item,
create_media_pool_item,
create_timeline_item,
get_timeline_item,
get_video_track_names,
get_current_track_items,
get_track_item_pype_tag,
set_track_item_pype_tag,
get_current_timeline_items,
get_pype_timeline_item_by_name,
get_timeline_item_pype_tag,
set_timeline_item_pype_tag,
imprint,
set_publish_attribute,
get_publish_attribute,
create_current_sequence_media_bin,
create_compound_clip,
swap_clips,
get_pype_clip_metadata,
set_project_manager_to_folder_name,
get_reformated_path,
get_otio_clip_instance_data
get_otio_clip_instance_data,
get_reformated_path
)
from .menu import launch_pype_menu
from .api.menu import launch_pype_menu
from .plugin import (
from .api.plugin import (
ClipLoader,
TimelineItemLoader,
Creator,
PublishClip
)
from .workio import (
from .api.workio import (
open_file,
save_file,
current_file,
@ -50,8 +59,8 @@ from .workio import (
work_root
)
bmdvr = None
bmdvf = None
from .api.testing_utils import TestGUI
__all__ = [
# pipeline
@ -59,6 +68,7 @@ __all__ = [
"uninstall",
"ls",
"containerise",
"update_container",
"reload_pipeline",
"publish",
"launch_workfiles_app",
@ -69,29 +79,37 @@ __all__ = [
"get_resolve_module",
# lib
"maintain_current_timeline",
"publish_clip_color",
"get_project_manager",
"get_current_project",
"get_current_sequence",
"get_current_timeline",
"create_bin",
"get_media_pool_item",
"create_media_pool_item",
"create_timeline_item",
"get_timeline_item",
"get_video_track_names",
"get_current_track_items",
"get_track_item_pype_tag",
"set_track_item_pype_tag",
"get_current_timeline_items",
"get_pype_timeline_item_by_name",
"get_timeline_item_pype_tag",
"set_timeline_item_pype_tag",
"imprint",
"set_publish_attribute",
"get_publish_attribute",
"create_current_sequence_media_bin",
"create_compound_clip",
"swap_clips",
"get_pype_clip_metadata",
"set_project_manager_to_folder_name",
"get_reformated_path",
"get_otio_clip_instance_data",
"get_reformated_path",
# menu
"launch_pype_menu",
# plugin
"ClipLoader",
"TimelineItemLoader",
"Creator",
"PublishClip",
@ -103,7 +121,5 @@ __all__ = [
"file_extensions",
"work_root",
# singleton with black magic resolve module
"bmdvr",
"bmdvf"
"TestGUI"
]

View file

@ -0,0 +1,11 @@
"""
resolve api
"""
import os
bmdvr = None
bmdvf = None
API_DIR = os.path.dirname(os.path.abspath(__file__))
HOST_DIR = os.path.dirname(API_DIR)
PLUGINS_DIR = os.path.join(HOST_DIR, "plugins")

View file

@ -21,7 +21,7 @@ class SelectInvalidAction(pyblish.api.Action):
def process(self, context, plugin):
try:
from . import get_project_manager
from .lib import get_project_manager
pm = get_project_manager()
self.log.debug(pm)
except ImportError:

View file

@ -1,10 +1,12 @@
import sys
import json
import re
import os
import contextlib
from opentimelineio import opentime
import pype
from .otio import davinci_export as otio_export
from ..otio import davinci_export as otio_export
from pype.api import Logger
@ -12,6 +14,7 @@ log = Logger().get_logger(__name__)
self = sys.modules[__name__]
self.project_manager = None
self.media_storage = None
# Pype sequencial rename variables
self.rename_index = 0
@ -29,6 +32,43 @@ self.pype_marker_duration = 1
self.pype_marker_color = "Mint"
self.temp_marker_frame = None
# Pype default timeline
self.pype_timeline_name = "PypeTimeline"
@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_project()
working_timeline = from_timeline or project.GetCurrentTimeline()
# swith to the input timeline
project.SetCurrentTimeline(to_timeline)
try:
# do a work
yield
finally:
# put the original working timeline to context
project.SetCurrentTimeline(working_timeline)
def get_project_manager():
from . import bmdvr
@ -37,6 +77,13 @@ def get_project_manager():
return self.project_manager
def get_media_storage():
from . import bmdvr
if not self.media_storage:
self.media_storage = bmdvr.GetMediaStorage()
return self.media_storage
def get_current_project():
# initialize project manager
get_project_manager()
@ -44,57 +91,241 @@ def get_current_project():
return self.project_manager.GetCurrentProject()
def get_current_sequence():
def get_current_timeline(new=False):
# get current project
project = get_current_project()
if new:
media_pool = project.GetMediaPool()
new_timeline = media_pool.CreateEmptyTimeline(self.pype_timeline_name)
project.SetCurrentTimeline(new_timeline)
return project.GetCurrentTimeline()
def get_video_track_names():
def create_bin(name: str, root: object = None) -> 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
Returns:
object: resolve.Folder
"""
# get all variables
media_pool = get_current_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, child_bin or root_bin)
if child_bin:
return child_bin
else:
created_bin = None
for subfolder in root_bin.GetSubFolderList():
if subfolder.GetName() in name:
created_bin = subfolder
if not created_bin:
new_folder = media_pool.AddSubFolder(root_bin, name)
media_pool.SetCurrentFolder(new_folder)
else:
media_pool.SetCurrentFolder(created_bin)
return media_pool.GetCurrentFolder()
def create_media_pool_item(fpath: str,
root: object = None) -> object:
"""
Create media pool item.
Args:
fpath (str): absolute path to a file
root (resolve.Folder)[optional]: root folder / bin object
Returns:
object: resolve.MediaPoolItem
"""
# get all variables
media_storage = get_media_storage()
media_pool = get_current_project().GetMediaPool()
root_bin = root or media_pool.GetRootFolder()
# try to search in bin if the clip does not exist
existing_mpi = get_media_pool_item(fpath, root_bin)
if not existing_mpi:
media_pool_item = media_storage.AddItemsToMediaPool(fpath)
print(media_pool_item)
# pop the returned dict on first item as resolve data object is such
return media_pool_item.pop(1.0)
else:
return existing_mpi
def get_media_pool_item(fpath, root: object = None) -> object:
"""
Return clip if found in folder with use of input file path.
Args:
fpath (str): absolute path to a file
root (resolve.Folder)[optional]: root folder / bin object
Returns:
object: resolve.MediaPoolItem
"""
media_pool = get_current_project().GetMediaPool()
root = root or media_pool.GetRootFolder()
fname = os.path.basename(fpath)
for _mpi in root.GetClipList():
_mpi_name = _mpi.GetClipProperty("File Name")["File Name"]
_mpi_name = get_reformated_path(_mpi_name, first=True)
if fname in _mpi_name:
return _mpi
return None
def create_timeline_item(media_pool_item: object,
timeline: object = 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 (resolve.Timeline)[optional]: resolve's object
source_start (int)[optional]: media source input frame (sequence frame)
source_end (int)[optional]: media source output frame (sequence frame)
Returns:
object: resolve.TimelineItem
"""
# get all variables
project = get_current_project()
media_pool = project.GetMediaPool()
clip_property = media_pool_item.GetClipProperty()
clip_name = clip_property["File Name"]
timeline = timeline or get_current_timeline()
# 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}
# add source time range if input was given
if source_start is not None:
clip_data.update({"startFrame": source_start})
if source_end is not None:
clip_data.update({"endFrame": source_end})
print(clip_data)
print(clip_property)
# add to timeline
media_pool.AppendToTimeline([clip_data])
output_timeline_item = get_timeline_item(
media_pool_item, timeline)
assert output_timeline_item, AssertionError(
"Track Item with name `{}` doesnt exist on the timeline: `{}`".format(
clip_name, timeline.GetName()
))
return output_timeline_item
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_property = media_pool_item.GetClipProperty()
clip_name = clip_property["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 = _ti_data["clip"]["item"]
_ti_clip_property = _ti_clip.GetMediaPoolItem().GetClipProperty()
if clip_name in _ti_clip_property["File Name"]:
output_timeline_item = _ti_clip
return output_timeline_item
def get_video_track_names() -> list:
tracks = list()
track_type = "video"
sequence = get_current_sequence()
timeline = get_current_timeline()
# get all tracks count filtered by track type
selected_track_count = sequence.GetTrackCount(track_type)
selected_track_count = timeline.GetTrackCount(track_type)
# loop all tracks and get items
track_index: int
for track_index in range(1, (int(selected_track_count) + 1)):
track_name = sequence.GetTrackName("video", track_index)
track_name = timeline.GetTrackName("video", track_index)
tracks.append(track_name)
return tracks
def get_current_track_items(
filter=False,
track_type=None,
selecting_color=None):
def get_current_timeline_items(
filter: bool = False,
track_type: str = None,
track_name: str = None,
selecting_color: str = None) -> list:
""" Gets all available current timeline track items
"""
track_type = track_type or "video"
selecting_color = selecting_color or "Chocolate"
project = get_current_project()
sequence = get_current_sequence()
timeline = get_current_timeline()
selected_clips = list()
# get all tracks count filtered by track type
selected_track_count = sequence.GetTrackCount(track_type)
selected_track_count = timeline.GetTrackCount(track_type)
# loop all tracks and get items
_clips = dict()
for track_index in range(1, (int(selected_track_count) + 1)):
track_name = sequence.GetTrackName(track_type, track_index)
track_track_items = sequence.GetItemListInTrack(
_track_name = timeline.GetTrackName(track_type, track_index)
# filter out all unmathed track names
if track_name:
if _track_name not in track_name:
continue
timeline_items = timeline.GetItemListInTrack(
track_type, track_index)
_clips[track_index] = track_track_items
_clips[track_index] = timeline_items
_data = {
"project": project,
"sequence": sequence,
"timeline": timeline,
"track": {
"name": track_name,
"name": _track_name,
"index": track_index,
"type": track_type}
}
@ -115,22 +346,34 @@ def get_current_track_items(
return selected_clips
def get_track_item_pype_tag(track_item):
def get_pype_timeline_item_by_name(name: str) -> object:
track_itmes = get_current_timeline_items()
for _ti in track_itmes:
tag_data = get_timeline_item_pype_tag(_ti["clip"]["item"])
tag_name = tag_data.get("name")
if not tag_name:
continue
if tag_data.get("name") in name:
return _ti
return None
def get_timeline_item_pype_tag(timeline_item):
"""
Get pype track item tag created by creator or loader plugin.
Attributes:
trackItem (resolve.TimelineItem): hiero object
trackItem (resolve.TimelineItem): resolve object
Returns:
hiero.core.Tag: hierarchy, orig clip attributes
dict: pype tag data
"""
return_tag = None
if self.pype_marker_workflow:
return_tag = get_pype_marker(track_item)
return_tag = get_pype_marker(timeline_item)
else:
media_pool_item = track_item.GetMediaPoolItem()
media_pool_item = timeline_item.GetMediaPoolItem()
# get all tags from track item
_tags = media_pool_item.GetMetadata()
@ -144,9 +387,9 @@ def get_track_item_pype_tag(track_item):
return return_tag
def set_track_item_pype_tag(track_item, data=None):
def set_timeline_item_pype_tag(timeline_item, data=None):
"""
Set pype track item tag to input track_item.
Set pype track item tag to input timeline_item.
Attributes:
trackItem (resolve.TimelineItem): resolve api object
@ -157,18 +400,18 @@ def set_track_item_pype_tag(track_item, data=None):
data = data or dict()
# get available pype tag if any
tag_data = get_track_item_pype_tag(track_item)
tag_data = get_timeline_item_pype_tag(timeline_item)
if self.pype_marker_workflow:
# delete tag as it is not updatable
if tag_data:
delete_pype_marker(track_item)
delete_pype_marker(timeline_item)
tag_data.update(data)
set_pype_marker(track_item, tag_data)
set_pype_marker(timeline_item, tag_data)
else:
if tag_data:
media_pool_item = track_item.GetMediaPoolItem()
media_pool_item = timeline_item.GetMediaPoolItem()
# it not tag then create one
tag_data.update(data)
media_pool_item.SetMetadata(
@ -177,19 +420,19 @@ def set_track_item_pype_tag(track_item, data=None):
tag_data = data
# if pype tag available then update with input data
# add it to the input track item
track_item.SetMetadata(self.pype_tag_name, json.dumps(tag_data))
timeline_item.SetMetadata(self.pype_tag_name, json.dumps(tag_data))
return tag_data
def imprint(track_item, data=None):
def imprint(timeline_item, data=None):
"""
Adding `Avalon data` into a hiero track item tag.
Also including publish attribute into tag.
Arguments:
track_item (hiero.core.TrackItem): hiero track item object
timeline_item (hiero.core.TrackItem): hiero track item object
data (dict): Any data which needst to be imprinted
Examples:
@ -201,39 +444,39 @@ def imprint(track_item, data=None):
"""
data = data or {}
set_track_item_pype_tag(track_item, data)
set_timeline_item_pype_tag(timeline_item, data)
# add publish attribute
set_publish_attribute(track_item, True)
set_publish_attribute(timeline_item, True)
def set_publish_attribute(track_item, value):
def set_publish_attribute(timeline_item, value):
""" Set Publish attribute in input Tag object
Attribute:
tag (hiero.core.Tag): a tag object
value (bool): True or False
"""
tag_data = get_track_item_pype_tag(track_item)
tag_data = get_timeline_item_pype_tag(timeline_item)
tag_data["publish"] = value
# set data to the publish attribute
set_track_item_pype_tag(track_item, tag_data)
set_timeline_item_pype_tag(timeline_item, tag_data)
def get_publish_attribute(track_item):
def get_publish_attribute(timeline_item):
""" Get Publish attribute from input Tag object
Attribute:
tag (hiero.core.Tag): a tag object
value (bool): True or False
"""
tag_data = get_track_item_pype_tag(track_item)
tag_data = get_timeline_item_pype_tag(timeline_item)
return tag_data["publish"]
def set_pype_marker(track_item, tag_data):
source_start = track_item.GetLeftOffset()
item_duration = track_item.GetDuration()
def set_pype_marker(timeline_item, tag_data):
source_start = timeline_item.GetLeftOffset()
item_duration = timeline_item.GetDuration()
frame = int(source_start + (item_duration / 2))
# marker attributes
@ -243,7 +486,7 @@ def set_pype_marker(track_item, tag_data):
note = json.dumps(tag_data)
duration = (self.pype_marker_duration / 10) * 10
track_item.AddMarker(
timeline_item.AddMarker(
frameId,
color,
name,
@ -252,12 +495,12 @@ def set_pype_marker(track_item, tag_data):
)
def get_pype_marker(track_item):
track_item_markers = track_item.GetMarkers()
for marker_frame in track_item_markers:
note = track_item_markers[marker_frame]["note"]
color = track_item_markers[marker_frame]["color"]
name = track_item_markers[marker_frame]["name"]
def get_pype_marker(timeline_item):
timeline_item_markers = timeline_item.GetMarkers()
for marker_frame in timeline_item_markers:
note = timeline_item_markers[marker_frame]["note"]
color = timeline_item_markers[marker_frame]["color"]
name = timeline_item_markers[marker_frame]["name"]
print(f"_ marker data: {marker_frame} | {name} | {color} | {note}")
if name == self.pype_marker_name and color == self.pype_marker_color:
self.temp_marker_frame = marker_frame
@ -266,105 +509,11 @@ def get_pype_marker(track_item):
return dict()
def delete_pype_marker(track_item):
track_item.DeleteMarkerAtFrame(self.temp_marker_frame)
def delete_pype_marker(timeline_item):
timeline_item.DeleteMarkerAtFrame(self.temp_marker_frame)
self.temp_marker_frame = None
def create_current_sequence_media_bin(sequence):
seq_name = sequence.GetName()
media_pool = get_current_project().GetMediaPool()
root_folder = media_pool.GetRootFolder()
sub_folders = root_folder.GetSubFolderList()
testing_names = list()
print(f"_ sub_folders: {sub_folders}")
for subfolder in sub_folders:
subf_name = subfolder.GetName()
if seq_name in subf_name:
testing_names.append(subfolder)
else:
testing_names.append(False)
matching = next((f for f in testing_names if f is not False), None)
if not matching:
new_folder = media_pool.AddSubFolder(root_folder, seq_name)
media_pool.SetCurrentFolder(new_folder)
else:
media_pool.SetCurrentFolder(matching)
return media_pool.GetCurrentFolder()
def get_name_with_data(clip_data, presets):
"""
Take hierarchy data from presets and build name with parents data
Args:
clip_data (dict): clip data from `get_current_track_items()`
presets (dict): data from create plugin
Returns:
list: name, data
"""
def _replace_hash_to_expression(name, text):
_spl = text.split("#")
_len = (len(_spl) - 1)
_repl = f"{{{name}:0>{_len}}}"
new_text = text.replace(("#" * _len), _repl)
return new_text
# presets data
clip_name = presets["clipName"]
hierarchy = presets["hierarchy"]
hierarchy_data = presets["hierarchyData"].copy()
count_from = presets["countFrom"]
steps = presets["steps"]
# reset rename_add
if self.rename_add < count_from:
self.rename_add = count_from
# shot num calculate
if self.rename_index == 0:
shot_num = self.rename_add
else:
shot_num = self.rename_add + steps
print(f"shot_num: {shot_num}")
# clip data
_data = {
"sequence": clip_data["sequence"].GetName(),
"track": clip_data["track"]["name"].replace(" ", "_"),
"shot": shot_num
}
# solve # in test to pythonic explression
for k, v in hierarchy_data.items():
if "#" not in v:
continue
hierarchy_data[k] = _replace_hash_to_expression(k, v)
# fill up pythonic expresisons
for k, v in hierarchy_data.items():
hierarchy_data[k] = v.format(**_data)
# fill up clip name and hierarchy keys
hierarchy = hierarchy.format(**hierarchy_data)
clip_name = clip_name.format(**hierarchy_data)
self.rename_add = shot_num
print(f"shot_num: {shot_num}")
return (clip_name, {
"hierarchy": hierarchy,
"hierarchyData": hierarchy_data
})
def create_compound_clip(clip_data, name, folder):
"""
Convert timeline object into nested timeline object
@ -380,7 +529,7 @@ def create_compound_clip(clip_data, name, folder):
"""
# get basic objects form data
project = clip_data["project"]
sequence = clip_data["sequence"]
timeline = clip_data["timeline"]
clip = clip_data["clip"]
# get details of objects
@ -411,7 +560,7 @@ def create_compound_clip(clip_data, name, folder):
out_frame = opentime.to_frames(mp_out_rc)
# keep original sequence
sq_origin = sequence
tl_origin = timeline
# Set current folder to input media_pool_folder:
mp.SetCurrentFolder(folder)
@ -433,18 +582,13 @@ def create_compound_clip(clip_data, name, folder):
if c.GetName() in name), None)
print(f"_ cct created: {cct}")
# Set current timeline to created timeline:
project.SetCurrentTimeline(cct)
# Add input clip to the current timeline:
mp.AppendToTimeline([{
"mediaPoolItem": mp_item,
"startFrame": mp_first_frame,
"endFrame": mp_last_frame
}])
# Set current timeline to the working timeline:
project.SetCurrentTimeline(sq_origin)
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 comound clip:
if mp_item.GetMetadata(self.pype_tag_name):
@ -465,13 +609,13 @@ def create_compound_clip(clip_data, name, folder):
cct.SetClipProperty("Start TC", mp_props["Start TC"])
# swap clips on timeline
swap_clips(clip_item, cct, name, in_frame, out_frame)
swap_clips(clip_item, cct, in_frame, out_frame)
cct.SetClipColor("Pink")
return cct
def swap_clips(from_clip, to_clip, to_clip_name, to_in_frame, to_out_frame):
def swap_clips(from_clip, to_clip, to_in_frame, to_out_frame):
"""
Swaping clips on timeline in timelineItem
@ -488,6 +632,8 @@ def swap_clips(from_clip, to_clip, to_clip_name, to_in_frame, to_out_frame):
bool: True if successfully replaced
"""
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,
@ -508,7 +654,7 @@ def swap_clips(from_clip, to_clip, to_clip_name, to_in_frame, to_out_frame):
return False
def validate_tc(x):
def _validate_tc(x):
# Validate and reformat timecode string
if len(x) != 11:
@ -590,7 +736,7 @@ def set_project_manager_to_folder_name(folder_name):
# go back to root folder
if self.project_manager.GotoRootFolder():
log.info(f"Testing existing folder: {folder_name}")
folders = convert_resolve_list_type(
folders = _convert_resolve_list_type(
self.project_manager.GetFoldersInCurrentFolder())
log.info(f"Testing existing folders: {folders}")
# get me first available folder object
@ -617,7 +763,7 @@ def set_project_manager_to_folder_name(folder_name):
return False
def convert_resolve_list_type(resolve_list):
def _convert_resolve_list_type(resolve_list):
""" Resolve is using indexed dictionary as list type.
`{1.0: 'vaule'}`
This will convert it to normal list class
@ -628,7 +774,59 @@ def convert_resolve_list_type(resolve_list):
return [resolve_list[i] for i in sorted(resolve_list.keys())]
def get_reformated_path(path, padded=True):
def create_otio_time_range_from_timeline_item_data(timeline_item_data):
timeline_item = timeline_item_data["clip"]["item"]
project = timeline_item_data["project"]
timeline = timeline_item_data["timeline"]
timeline_start = timeline.GetStartFrame()
frame_start = int(timeline_item.GetStart() - timeline_start)
frame_duration = int(timeline_item.GetDuration())
fps = project.GetSetting("timelineFrameRate")
return otio_export.create_otio_time_range(
frame_start, frame_duration, fps)
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)
for otio_clip in otio_timeline.each_clip():
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 pype.lib.is_overlapping_otio_ranges(
parent_range, timeline_range, strict=True):
# add pypedata marker to otio_clip metadata
for marker in otio_clip.markers:
if self.pype_marker_name in marker.name:
otio_clip.metadata.update(marker.metadata)
return {"otioClip": otio_clip}
return None
def get_reformated_path(path, padded=False, first=False):
"""
Return fixed python expression path
@ -642,64 +840,19 @@ def get_reformated_path(path, padded=True):
get_reformated_path("plate.[0001-1008].exr") > plate.%04d.exr
"""
num_pattern = "(\\[\\d+\\-\\d+\\])"
padding_pattern = "(\\d+)(?=-)"
num_pattern = r"(\[\d+\-\d+\])"
padding_pattern = r"(\d+)(?=-)"
first_frame_pattern = re.compile(r"\[(\d+)\-\d+\]")
if "[" in path:
padding = len(re.findall(padding_pattern, path).pop())
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, f"%d", path)
path = re.sub(num_pattern, "%d", path)
return path
def create_otio_time_range_from_track_item_data(track_item_data):
track_item = track_item_data["clip"]["item"]
project = track_item_data["project"]
timeline = track_item_data["sequence"]
timeline_start = timeline.GetStartFrame()
frame_start = int(track_item.GetStart() - timeline_start)
frame_duration = int(track_item.GetDuration())
fps = project.GetSetting("timelineFrameRate")
return otio_export.create_otio_time_range(
frame_start, frame_duration, fps)
def get_otio_clip_instance_data(otio_timeline, track_item_data):
"""
Return otio objects for timeline, track and clip
Args:
track_item_data (dict): track_item_data from list returned by
resolve.get_current_track_items()
otio_timeline (otio.schema.Timeline): otio object
Returns:
dict: otio clip object
"""
track_item = track_item_data["clip"]["item"]
track_name = track_item_data["track"]["name"]
timeline_range = create_otio_time_range_from_track_item_data(
track_item_data)
for otio_clip in otio_timeline.each_clip():
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 track_item.GetName():
continue
if pype.lib.is_overlapping_otio_ranges(
parent_range, timeline_range, strict=True):
# add pypedata marker to otio_clip metadata
for marker in otio_clip.markers:
if self.pype_marker_name in marker.name:
otio_clip.metadata.update(marker.metadata)
return {"otioClip": otio_clip}
return None

View file

@ -9,24 +9,17 @@ from avalon import api as avalon
from avalon import schema
from avalon.pipeline import AVALON_CONTAINER_ID
from pyblish import api as pyblish
import pype
from pype.api import Logger
from . import lib
from . import PLUGINS_DIR
log = Logger().get_logger(__name__)
AVALON_CONFIG = os.environ["AVALON_CONFIG"]
LOAD_PATH = os.path.join(pype.PLUGINS_DIR, "resolve", "load")
CREATE_PATH = os.path.join(pype.PLUGINS_DIR, "resolve", "create")
INVENTORY_PATH = os.path.join(pype.PLUGINS_DIR, "resolve", "inventory")
PUBLISH_PATH = os.path.join(
pype.PLUGINS_DIR, "resolve", "publish"
).replace("\\", "/")
PUBLISH_PATH = os.path.join(PLUGINS_DIR, "publish")
LOAD_PATH = os.path.join(PLUGINS_DIR, "load")
CREATE_PATH = os.path.join(PLUGINS_DIR, "create")
INVENTORY_PATH = os.path.join(PLUGINS_DIR, "inventory")
AVALON_CONTAINERS = ":AVALON_CONTAINERS"
# IS_HEADLESS = not hasattr(cmds, "about") or cmds.about(batch=True)
def install():
@ -40,11 +33,14 @@ def install():
See the Maya equivalent for inspiration on how to implement this.
"""
from . import get_resolve_module
from .. import get_resolve_module
# Disable all families except for the ones we explicitly want to see
family_states = [
"imagesequence",
"render2d",
"plate",
"render",
"mov",
"clip"
]
@ -90,7 +86,7 @@ def uninstall():
pyblish.deregister_callback("instanceToggled", on_pyblish_instance_toggled)
def containerise(track_item,
def containerise(timeline_item,
name,
namespace,
context,
@ -102,14 +98,14 @@ def containerise(track_item,
for loaded assets.
Arguments:
track_item (hiero.core.TrackItem): object to imprint as container
timeline_item (hiero.core.TrackItem): object to imprint as container
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:
track_item (hiero.core.TrackItem): containerised object
timeline_item (hiero.core.TrackItem): containerised object
"""
@ -127,9 +123,9 @@ def containerise(track_item,
data_imprint.update({k: v})
print("_ data_imprint: {}".format(data_imprint))
lib.set_track_item_pype_tag(track_item, data_imprint)
lib.set_timeline_item_pype_tag(timeline_item, data_imprint)
return track_item
return timeline_item
def ls():
@ -144,20 +140,20 @@ def ls():
"""
# get all track items from current timeline
all_track_items = lib.get_current_track_items(filter=False)
all_timeline_items = lib.get_current_timeline_items(filter=False)
for track_item_data in all_track_items:
track_item = track_item_data["clip"]["item"]
container = parse_container(track_item)
for timeline_item_data in all_timeline_items:
timeline_item = timeline_item_data["clip"]["item"]
container = parse_container(timeline_item)
if container:
yield container
def parse_container(track_item, validate=True):
"""Return container data from track_item's pype tag.
def parse_container(timeline_item, validate=True):
"""Return container data from timeline_item's pype tag.
Args:
track_item (hiero.core.TrackItem): A containerised track item.
timeline_item (hiero.core.TrackItem): A containerised track item.
validate (bool)[optional]: validating with avalon scheme
Returns:
@ -165,7 +161,7 @@ def parse_container(track_item, validate=True):
"""
# convert tag metadata to normal keys names
data = lib.get_track_item_pype_tag(track_item)
data = lib.get_timeline_item_pype_tag(timeline_item)
if validate and data and data.get("schema"):
schema.validate(data)
@ -182,19 +178,19 @@ def parse_container(track_item, validate=True):
container = {key: data[key] for key in required}
container["objectName"] = track_item.name()
container["objectName"] = timeline_item.GetName()
# Store reference to the node object
container["_track_item"] = track_item
container["_timeline_item"] = timeline_item
return container
def update_container(track_item, data=None):
"""Update container data to input track_item's pype tag.
def update_container(timeline_item, data=None):
"""Update container data to input timeline_item's pype tag.
Args:
track_item (hiero.core.TrackItem): A containerised track item.
timeline_item (hiero.core.TrackItem): A containerised track item.
data (dict)[optional]: dictionery with data to be updated
Returns:
@ -203,7 +199,7 @@ def update_container(track_item, data=None):
"""
data = data or dict()
container = lib.get_track_item_pype_tag(track_item)
container = lib.get_timeline_item_pype_tag(timeline_item)
for _key, _value in container.items():
try:
@ -211,8 +207,8 @@ def update_container(track_item, data=None):
except KeyError:
pass
log.info("Updating container: `{}`".format(track_item))
return bool(lib.set_track_item_pype_tag(track_item, container))
log.info("Updating container: `{}`".format(timeline_item))
return bool(lib.set_timeline_item_pype_tag(timeline_item, container))
def launch_workfiles_app(*args):
@ -260,5 +256,5 @@ def on_pyblish_instance_toggled(instance, old_value, new_value):
)
# Whether instances should be passthrough based on new value
track_item = instance.data["item"]
set_publish_attribute(track_item, new_value)
timeline_item = instance.data["item"]
set_publish_attribute(timeline_item, new_value)

View file

@ -1,5 +1,6 @@
import re
from avalon import api
import pype.api as pype
from pype.hosts import resolve
from avalon.vendor import qargparse
from . import lib
@ -278,7 +279,172 @@ class Spacer(QtWidgets.QWidget):
self.setLayout(layout)
class SequenceLoader(api.Loader):
class ClipLoader:
active_bin = None
data = dict()
def __init__(self, cls, context, **options):
""" Initialize object
Arguments:
cls (avalon.api.Loader): plugin object
context (dict): loader plugin context
options (dict)[optional]: possible keys:
projectBinPath: "path/to/binItem"
"""
self.__dict__.update(cls.__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") or bool(
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 bool(
"New timeline" in options.get("load_to", ""))
assert self._populate_data(), str(
"Cannot Load selected data, look into database "
"or call your supervisor")
# inject asset data to representation dict
self._get_asset_data()
print("__init__ self.data: `{}`".format(self.data))
# add active components to class
if self.new_timeline:
if options.get("timeline"):
# if multiselection is set then use options sequence
self.active_timeline = options["timeline"]
else:
# create new sequence
self.active_timeline = lib.get_current_timeline(new=True)
else:
self.active_timeline = lib.get_current_timeline()
cls.timeline = self.active_timeline
def _populate_data(self):
""" Gets context and convert it to self.data
data structure:
{
"name": "assetName_subsetName_representationName"
"path": "path/to/file/created/by/get_repr..",
"binPath": "projectBinPath",
}
"""
# create name
repr = self.context["representation"]
repr_cntx = repr["context"]
asset = str(repr_cntx["asset"])
subset = str(repr_cntx["subset"])
representation = str(repr_cntx["representation"])
self.data["clip_name"] = "_".join([asset, subset, representation])
self.data["versionData"] = self.context["version"]["data"]
# gets file path
file = self.fname
if not file:
repr_id = repr["_id"]
print(
"Representation id `{}` is failing to load".format(repr_id))
return None
self.data["path"] = file.replace("\\", "/")
# solve project bin structure path
hierarchy = str("/".join((
"Loader",
repr_cntx["hierarchy"].replace("\\", "/"),
asset
)))
self.data["binPath"] = hierarchy
return True
def _get_asset_data(self):
""" Get all available asset data
joint `data` key with asset.data dict into the representaion
"""
asset_name = self.context["representation"]["context"]["asset"]
self.data["assetData"] = pype.get_asset(asset_name)["data"]
def load(self):
# 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(
self.data["path"], self.active_bin)
clip_property = media_pool_item.GetClipProperty()
# get handles
handle_start = self.data["versionData"].get("handleStart")
handle_end = self.data["versionData"].get("handleEnd")
if handle_start is None:
handle_start = int(self.data["assetData"]["handleStart"])
if handle_end is None:
handle_end = int(self.data["assetData"]["handleEnd"])
source_in = int(clip_property["Start"])
source_out = int(clip_property["End"])
if clip_property["Type"] == "Video":
source_in += handle_start
source_out -= handle_end
# include handles
if self.with_handles:
source_in -= handle_start
source_out += handle_end
handle_start = 0
handle_end = 0
# make track item from source in bin as item
timeline_item = lib.create_timeline_item(
media_pool_item, self.active_timeline, source_in, source_out)
print("Loading clips: `{}`".format(self.data["clip_name"]))
return timeline_item
def update(self, timeline_item):
# 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(
self.data["path"], self.active_bin)
clip_property = media_pool_item.GetClipProperty()
clip_name = clip_property["File Name"]
# get handles
handle_start = self.data["versionData"].get("handleStart")
handle_end = self.data["versionData"].get("handleEnd")
if handle_start is None:
handle_start = int(self.data["assetData"]["handleStart"])
if handle_end is None:
handle_end = int(self.data["assetData"]["handleEnd"])
source_in = int(clip_property["Start"])
source_out = int(clip_property["End"])
resolve.swap_clips(
timeline_item,
media_pool_item,
source_in,
source_out
)
print("Loading clips: `{}`".format(self.data["clip_name"]))
return timeline_item
class TimelineItemLoader(api.Loader):
"""A basic SequenceLoader for Resolve
This will implement the basic behavior for a loader to inherit from that
@ -303,16 +469,6 @@ class SequenceLoader(api.Loader):
],
default=0,
help="Where do you want clips to be loaded?"
),
qargparse.Choice(
"load_how",
label="How to load clips",
items=[
"original timing",
"sequential in order"
],
default=0,
help="Would you like to place it at orignal timing?"
)
]
@ -352,12 +508,12 @@ class Creator(api.Creator):
# adding basic current context resolve objects
self.project = resolve.get_current_project()
self.sequence = resolve.get_current_sequence()
self.timeline = resolve.get_current_timeline()
if (self.options or {}).get("useSelection"):
self.selected = resolve.get_current_track_items(filter=True)
self.selected = resolve.get_current_timeline_items(filter=True)
else:
self.selected = resolve.get_current_track_items(filter=False)
self.selected = resolve.get_current_timeline_items(filter=False)
self.widget = CreatorWidget
@ -367,7 +523,7 @@ class PublishClip:
Convert a track item to publishable instance
Args:
track_item (hiero.core.TrackItem): hiero track item object
timeline_item (hiero.core.TrackItem): hiero track item object
kwargs (optional): additional data needed for rename=True (presets)
Returns:
@ -398,24 +554,24 @@ class PublishClip:
vertical_sync_default = False
driving_layer_default = ""
def __init__(self, cls, track_item_data, **kwargs):
def __init__(self, cls, timeline_item_data, **kwargs):
# populate input cls attribute onto self.[attr]
self.__dict__.update(cls.__dict__)
# get main parent objects
self.track_item_data = track_item_data
self.track_item = track_item_data["clip"]["item"]
sequence_name = track_item_data["sequence"].GetName()
self.sequence_name = str(sequence_name).replace(" ", "_")
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.track_item.GetName()
self.ti_index = int(track_item_data["clip"]["index"])
self.ti_name = self.timeline_item.GetName()
self.ti_index = int(timeline_item_data["clip"]["index"])
# get track name and index
track_name = track_item_data["track"]["name"]
track_name = timeline_item_data["track"]["name"]
self.track_name = str(track_name).replace(" ", "_")
self.track_index = int(track_item_data["track"]["index"])
self.track_index = int(timeline_item_data["track"]["index"])
# adding tag.family into tag
if kwargs.get("avalon"):
@ -428,7 +584,7 @@ class PublishClip:
self.mp_folder = kwargs.get("mp_folder")
# populate default data before we get other attributes
self._populate_track_item_default_data()
self._populate_timeline_item_default_data()
# use all populated default data to create all important attributes
self._populate_attributes()
@ -457,27 +613,27 @@ class PublishClip:
if not lib.pype_marker_workflow:
# create compound clip workflow
lib.create_compound_clip(
self.track_item_data,
self.timeline_item_data,
self.tag_data["asset"],
self.mp_folder
)
# add track_item_data selection to tag
# add timeline_item_data selection to tag
self.tag_data.update({
"track_data": self.track_item_data["track"]
"track_data": self.timeline_item_data["track"]
})
# create pype tag on track_item and add data
lib.imprint(self.track_item, self.tag_data)
# create pype tag on timeline_item and add data
lib.imprint(self.timeline_item, self.tag_data)
return self.track_item
return self.timeline_item
def _populate_track_item_default_data(self):
def _populate_timeline_item_default_data(self):
""" Populate default formating data from track item. """
self.track_item_default_data = {
self.timeline_item_default_data = {
"_folder_": "shots",
"_sequence_": self.sequence_name,
"_sequence_": self.timeline_name,
"_track_": self.track_name,
"_clip_": self.ti_name,
"_trackIndex_": self.track_index,
@ -487,8 +643,8 @@ class PublishClip:
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.track_item.GetStart())
self.clip_out = int(self.track_item.GetEnd())
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
@ -504,7 +660,7 @@ class PublishClip:
"hierarchy", {}).get("value") or self.hierarchy_default
self.hierarchy_data = self.ui_inputs.get(
"hierarchyData", {}).get("value") or \
self.track_item_default_data.copy()
self.timeline_item_default_data.copy()
self.count_from = self.ui_inputs.get(
"countFrom", {}).get("value") or self.count_from_default
self.count_steps = self.ui_inputs.get(
@ -553,7 +709,7 @@ class PublishClip:
self.count_steps *= self.rename_index
hierarchy_formating_data = dict()
_data = self.track_item_default_data.copy()
_data = self.timeline_item_default_data.copy()
if self.ui_inputs:
# adding tag metadata from ui
for _k, _v in self.ui_inputs.items():
@ -652,7 +808,7 @@ class PublishClip:
return {
"entity_type": entity_type,
"entity_name": self.hierarchy_data[key]["value"].format(
**self.track_item_default_data
**self.timeline_item_default_data
)
}

View file

@ -0,0 +1,71 @@
#! python3
class TestGUI:
def __init__(self):
resolve = bmd.scriptapp("Resolve") # noqa
self.fu = resolve.Fusion()
ui = self.fu.UIManager
self.disp = bmd.UIDispatcher(self.fu.UIManager) # noqa
self.title_font = ui.Font({"PixelSize": 18})
self._dialogue = self.disp.AddWindow(
{
"WindowTitle": "Get Testing folder",
"ID": "TestingWin",
"Geometry": [250, 250, 250, 100],
"Spacing": 0,
"Margin": 10
},
[
ui.VGroup(
{
"Spacing": 2
},
[
ui.Button(
{
"ID": "inputTestSourcesFolder",
"Text": "Select folder with testing medias",
"Weight": 1.25,
"ToolTip": (
"Chose folder with videos, sequences, "
"single images, nested folders with "
"medias"
),
"Flat": False
}
),
ui.VGap(),
ui.Button(
{
"ID": "openButton",
"Text": "Process Test",
"Weight": 2,
"ToolTip": "Run the test...",
"Flat": False
}
)
]
)
]
)
self._widgets = self._dialogue.GetItems()
self._dialogue.On.TestingWin.Close = self._close_window
self._dialogue.On.inputTestSourcesFolder.Clicked = self._open_dir_button_pressed # noqa
self._dialogue.On.openButton.Clicked = self.process
def _close_window(self, event):
self.disp.ExitLoop()
def process(self, event):
# placeholder function this supposed to be run from child class
pass
def _open_dir_button_pressed(self, event):
# placeholder function this supposed to be run from child class
pass
def show_gui(self):
self._dialogue.Show()
self.disp.RunLoop()
self._dialogue.Hide()

View file

@ -7,7 +7,7 @@ Resolve's tools for setting environment
import sys
import os
import shutil
from . import HOST_DIR
from pype.api import Logger
log = Logger().get_logger(__name__)
@ -15,10 +15,10 @@ log = Logger().get_logger(__name__)
def get_resolve_module():
from pype.hosts import resolve
# dont run if already loaded
if resolve.bmdvr:
if resolve.api.bmdvr:
log.info(("resolve module is assigned to "
f"`pype.hosts.resolve.bmdvr`: {resolve.bmdvr}"))
return resolve.bmdvr
f"`pype.hosts.resolve.api.bmdvr`: {resolve.api.bmdvr}"))
return resolve.api.bmdvr
try:
"""
The PYTHONPATH needs to be set correctly for this import
@ -71,12 +71,12 @@ def get_resolve_module():
# assign global var and return
bmdvr = bmd.scriptapp("Resolve")
# bmdvf = bmd.scriptapp("Fusion")
resolve.bmdvr = bmdvr
resolve.bmdvf = bmdvr.Fusion()
resolve.api.bmdvr = bmdvr
resolve.api.bmdvf = bmdvr.Fusion()
log.info(("Assigning resolve module to "
f"`pype.hosts.resolve.bmdvr`: {resolve.bmdvr}"))
f"`pype.hosts.resolve.api.bmdvr`: {resolve.api.bmdvr}"))
log.info(("Assigning resolve module to "
f"`pype.hosts.resolve.bmdvf`: {resolve.bmdvf}"))
f"`pype.hosts.resolve.api.bmdvf`: {resolve.api.bmdvf}"))
def _sync_utility_scripts(env=None):
@ -93,7 +93,7 @@ def _sync_utility_scripts(env=None):
us_env = env.get("RESOLVE_UTILITY_SCRIPTS_SOURCE_DIR")
us_dir = env.get("RESOLVE_UTILITY_SCRIPTS_DIR", "")
us_paths = [os.path.join(
os.path.dirname(__file__),
HOST_DIR,
"utility_scripts"
)]
@ -115,7 +115,10 @@ def _sync_utility_scripts(env=None):
for s in os.listdir(us_dir):
path = os.path.join(us_dir, s)
log.info(f"Removing `{path}`...")
os.remove(path)
if os.path.isdir(path):
shutil.rmtree(path, onerror=None)
else:
os.remove(path)
# copy scripts into Resolve's utility scripts dir
for d, sl in scripts.items():
@ -125,7 +128,13 @@ def _sync_utility_scripts(env=None):
src = os.path.join(d, s)
dst = os.path.join(us_dir, s)
log.info(f"Copying `{src}` to `{dst}`...")
shutil.copy2(src, dst)
if os.path.isdir(src):
shutil.copytree(
src, dst, symlinks=False,
ignore=None, ignore_dangling_symlinks=False
)
else:
shutil.copy2(src, dst)
def setup(env=None):

View file

@ -2,7 +2,7 @@
import os
from pype.api import Logger
from . import (
from .. import (
get_project_manager,
get_current_project,
set_project_manager_to_folder_name

View file

@ -1,7 +1,7 @@
import os
import importlib
from pype.lib import PreLaunchHook
from pype.hosts.resolve import utils
from pype.hosts.resolve.api import utils
class ResolvePrelaunch(PreLaunchHook):

View file

@ -17,7 +17,7 @@ def frames_to_secons(frames, framerate):
return otio.opentime.to_seconds(rt)
def get_reformated_path(path, padded=True):
def get_reformated_path(path, padded=True, first=False):
"""
Return fixed python expression path
@ -31,14 +31,21 @@ def get_reformated_path(path, padded=True):
get_reformated_path("plate.[0001-1008].exr") > plate.%04d.exr
"""
num_pattern = "(\\[\\d+\\-\\d+\\])"
padding_pattern = "(\\d+)(?=-)"
num_pattern = r"(\[\d+\-\d+\])"
padding_pattern = r"(\d+)(?=-)"
first_frame_pattern = re.compile(r"\[(\d+)\-\d+\]")
if "[" in path:
padding = len(re.findall(padding_pattern, path).pop())
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, f"%d", path)
path = re.sub(num_pattern, "%d", path)
return path

View file

@ -240,11 +240,11 @@ class CreateShotClip(resolve.Creator):
sorted_selected_track_items.extend(unsorted_selected_track_items)
# sequence attrs
sq_frame_start = self.sequence.GetStartFrame()
sq_markers = self.sequence.GetMarkers()
sq_frame_start = self.timeline.GetStartFrame()
sq_markers = self.timeline.GetMarkers()
# create media bin for compound clips (trackItems)
mp_folder = resolve.create_current_sequence_media_bin(self.sequence)
mp_folder = resolve.create_current_sequence_media_bin(self.timeline)
kwargs = {
"ui_inputs": widget.result,

View file

@ -0,0 +1,148 @@
from avalon import io, api
from pype.hosts import resolve
from copy import deepcopy
class LoadClip(resolve.TimelineItemLoader):
"""Load a subset to timeline as clip
Place clip to timeline on its asset origin timings collected
during conforming to project
"""
families = ["render2d", "source", "plate", "render", "review"]
representations = ["exr", "dpx", "jpg", "jpeg", "png", "h264", ".mov"]
label = "Load as clip"
order = -10
icon = "code-fork"
color = "orange"
# for loader multiselection
timeline = None
# presets
clip_color_last = "Olive"
clip_color = "Orange"
def load(self, context, name, namespace, options):
# in case loader uses multiselection
if self.timeline:
options.update({
"timeline": self.timeline,
})
# load clip to timeline and get main variables
timeline_item = resolve.ClipLoader(
self, context, **options).load()
namespace = namespace or timeline_item.GetName()
version = context['version']
version_data = version.get("data", {})
version_name = version.get("name", None)
colorspace = version_data.get("colorspace", None)
object_name = "{}_{}".format(name, namespace)
# add additional metadata from the version to imprint Avalon knob
add_keys = [
"frameStart", "frameEnd", "source", "author",
"fps", "handleStart", "handleEnd"
]
# move all version data keys to tag data
data_imprint = {}
for key in add_keys:
data_imprint.update({
key: version_data.get(key, str(None))
})
# add variables related to version context
data_imprint.update({
"version": version_name,
"colorspace": colorspace,
"objectName": object_name
})
# update color of clip regarding the version order
self.set_item_color(timeline_item, version)
self.log.info("Loader done: `{}`".format(name))
return resolve.containerise(
timeline_item,
name, namespace, context,
self.__class__.__name__,
data_imprint)
def switch(self, container, representation):
self.update(container, representation)
def update(self, container, representation):
""" Updating previously loaded clips
"""
# load clip to timeline and get main variables
context = deepcopy(representation["context"])
context.update({"representation": representation})
name = container['name']
namespace = container['namespace']
timeline_item_data = resolve.get_pype_timeline_item_by_name(namespace)
timeline_item = timeline_item_data["clip"]["item"]
version = io.find_one({
"type": "version",
"_id": representation["parent"]
})
version_data = version.get("data", {})
version_name = version.get("name", None)
colorspace = version_data.get("colorspace", None)
object_name = "{}_{}".format(name, namespace)
self.fname = api.get_representation_path(representation)
context["version"] = {"data": version_data}
loader = resolve.ClipLoader(self, context)
timeline_item = loader.update(timeline_item)
# add additional metadata from the version to imprint Avalon knob
add_keys = [
"frameStart", "frameEnd", "source", "author",
"fps", "handleStart", "handleEnd"
]
# move all version data keys to tag data
data_imprint = {}
for key in add_keys:
data_imprint.update({
key: version_data.get(key, str(None))
})
# add variables related to version context
data_imprint.update({
"representation": str(representation["_id"]),
"version": version_name,
"colorspace": colorspace,
"objectName": object_name
})
# update color of clip regarding the version order
self.set_item_color(timeline_item, version)
return resolve.update_container(timeline_item, data_imprint)
@classmethod
def set_item_color(cls, timeline_item, version):
# define version name
version_name = version.get("name", None)
# get all versions in list
versions = io.find({
"type": "version",
"parent": version["parent"]
}).distinct('name')
max_version = max(versions)
# set clip colour
if version_name == max_version:
timeline_item.SetClipColor(cls.clip_color_last)
else:
timeline_item.SetClipColor(cls.clip_color)

View file

@ -14,20 +14,20 @@ class CollectInstances(pyblish.api.ContextPlugin):
def process(self, context):
otio_timeline = context.data["otioTimeline"]
selected_track_items = resolve.get_current_track_items(
selected_timeline_items = resolve.get_current_timeline_items(
filter=True, selecting_color=resolve.publish_clip_color)
self.log.info(
"Processing enabled track items: {}".format(
len(selected_track_items)))
len(selected_timeline_items)))
for track_item_data in selected_track_items:
for timeline_item_data in selected_timeline_items:
data = dict()
track_item = track_item_data["clip"]["item"]
timeline_item = timeline_item_data["clip"]["item"]
# get pype tag data
tag_data = resolve.get_track_item_pype_tag(track_item)
tag_data = resolve.get_timeline_item_pype_tag(timeline_item)
self.log.debug(f"__ tag_data: {pformat(tag_data)}")
if not tag_data:
@ -36,7 +36,7 @@ class CollectInstances(pyblish.api.ContextPlugin):
if tag_data.get("id") != "pyblish.avalon.instance":
continue
media_pool_item = track_item.GetMediaPoolItem()
media_pool_item = timeline_item.GetMediaPoolItem()
clip_property = media_pool_item.GetClipProperty()
self.log.debug(f"clip_property: {clip_property}")
@ -57,15 +57,15 @@ class CollectInstances(pyblish.api.ContextPlugin):
data.update({
"name": "{} {} {}".format(asset, subset, families),
"asset": asset,
"item": track_item,
"item": timeline_item,
"families": families,
"publish": resolve.get_publish_attribute(track_item),
"publish": resolve.get_publish_attribute(timeline_item),
"fps": context.data["fps"]
})
# otio clip data
otio_data = resolve.get_otio_clip_instance_data(
otio_timeline, track_item_data) or {}
otio_timeline, timeline_item_data) or {}
data.update(otio_data)
# add resolution
@ -75,7 +75,7 @@ class CollectInstances(pyblish.api.ContextPlugin):
instance = context.create_instance(**data)
# create shot instance for shot attributes create/update
self.create_shot_instance(context, track_item, **data)
self.create_shot_instance(context, timeline_item, **data)
self.log.info("Creating instance: {}".format(instance))
self.log.debug(
@ -101,7 +101,7 @@ class CollectInstances(pyblish.api.ContextPlugin):
"pixelAspect": otio_tl_metadata["pixelAspect"]
})
def create_shot_instance(self, context, track_item, **data):
def create_shot_instance(self, context, timeline_item, **data):
master_layer = data.get("masterLayer")
hierarchy_data = data.get("hierarchyData")
@ -123,7 +123,7 @@ class CollectInstances(pyblish.api.ContextPlugin):
"asset": asset,
"family": family,
"families": [],
"publish": resolve.get_publish_attribute(track_item)
"publish": resolve.get_publish_attribute(timeline_item)
})
context.create_instance(**data)

View file

@ -22,7 +22,7 @@ class CollectWorkfile(pyblish.api.ContextPlugin):
project = resolve.get_current_project()
fps = project.GetSetting("timelineFrameRate")
active_sequence = resolve.get_current_sequence()
active_timeline = resolve.get_current_timeline()
video_tracks = resolve.get_video_track_names()
# adding otio timeline to context
@ -42,7 +42,6 @@ class CollectWorkfile(pyblish.api.ContextPlugin):
# update context with main project attributes
context_data = {
"activeProject": project,
"activeSequence": active_sequence,
"otioTimeline": otio_timeline,
"videoTracks": video_tracks,
"currentFile": project.GetName(),

View file

@ -1,22 +0,0 @@
#!/usr/bin/env python
def main():
import pype.hosts.resolve as bmdvr
bmdvr.utils.get_resolve_module()
tracks = list()
track_type = "video"
sequence = bmdvr.get_current_sequence()
# get all tracks count filtered by track type
selected_track_count = sequence.GetTrackCount(track_type)
# loop all tracks and get items
for track_index in range(1, (int(selected_track_count) + 1)):
track_name = sequence.GetTrackName("video", track_index)
tracks.append(track_name)
if __name__ == "__main__":
main()

View file

@ -1,26 +0,0 @@
#! python3
import sys
import DaVinciResolveScript as bmdvr
def main():
resolve = bmdvr.scriptapp('Resolve')
print(f"resolve: {resolve}")
project_manager = resolve.GetProjectManager()
project = project_manager.GetCurrentProject()
media_pool = project.GetMediaPool()
root_folder = media_pool.GetRootFolder()
ls_folder = root_folder.GetClipList()
timeline = project.GetCurrentTimeline()
timeline_name = timeline.GetName()
for tl in ls_folder:
if tl.GetName() not in timeline_name:
continue
print(tl.GetName())
print(tl.GetMetadata())
print(tl.GetClipProperty())
if __name__ == "__main__":
result = main()
sys.exit(not bool(result))

View file

@ -0,0 +1,49 @@
#! python3
import os
import sys
import avalon.api as avalon
import pype
import opentimelineio as otio
from pype.hosts.resolve import TestGUI
import pype.hosts.resolve as bmdvr
from pype.hosts.resolve.otio import davinci_export as otio_export
class ThisTestGUI(TestGUI):
extensions = [".exr", ".jpg", ".mov", ".png", ".mp4", ".ari", ".arx"]
def __init__(self):
super(ThisTestGUI, self).__init__()
# Registers pype's Global pyblish plugins
pype.install()
# activate resolve from pype
avalon.install(bmdvr)
def _open_dir_button_pressed(self, event):
# selected_path = self.fu.RequestFile(os.path.expanduser("~"))
selected_path = self.fu.RequestDir(os.path.expanduser("~"))
self._widgets["inputTestSourcesFolder"].Text = selected_path
# main function
def process(self, event):
self.input_dir_path = self._widgets["inputTestSourcesFolder"].Text
project = bmdvr.get_current_project()
otio_timeline = otio_export.create_otio_timeline(project)
print(f"_ otio_timeline: `{otio_timeline}`")
edl_path = os.path.join(self.input_dir_path, "this_file_name.edl")
print(f"_ edl_path: `{edl_path}`")
# xml_string = otio_adapters.fcpx_xml.write_to_string(otio_timeline)
# print(f"_ xml_string: `{xml_string}`")
otio.adapters.write_to_file(
otio_timeline, edl_path, adapter_name="cmx_3600")
project = bmdvr.get_current_project()
media_pool = project.GetMediaPool()
timeline = media_pool.ImportTimelineFromFile(edl_path)
# at the end close the window
self._close_window(None)
if __name__ == "__main__":
test_gui = ThisTestGUI()
test_gui.show_gui()
sys.exit(not bool(True))

View file

@ -0,0 +1,70 @@
#! python3
import os
import sys
import avalon.api as avalon
import pype
from pype.hosts.resolve import TestGUI
import pype.hosts.resolve as bmdvr
import clique
class ThisTestGUI(TestGUI):
extensions = [".exr", ".jpg", ".mov", ".png", ".mp4", ".ari", ".arx"]
def __init__(self):
super(ThisTestGUI, self).__init__()
# Registers pype's Global pyblish plugins
pype.install()
# activate resolve from pype
avalon.install(bmdvr)
def _open_dir_button_pressed(self, event):
# selected_path = self.fu.RequestFile(os.path.expanduser("~"))
selected_path = self.fu.RequestDir(os.path.expanduser("~"))
self._widgets["inputTestSourcesFolder"].Text = selected_path
# main function
def process(self, event):
self.input_dir_path = self._widgets["inputTestSourcesFolder"].Text
self.dir_processing(self.input_dir_path)
# at the end close the window
self._close_window(None)
def dir_processing(self, dir_path):
collections, reminders = clique.assemble(os.listdir(dir_path))
# process reminders
for _rem in reminders:
_rem_path = os.path.join(dir_path, _rem)
# go deeper if directory
if os.path.isdir(_rem_path):
print(_rem_path)
self.dir_processing(_rem_path)
else:
self.file_processing(_rem_path)
# process collections
for _coll in collections:
_coll_path = os.path.join(dir_path, list(_coll).pop())
self.file_processing(_coll_path)
def file_processing(self, fpath):
print(f"_ fpath: `{fpath}`")
_base, ext = os.path.splitext(fpath)
# skip if unwanted extension
if ext not in self.extensions:
return
media_pool_item = bmdvr.create_media_pool_item(fpath)
print(media_pool_item)
track_item = bmdvr.create_timeline_item(media_pool_item)
print(track_item)
if __name__ == "__main__":
test_gui = ThisTestGUI()
test_gui.show_gui()
sys.exit(not bool(True))

View file

@ -1,38 +0,0 @@
import pyblish.api
class CollectClipResolution(pyblish.api.InstancePlugin):
"""Collect clip geometry resolution"""
order = pyblish.api.CollectorOrder - 0.1
label = "Collect Clip Resoluton"
hosts = ["resolve"]
families = ["clip"]
def process(self, instance):
sequence = instance.context.data['activeSequence']
item = instance.data["item"]
source_resolution = instance.data.get("sourceResolution", None)
resolution_width = int(sequence.format().width())
resolution_height = int(sequence.format().height())
pixel_aspect = sequence.format().pixelAspect()
# source exception
if source_resolution:
resolution_width = int(item.source().mediaSource().width())
resolution_height = int(item.source().mediaSource().height())
pixel_aspect = item.source().mediaSource().pixelAspect()
resolution_data = {
"resolutionWidth": resolution_width,
"resolutionHeight": resolution_height,
"pixelAspect": pixel_aspect
}
# add to instacne data
instance.data.update(resolution_data)
self.log.info("Resolution of instance '{}' is: {}".format(
instance,
resolution_data
))

View file

@ -1,162 +0,0 @@
import os
from pyblish import api
from pype.hosts import resolve
import json
class CollectClips(api.ContextPlugin):
"""Collect all Track items selection."""
order = api.CollectorOrder + 0.01
label = "Collect Clips"
hosts = ["resolve"]
def process(self, context):
# create asset_names conversion table
if not context.data.get("assetsShared"):
self.log.debug("Created `assetsShared` in context")
context.data["assetsShared"] = dict()
projectdata = context.data["projectEntity"]["data"]
selection = resolve.get_current_track_items(
filter=True, selecting_color="Pink")
for clip_data in selection:
data = dict()
# get basic objects form data
project = clip_data["project"]
sequence = clip_data["sequence"]
clip = clip_data["clip"]
# sequence attrs
sq_frame_start = sequence.GetStartFrame()
self.log.debug(f"sq_frame_start: {sq_frame_start}")
sq_markers = sequence.GetMarkers()
# get details of objects
clip_item = clip["item"]
track = clip_data["track"]
mp = project.GetMediaPool()
# get clip attributes
clip_metadata = resolve.get_pype_clip_metadata(clip_item)
clip_metadata = json.loads(clip_metadata)
self.log.debug(f"clip_metadata: {clip_metadata}")
compound_source_prop = clip_metadata["sourceProperties"]
self.log.debug(f"compound_source_prop: {compound_source_prop}")
asset_name = clip_item.GetName()
mp_item = clip_item.GetMediaPoolItem()
mp_prop = mp_item.GetClipProperty()
source_first = int(compound_source_prop["Start"])
source_last = int(compound_source_prop["End"])
source_duration = compound_source_prop["Frames"]
fps = float(mp_prop["FPS"])
self.log.debug(f"source_first: {source_first}")
self.log.debug(f"source_last: {source_last}")
self.log.debug(f"source_duration: {source_duration}")
self.log.debug(f"fps: {fps}")
source_path = os.path.normpath(
compound_source_prop["File Path"])
source_name = compound_source_prop["File Name"]
source_id = clip_metadata["sourceId"]
self.log.debug(f"source_path: {source_path}")
self.log.debug(f"source_name: {source_name}")
self.log.debug(f"source_id: {source_id}")
clip_left_offset = int(clip_item.GetLeftOffset())
clip_right_offset = int(clip_item.GetRightOffset())
self.log.debug(f"clip_left_offset: {clip_left_offset}")
self.log.debug(f"clip_right_offset: {clip_right_offset}")
# source in/out
source_in = int(source_first + clip_left_offset)
source_out = int(source_first + clip_right_offset)
self.log.debug(f"source_in: {source_in}")
self.log.debug(f"source_out: {source_out}")
clip_in = int(clip_item.GetStart() - sq_frame_start)
clip_out = int(clip_item.GetEnd() - sq_frame_start)
clip_duration = int(clip_item.GetDuration())
self.log.debug(f"clip_in: {clip_in}")
self.log.debug(f"clip_out: {clip_out}")
self.log.debug(f"clip_duration: {clip_duration}")
is_sequence = False
self.log.debug(
"__ assets_shared: {}".format(
context.data["assetsShared"]))
# Check for clips with the same range
# this is for testing if any vertically neighbouring
# clips has been already processed
clip_matching_with_range = next(
(k for k, v in context.data["assetsShared"].items()
if (v.get("_clipIn", 0) == clip_in)
and (v.get("_clipOut", 0) == clip_out)
), False)
# check if clip name is the same in matched
# vertically neighbouring clip
# if it is then it is correct and resent variable to False
# not to be rised wrong name exception
if asset_name in str(clip_matching_with_range):
clip_matching_with_range = False
# rise wrong name exception if found one
assert (not clip_matching_with_range), (
"matching clip: {asset}"
" timeline range ({clip_in}:{clip_out})"
" conflicting with {clip_matching_with_range}"
" >> rename any of clips to be the same as the other <<"
).format(
**locals())
if ("[" in source_name) and ("]" in source_name):
is_sequence = True
data.update({
"name": "_".join([
track["name"], asset_name, source_name]),
"item": clip_item,
"source": mp_item,
# "timecodeStart": str(source.timecodeStart()),
"timelineStart": sq_frame_start,
"sourcePath": source_path,
"sourceFileHead": source_name,
"isSequence": is_sequence,
"track": track["name"],
"trackIndex": track["index"],
"sourceFirst": source_first,
"sourceIn": source_in,
"sourceOut": source_out,
"mediaDuration": source_duration,
"clipIn": clip_in,
"clipOut": clip_out,
"clipDuration": clip_duration,
"asset": asset_name,
"subset": "plateMain",
"family": "clip",
"families": [],
"handleStart": projectdata.get("handleStart", 0),
"handleEnd": projectdata.get("handleEnd", 0)})
instance = context.create_instance(**data)
self.log.info("Created instance: {}".format(instance))
self.log.info("Created instance.data: {}".format(instance.data))
context.data["assetsShared"][asset_name] = {
"_clipIn": clip_in,
"_clipOut": clip_out
}
self.log.info(
"context.data[\"assetsShared\"]: {}".format(
context.data["assetsShared"]))