Media tools
A media tool is one declaration of something that edits media: trim a clip, resize an image, loop a video. Core ships nineteen; a plugin adds its own. The Tools menu on the Library and History pages, a media field's toolbar, presets, PotionAI chat and automation all read the same catalog, so a plugin tool shows up in every one of them as soon as the plugin is enabled and disappears when it is disabled. Tools change shape, time, sound or pixels (trim, crop, resize, rotate, flip, speed, split, frame, concat, fit canvas, crop to subject, colour key, fix colours, film grain, mute, volume, replace audio, paint layer) and run deterministically with no model. Looks on still images (grain, VHS, grades) are photo filters, not tools: see Contributing photo filters and filter ops.
On this page
Core tools#
| id | accepts | produces | params |
|---|---|---|---|
trim | video, audio | same | start, end (seconds) |
crop | image, video | same | x, y, width, height (px) |
resize | image, video | same | width, height (one side keeps the aspect ratio), quality high / balanced / small |
rotate | image, video | same | degrees 90 / 180 / 270, clockwise |
flip | image, video | same | axis horizontal / vertical |
speed | video, audio | same | speed 0.25 to 4, keep_pitch |
fit_canvas | image | same | width, height, scale_percent, anchor, fill |
color_key | image | same | key_mode, key_color, tolerance, softness, despill, feather |
crop_subject | image with transparency | same | margin, alpha_threshold |
frame | video | image | time (seconds) |
split | audio, video | same, many | mode every / at, part_seconds, at (seconds) |
concat | video, 2 to 8 selected | video, one | overlap, overlap_frames, fit, keep_audio |
cut_finder | video | video, many | sensitivity 0 to 100, min_shot_seconds |
mute | video with sound | same | none |
volume | video, audio with sound | same | unit percent / db, percent 0 to 400, db -60 to 20, fade_in, fade_out (seconds) |
replace_audio | video (editor only) | same | audio (media), start (seconds into the track), loop |
paint_layer | image (editor only) | same | layer (media, a transparent PNG), opacity (0 to 1, default 1) |
place_patch | image (editor only) | same | patch (media, an RGBA PNG made by an editor run), x, y, width, height (0 to 1, the patch's place as fractions of the picture), opacity (0 to 1, default 1), canvas_width, canvas_height, canvas_x, canvas_y (pixels, grow the picture onto a larger transparent canvas first), replace (checkbox, default off: the patch is the whole picture at its own size, as an upscale makes it) |
replace_background | image (editor only) | same | kind (color default, picture, transparent), color (#rrggbb, default #ffffff, for kind: color), picture (media, cover-fitted to the canvas, for kind: picture), matte (media, a grayscale mask, white = the background; its soft values are used as they are), opacity (0 to 1, how much of the replacement shows, default 1). transparent makes an RGBA picture with alpha multiplied by 1 minus the matte |
Core ids never contain a dot. Video output keeps even dimensions and the sound; images keep their transparency (a JPEG that gains an alpha channel is saved as PNG).
mute, volume and replace_audio copy the video stream when they run alone; next to a picture or timing edit they
share that edit's single encode. replace_audio keeps the video's length: the track starts start seconds in and, with
loop, repeats until the picture ends. split with mode: at cuts at one time point into two items; video parts are
re-encoded so the cut lands on the exact frame. Tools whose scopes are only editor (replace_audio, paint_layer, place_patch, replace_background)
are left out of the Library and History menus because they need a file picked in the editor.
A media parameter names another file: {"item_id": "..."} (a Library item or a helper upload) or
{"generation_file_id": "..."}; a bare string is read as an item_id. The run checks that the caller owns it and that
its kind is one of the parameter's accepts, then hands the tool a staged ToolMedia in its place.
The Effects menu (group: effects) lists effects: tools defined by an effect.yml folder, with a live preview
shader and ffmpeg, torch or numpy renders. Film grain (film_grain) and Fix colours (fix_colors) are the core ones.
Their contract, the catalog effect block and the shader and analysis endpoints are in Video Effects.
The editor API#
The Image and Video editor tabs keep a stack of steps, {tool, params, hidden?}, and talk to these endpoints. Every
one needs a signed-in user, answers 404 for a source, helper file, run or preview owned by someone else, and never puts
a file path in a response.
| Method and path | Body | Answer |
|---|---|---|
POST /api/media-tools/runs | {steps, inputs: [ref], output: {mode, target_item_id?}} | 202 {run_id} |
GET /api/media-tools/runs | {runs: [run]}, my runs still held (queued, running, or finished in the last 10 minutes) | |
GET /api/media-tools/runs/{id} | run | |
DELETE /api/media-tools/runs/{id} | run, cancelled | |
POST /api/media-tools/preview/frame | {input: ref, steps, time_seconds?, max_side? 1280, format? webp / png} | the image; header X-Preview-Cache: hit / miss |
POST /api/media-tools/preview/clip | {input: ref, steps, start_seconds? 0, duration_seconds? 3, height? 480} | 202 {run_id, preview} |
GET /api/media-tools/previews/{id} | the preview clip (cookie or bearer, so a <video> can play it) | |
POST /api/media-tools/artifacts | multipart file | {id, media_type, mime_type, url, width, height, duration_seconds, fps, size} |
GET /api/media-tools/effects/{tool_id}/shader | the effect's preview shader as text/plain, with an ETag | |
POST /api/media-tools/effects/analysis | {input: ref, steps, step_index} | {values, cached}, an effect's measured values |
- A
runis{run_id, kind: run / preview, status, progress 0..1, label, items, replaced, preview, error, summary}. Poll it by id for progress; a reload reattaches through the stored id or the run list. - Saving a stack runs it as one background run. Hidden steps are skipped and never validated; up to 64 visible steps
run in order.
mode: newmakes Library items,mode: updatewithtarget_item_idreplaces the file of the copy a first save made (one input, no split, same kind), andmode: replacereplaces a Library source; a History source or a helper upload is refused withreplace_not_allowed. A stack withsplitsaves its parts as separate items named "part 1 of 2". - Frame preview renders one frame of a video, or the image, through the stack with each tool's frame path, the same
code the full render uses:
film_grainseeds each frame's grain by a hash of its frame number, so the paused frame shows the grain the render will put there, andfix_colorsmeasures the trimmed range of the source.time_secondsis on the source clip; trim and speed steps map it to the frame the render would show. Sound and timing steps leave the picture alone. A tool with no frame path (frame,concat, most plugin tools) is refused with itsstep_index. Answers are cached per user, source, time, stack and size. - Clip preview cuts
duration_secondsfromstart_seconds(source time, clamped inside the trim), runs the stack on that piece and scales it toheightas an MP4. A split step is left out. When the same request is cached the answer is{run_id: null, preview}at once; otherwise poll the run and readpreviewwhen it completes, or cancel it. Fades and the replacement track's offset count from the start of the piece, not of the whole clip. - Helper uploads (
derived_artifact) hold what an editor makes or receives: a paint layer, a mask, a dropped file, a replacement track. Use the returnedidas a run input or in amediaparameter. They stay out of the Library but count toward the plan's storage and per-file limits. They must be an image, audio or video file of at most 512 MB. The announced size is checked before the body is read and the bytes are checked again after. The same rules apply toPOST /api/media/uploadwithpurpose=derived_artifact. The Image editor stores every paint layer as its own helper upload and its ownpaintstep ({layer, url, layers: 1, name}, with the step'slayer.opacityandhiddencarrying the fade and the eye), so a saved edit keeps each layer; a layer that was added but not painted yet has an emptylayerandurland sends no step; apaintstep withoutnameis an older one-PNG paint and opens as a single layer. Nothing sweeps these helper uploads, so a saved edit keeps every layer file it names.
From chat, MCP and automation#
PotionAI's run_media_tool chat tool, the same tool over MCP and the action.media_tool automation node run
the catalog tools that have a Python implementation (python:). Component-only tools have no run API and are
not offered. The chat tool builds its description and tool enum from the live catalog each turn, so a
plugin's tools appear in the model's schema while the plugin is enabled, with each parameter written as
name type[min..max]unit =default. Keep parameter names short and give a min, max and default where
they make sense, because the model reads them verbatim. Every run goes through the same service as the API:
the same ownership checks, parameter validation and Library quota. mode: replace is the one call that waits
for the user's approval in chat. See Chat Modes and
Automation Nodes.
From presets#
A preset step runs any registered tool, a plugin's included, through the media_tool pipe. tool is the catalog id,
params are the tool's parameters (the same names and the same validation as the API), and skip_unfit: true passes
media the tool cannot work on, such as an image without transparency for crop_subject, through unchanged instead of
failing.
- name: "media_tool"
id: "crop_subject"
input:
- ["image", "matting", "image"]
configuration:
display_title: "Cropping subject"
tool: "crop_subject"
skip_unfit: true
params:
margin: "{{ form.crop_margin }}"Images, videos and audio files go in and come out as arrays on image, video and audio; a tool that makes a
different kind (frame turns a video into an image) fills the output of that kind. A tool that joins (concat) takes
every input of one kind and makes one output. Image tools run in memory without writing the picture to disk. The pipe
reads the plugin catalog from the MEDIA_TOOLS service the generation engine injects, so a plugin's tool runs while the
plugin is enabled; a Remote Native worker has no such service and runs the core tools only. See the
Pipes Reference.
Declaring a tool#
A plugin declares tools in manifest.yml under media_tools. Disabling the plugin removes them from
every surface.
media_tools:
- id: boomerang.loop # must be "<plugin-id>.<tool>"
label: Boomerang
icon: repeat # optional, an Icon name; default "extension"
description: Play the clip forward, then backward # optional
accepts: [video] # image | video | audio, at least one
produces: same # same | image | video | audio
cardinality: one_to_one # one_to_one | one_to_many | many_to_one
params:
- { name: style, type: select, options: [forward, pingpong], default: pingpong }
- { name: repeats, type: integer, min: 1, max: 8, default: 2 }
requires: { has_audio: false } # optional: has_audio, has_alpha, min_duration (seconds)
selection: { min: 1, max: 4 } # optional: how many items the tool takes
scopes: [library, history] # optional: library | history | field | editor; default library, history, field
preview: false # true needs python; the dialog then shows a before/after pane
python: tools/loop.py:LoopTool # optional: a path inside the plugin dir, then :ClassName
component: loop-preview # optional: a plugin frontend assetAt least one of python and component is required. The id must start with your plugin id and a dot,
and a plugin cannot take an id another plugin or core already registered; an entry that breaks either
rule keeps the plugin from enabling.
A tool that needs sound (requires: { has_audio: true }) is greyed out in the Tools menu on a Library video
recorded as silent. The Library records whether a video has sound when it is uploaded or copied from History,
by probing the file, and a sound file always counts as having sound. For a media tool's result it records the
has_audio of the ToolMedia the tool returns: the core tools probe their output, and a plugin tool's value is
taken as the tool reports it. The value stays unknown on a History file, on an item stored before PotionUI
recorded sound, on an item saved from Inspirations, on a file uploaded again with the same bytes as an item of
unknown sound, and when the probe fails. The menu then offers the tool, and the run checks requires on each
input and refuses it with unsupported_media.
In the Library menu, Mute and Replace audio sit under the Audio entry, which opens the video editor on
Volume; that entry stays enabled on a silent clip, since Replace audio needs no sound.
params are form fields. type is integer, float, select, checkbox, color, string or
anchor, with these keys: name, label, default, min, max, step, unit, options (a list of
values or of {label, value}), allow_transparent (a color that may also be transparent), when
and description. when uses the preset form's when: grammar ({ field: key_mode, equals: color }),
and a parameter whose condition is false is dropped from the validated params. A parameter without a
default is required; default: null makes it optional. The dialog builds its controls from this
list: a select with up to four options becomes a segmented control, a number with min and max a
slider, a checkbox a switch.
The Python half#
from src.plugin_api.media_tools import FilterFragment, InvalidToolParams, MediaTool, ToolContext, ToolMedia
class LoopTool(MediaTool):
def run(self, inputs: list[ToolMedia], params: dict, ctx: ToolContext) -> list[ToolMedia]:
source = inputs[0]
out = ctx.new_path(".mp4")
ctx.ffmpeg(["-i", str(source.path), "-filter_complex", "...", str(out)], duration=source.duration)
return [ctx.probe(out)]run(inputs, params, ctx) receives the already validated params and returns the produced files, which
must live under ctx.scratch_dir: the host publishes them to the Library and deletes the scratch
directory afterwards, whatever happens.
ToolMediais a frozen dataclass:path,kind(image|video|audio),width,height,duration,fps,has_audio,has_alpha. Everything exceptpathandkindmay beNone.ToolContextgives youscratch_dir,user_id(the user the run belongs to,Noneoutside a Library or History run),new_path(suffix)for a fresh output path,progress(fraction, label=""),is_cancelled(),probe(path)andffmpeg(args, duration=None).ffmpegis the one cancellable runner: it adds-y, parses-progressintoctx.progresswhen you pass the expected outputduration, kills the process when the run is cancelled and raises on a failure without ever exposing stderr or server paths. Use it instead ofsubprocessso cancel works.ctx.summarize(message, links=())lets the last step of a run finish with no media: return[]after calling it and the run completes with nothing added to the Library, showingmessage(and the first(label, href)link: a path inside the app such as/models, with no backslash, whitespace or control character) in place of the Library notice. The run'ssummaryis{message, links: [{label, href}]}.ToolFailed(message)ends the run as failed withmessageshown to the user, andToolCancelled()ends it as cancelled; raise it whenctx.is_cancelled()turns true during a long loop.check_params(params)is an optional override for rules that span parameters (endmust be greater thanstart); raiseInvalidToolParams(field, message).validate_params(spec, params)is what the API, presets and chat all call before running; it applies defaults, coerces, checks ranges and options, and raisesInvalidToolParams.
Chains and the fast paths
A request is a list of steps, and a single tool is a chain of one. The runner fuses neighbouring steps that offer a fast path so the media is decoded and encoded once:
class Mirror(MediaTool):
def video_filter(self, media: ToolMedia, params: dict) -> FilterFragment | None:
return FilterFragment(vf=["hflip"])
def image(self, image, params):
return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)video_filter(media, params)returns aFilterFragment:vfandafare lists of ffmpeg filters,startandenda time window,drop_audioremoves the sound. A fragment that changes the picture size, the length or the quality reports it in the optionalwidth,height,durationandcrfso the next step is validated against the right media. Consecutive fragments merge into one ffmpeg pass; a leadingstart/endbecomes an input seek. It is also asked about audio files, where onlyafand the window apply. ReturnNoneto say "no fast path for this input".image(image, params)receives and returns a PIL image. Consecutive image steps run in memory and the result is saved once, with the source's EXIF orientation already applied.- A step with neither fast path runs
run()on the previous step's output file.
Component-only tools#
An entry with a component and no python is a tool the browser runs itself, the case the old
history_tools key covered. It gets no run endpoint: the catalog lists it so the Tools menu can offer it
for the selected media, and the host mounts the component in a modal.
media_tools:
- id: my-plugin.contact-sheet
label: Contact sheet
icon: grid
accepts: [image]
selection: { min: 2, max: 12 }
scopes: [history]
component: ContactSheetModal.svelteThe catalog serves its component as plugin:<plugin-id>:<asset>, the same reference string a
phrasebook_ops[].component resolves to. The component is mounted with the props { items, generationIds, generations, onClose(), onDone() }: items is the selection as
{ id, kind, url, filename, width, height }, generationIds and generations are filled on the History
page, and onDone() clears the selection once the tool finished. If it needs the backend it calls its own
plugin API route.
Shipping effects#
An effect is a media tool defined by one folder (see Video effects). Declare one or more roots and put
<name>/effect.yml folders in them:
effects:
- path: effects- Each effect registers as
<plugin-id>.<id>under the plugin's source, in the Video editor's Effects panel, the Library Effects menu, presets, chat, MCP and automation. Nothing in the UI names the plugin. - Python renders and analyses (
render.py:fn) may import onlynumpy,torchandsrc.plugin_api.*. - A path outside the plugin folder, a missing folder or any broken
effect.ymlfails the enable with the error, and nothing of the plugin registers. Disabling the plugin removes its effects; the open editor's catalog refreshes. python scripts/effect_parity.py <plugin folder> --goldenwrites the parity goldens to<plugin>/tests/effects/golden/, and the same command without--goldenchecks every render against them.tests/e2e/effect_plugins/e2e-effects/is a complete example (an Invert effect with a shader and a numpy render).
The API#
Successful JSON responses use the usual {success, data} envelope. A refusal answers with detail: {success: false, error, message, ...}; the codes are listed per route.
GET /api/media-tools?kind=&scope=returns{tools: [...]}: every tool for the kind and scope, with the declaration (id,label,icon,accepts,produces,cardinality,params,requires,selection,scopes,editor,preview,component,source) plusrunnable(truewhen the tool has a Python implementation,falsefor a component-only tool that has no run API) andlast_params, the values this user ran the tool with last (ornull).sourceiscoreor the plugin id. A param'smaxis enforced before a run starts, so a value above it is a 400.POST /api/media-tools/runstakes{steps: [{tool, params, hidden?}], inputs: [{item_id} | {generation_file_id}], output: {mode: "new" | "replace" | "update", target_item_id?}}and answers 202{run_id}. A generation file is read straight from storage and the result is always a new Library item;replacekeeps the row, its tags and its collections, and is only allowed for one Library item, tools that return one file per input, and a result of the same kind. When the result is in another format than the item's name says, the name takes the new file's extension: Color key turnsphoto.jpginto a PNG namedphoto.png, a video tool turnsclip.aviintoclip.mp4, and a name an earlier replace left wrong is mended the same way..jpgand.jpeg, or a change of case, are one format and leave the name as it is, and so do a name without a media extension and a result without one.update, the save of an editor stack into the copy a first save made (see The editor API), renames that copy by the same rule. A run takes 1 to 64 visible steps (the steps markedhiddenare skipped and not counted) and 1 to 50 inputs. A 400 before anything runs carries one ofunknown_tool,unsupported_media,invalid_params(withfieldandstep_index),invalid_selectionorreplace_not_allowed; an item that is missing or not the caller's answers 404not_found. A user may have 8 runs waiting at once (429too_many_queued) and nothing starts while the server shuts down (503shutting_down). The same upload quota the editor used applies (403limit_exceeded), and a refusal leaves no file behind.- Results look like normal uploads: each carries its content hash, images get their thumbnails before the run
completes, and a video's thumbnails are rendered right after (the Library card fills in a moment later). A
run item lists
thumbnail_small,thumbnail_mediumandthumbnail_largeURLs for the sizes that exist.replaceswaps the thumbnails together with the file and deletes the old ones. If another run replaced the same item first, the later run fails withconflictand publishes nothing. A run that would create more than 500 files fails withtoo_many_outputsbefore anything is published. GET /api/media-tools/runs/{run_id}returns{run_id, status, progress, label, items, replaced, error, summary}.statusisqueued,running,completed,failedorcancelled;itemsare the resulting Library items; a failed run carrieserror: {code, message}(a tool'srequirescheck ends the run withunsupported_media). An unknown run id, or another user's, is a 404.DELETE /api/media-tools/runs/{run_id}cancels: the encoder is killed and nothing is published.POST /api/media-tools/previewtakes{tool, params, input, time_seconds?}for a tool withpreview: trueand returnsimage/webpwith a long side of at most 512. Pixel params (unit: px) are scaled down together when the largest exceeds 512, so a huge canvas renders as a small one. For a video,time_secondsmust be finite, not negative and not past the end, otherwise 400invalid_paramsontime_seconds. Only two previews render at once; one that cannot get a slot within a few seconds answers 429preview_busy.
Runs are in-process: at most two execute at once, the rest wait their turn, and a finished run is kept for
ten minutes. A user only ever sees, polls and cancels their own runs. After a single-step run completes, its
parameters are stored as that user's last_params for the tool.