@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,903 @@
|
|
|
1
|
+
// FFmpeg filtergraphs as data: a bounded catalog of common
|
|
2
|
+
// filters, a graph of typed nodes and labelled edges, validation, an exact
|
|
3
|
+
// `-filter_complex` string with the escaping ffmpeg's parser expects, a
|
|
4
|
+
// command line quoted for a POSIX shell, cmd.exe or PowerShell (or as an argv array that needs no
|
|
5
|
+
// shell at all), a stable JSON form, and a parser for filter_complex text.
|
|
6
|
+
//
|
|
7
|
+
// This file never runs ffmpeg, never reads a file and never fetches anything.
|
|
8
|
+
// Pure and dependency-free: it runs in the page, in the sandbox Worker (pane
|
|
9
|
+
// code gets ffmpegCommand() and friends from it) and in headless runs.
|
|
10
|
+
//
|
|
11
|
+
// What is NOT done here, on purpose:
|
|
12
|
+
// - A filter outside the catalog (or an option it does not list) stays in the
|
|
13
|
+
// graph as a readable stand-in, `unsupported`, and the graph then refuses to
|
|
14
|
+
// export a command: nothing is approximated or dropped.
|
|
15
|
+
// - Filters that read files (movie, subtitles, lut3d, drawtext's fontfile and
|
|
16
|
+
// textfile, ...) are not in the catalog: a path inside a filter is a second
|
|
17
|
+
// way to name a file, and this tool names files in one place (the inputs).
|
|
18
|
+
// - Inputs and the output are local file names. A name that is a URL or an
|
|
19
|
+
// ffmpeg protocol (http:, concat:, pipe:, ...) is refused.
|
|
20
|
+
|
|
21
|
+
export const LIMITS = Object.freeze({
|
|
22
|
+
inputs: 16,
|
|
23
|
+
nodes: 64,
|
|
24
|
+
maps: 8,
|
|
25
|
+
outputs: 4, // the output and the extra ones together
|
|
26
|
+
text: 200, // any option value
|
|
27
|
+
longText: 400, // drawtext's text
|
|
28
|
+
path: 1024,
|
|
29
|
+
filterComplex: 16_384,
|
|
30
|
+
source: 32_768, // filter_complex text accepted by the parser
|
|
31
|
+
problems: 50,
|
|
32
|
+
json: 262_144,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const V = "video";
|
|
36
|
+
const A = "audio";
|
|
37
|
+
|
|
38
|
+
// ── the catalog ──────────────────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
const expr = (help, extra) => ({ type: "expr", help, ...extra });
|
|
41
|
+
const int = (help, min, max, extra) => ({ type: "int", help, min, max, ...extra });
|
|
42
|
+
const float = (help, min, max, extra) => ({ type: "float", help, min, max, ...extra });
|
|
43
|
+
const time = (help) => ({ type: "time", help });
|
|
44
|
+
const color = (help) => ({ type: "color", help });
|
|
45
|
+
const token = (help) => ({ type: "token", help });
|
|
46
|
+
const enumOf = (help, values) => ({ type: "enum", help, values });
|
|
47
|
+
const bool = (help) => ({ type: "bool", help });
|
|
48
|
+
|
|
49
|
+
const SCALE_FLAGS = ["fast_bilinear", "bilinear", "bicubic", "neighbor", "area", "bicublin", "gauss", "sinc", "lanczos", "spline"];
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* name -> { summary, pads, options, positional? }.
|
|
53
|
+
* `pads(options)` gives the input and output kinds (they depend on options for concat, amix, split, hstack, ...).
|
|
54
|
+
* `positional` lists the option names a bare `filter=a:b` text maps to, only where ffmpeg's order is certain.
|
|
55
|
+
*/
|
|
56
|
+
const fixed = (inKinds, outKinds) => () => ({ in: inKinds, out: outKinds });
|
|
57
|
+
const repeat = (kind, n) => Array.from({ length: n }, () => kind);
|
|
58
|
+
|
|
59
|
+
export const FILTERS = Object.freeze({
|
|
60
|
+
// ── video ──
|
|
61
|
+
scale: { summary: "Resize the picture.", pads: fixed([V], [V]), positional: ["w", "h"], options: { w: expr("output width in pixels, or an expression such as iw/2 (-2 keeps the aspect ratio and an even size)"), h: expr("output height, same rules as w"), flags: enumOf("scaling algorithm", SCALE_FLAGS), force_original_aspect_ratio: enumOf("fit inside (decrease) or cover (increase) the size instead of stretching", ["disable", "decrease", "increase"]), force_divisible_by: int("round the size to a multiple of this", 1, 256) } },
|
|
62
|
+
crop: { summary: "Cut a rectangle out of the picture.", pads: fixed([V], [V]), positional: ["w", "h", "x", "y"], options: { w: expr("width of the result"), h: expr("height of the result"), x: expr("left edge (default: centered)"), y: expr("top edge (default: centered)"), keep_aspect: bool("change the sample aspect ratio to keep the display aspect") } },
|
|
63
|
+
pad: { summary: "Add a border so the picture fits a larger frame.", pads: fixed([V], [V]), positional: ["w", "h", "x", "y", "color"], options: { w: expr("width of the padded frame"), h: expr("height of the padded frame"), x: expr("where the picture sits (default: 0)"), y: expr("where the picture sits (default: 0)"), color: color("border color, e.g. black or 0x336699") } },
|
|
64
|
+
trim: { summary: "Keep one stretch of the video (use with setpts to restart the clock).", pads: fixed([V], [V]), options: { start: time("first second to keep"), end: time("first second to drop"), duration: time("longest stretch to keep"), start_frame: int("first frame to keep", 0, 100_000_000), end_frame: int("first frame to drop", 0, 100_000_000) } },
|
|
65
|
+
setpts: { summary: "Change timestamps: speed up, slow down or restart the clock.", pads: fixed([V], [V]), positional: ["expr"], options: { expr: expr("timestamp expression, e.g. PTS-STARTPTS or 0.5*PTS") } },
|
|
66
|
+
fps: { summary: "Change the frame rate by dropping or repeating frames.", pads: fixed([V], [V]), positional: ["fps"], options: { fps: expr("frames per second, e.g. 30 or 30000/1001"), round: enumOf("how timestamps round", ["zero", "inf", "down", "up", "near"]) } },
|
|
67
|
+
hflip: { summary: "Mirror the picture left to right.", pads: fixed([V], [V]), options: {} },
|
|
68
|
+
vflip: { summary: "Mirror the picture top to bottom.", pads: fixed([V], [V]), options: {} },
|
|
69
|
+
transpose: { summary: "Rotate by quarter turns, optionally mirrored.", pads: fixed([V], [V]), positional: ["dir"], options: { dir: enumOf("0 = rotate 90 counterclockwise and flip, 1 = clockwise, 2 = counterclockwise, 3 = clockwise and flip", ["0", "1", "2", "3", "cclock_flip", "clock", "cclock", "clock_flip"]) } },
|
|
70
|
+
eq: { summary: "Adjust contrast, brightness, saturation and gamma.", pads: fixed([V], [V]), options: { contrast: float("-1000 to 1000 (1 = unchanged)", -1000, 1000), brightness: float("-1 to 1 (0 = unchanged)", -1, 1), saturation: float("0 to 3 (1 = unchanged)", 0, 3), gamma: float("0.1 to 10 (1 = unchanged)", 0.1, 10) } },
|
|
71
|
+
hue: { summary: "Rotate hue and scale saturation.", pads: fixed([V], [V]), positional: ["h", "s"], options: { h: expr("hue angle in degrees"), s: float("saturation, -10 to 10 (1 = unchanged)", -10, 10), b: float("brightness, -10 to 10", -10, 10) } },
|
|
72
|
+
format: { summary: "Convert to a pixel format (e.g. yuv420p for players that need it).", pads: fixed([V], [V]), positional: ["pix_fmts"], options: { pix_fmts: token("pixel format names joined by |, e.g. yuv420p|yuvj420p") } },
|
|
73
|
+
boxblur: { summary: "Blur with a box filter.", pads: fixed([V], [V]), positional: ["luma_radius", "luma_power"], options: { luma_radius: expr("blur radius of the luma plane"), luma_power: int("passes", 0, 8) } },
|
|
74
|
+
gblur: { summary: "Blur with a Gaussian filter.", pads: fixed([V], [V]), positional: ["sigma", "steps"], options: { sigma: float("standard deviation, 0 to 1024", 0, 1024), steps: int("approximation steps", 1, 6) } },
|
|
75
|
+
unsharp: { summary: "Sharpen or blur with an unsharp mask.", pads: fixed([V], [V]), positional: ["luma_msize_x", "luma_msize_y", "luma_amount"], options: { luma_msize_x: int("luma matrix width (odd, 3 to 23)", 3, 23), luma_msize_y: int("luma matrix height (odd, 3 to 23)", 3, 23), luma_amount: float("luma effect strength, -2 to 5", -2, 5) } },
|
|
76
|
+
fade: { summary: "Fade in or out.", pads: fixed([V], [V]), positional: ["type", "start_frame", "nb_frames", "alpha"], options: { type: enumOf("in or out", ["in", "out"]), start_time: time("when the fade starts"), duration: time("how long it lasts"), start_frame: int("first frame of the fade", 0, 100_000_000), nb_frames: int("frames in the fade", 1, 100_000_000), alpha: bool("fade only the alpha channel"), color: color("color to fade to or from") } },
|
|
77
|
+
setsar: { summary: "Set the sample aspect ratio.", pads: fixed([V], [V]), options: { sar: expr("ratio such as 1 or 16/9") } },
|
|
78
|
+
drawtext: { summary: "Draw a line of text (needs a build with libfreetype; the default font comes from fontconfig).", pads: fixed([V], [V]), options: { text: { type: "text", help: "the text. drawtext itself treats a backslash and %{...} specially", max: 400 }, x: expr("left edge"), y: expr("top edge"), fontsize: int("size in pixels", 1, 1000), fontcolor: color("text color, e.g. white or 0xffffff@0.8") } },
|
|
79
|
+
overlay: { summary: "Put the second video over the first.", pads: fixed([V, V], [V]), positional: ["x", "y"], options: { x: expr("left edge of the overlay"), y: expr("top edge of the overlay"), eof_action: enumOf("what to do when the overlay ends", ["repeat", "endall", "pass"]), shortest: bool("end with the shortest input") } },
|
|
80
|
+
hstack: { summary: "Place videos side by side.", pads: (o) => ({ in: repeat(V, count(o.inputs, 2, 2, 8)), out: [V] }), positional: ["inputs"], options: { inputs: int("how many videos (2 to 8)", 2, 8), shortest: bool("end with the shortest input") } },
|
|
81
|
+
vstack: { summary: "Stack videos top to bottom.", pads: (o) => ({ in: repeat(V, count(o.inputs, 2, 2, 8)), out: [V] }), positional: ["inputs"], options: { inputs: int("how many videos (2 to 8)", 2, 8), shortest: bool("end with the shortest input") } },
|
|
82
|
+
split: { summary: "Copy a video stream to several outputs (a label can be used once).", pads: (o) => ({ in: [V], out: repeat(V, count(o.outputs, 2, 2, 8)) }), positional: ["outputs"], options: { outputs: int("how many copies (2 to 8)", 2, 8) } },
|
|
83
|
+
negate: { summary: "Invert the colors.", pads: fixed([V], [V]), options: { negate_alpha: bool("invert the alpha channel too") } },
|
|
84
|
+
reverse: { summary: "Play the video backwards (holds every frame in memory: only for short clips).", pads: fixed([V], [V]), options: {} },
|
|
85
|
+
rotate: { summary: "Rotate by any angle, filling the corners.", pads: fixed([V], [V]), positional: ["angle"], options: { angle: expr("angle in radians, e.g. PI/6 (clockwise)"), ow: expr("output width (default: iw)"), oh: expr("output height (default: ih)"), fillcolor: color("color of the corners, e.g. black or 0x336699"), bilinear: bool("smooth the result (default: on)") } },
|
|
86
|
+
tpad: { summary: "Hold the first frame, or add color, before and after the video.", pads: fixed([V], [V]), options: { start_duration: time("how long to add at the start"), stop_duration: time("how long to add at the end"), start_mode: enumOf("what the start is filled with: a color or a copy of the first frame", ["add", "clone"]), stop_mode: enumOf("what the end is filled with: a color or a copy of the last frame", ["add", "clone"]), color: color("color for the added time, e.g. black") } },
|
|
87
|
+
hqdn3d: { summary: "Reduce noise (a high-quality 3D denoiser).", pads: fixed([V], [V]), positional: ["luma_spatial", "chroma_spatial", "luma_tmp", "chroma_tmp"], options: { luma_spatial: float("luma spatial strength, 0 to 255 (default 4)", 0, 255), chroma_spatial: float("chroma spatial strength, 0 to 255 (default 3)", 0, 255), luma_tmp: float("luma temporal strength, 0 to 255 (default 6)", 0, 255), chroma_tmp: float("chroma temporal strength, 0 to 255 (default 4.5)", 0, 255) } },
|
|
88
|
+
edgedetect: { summary: "Draw the edges of the picture.", pads: fixed([V], [V]), options: { low: float("low threshold, 0 to 1", 0, 1), high: float("high threshold, 0 to 1", 0, 1), mode: enumOf("white edges on black, edges in color, or Canny", ["wires", "colormix", "canny"]) } },
|
|
89
|
+
vignette: { summary: "Darken the corners.", pads: fixed([V], [V]), positional: ["angle"], options: { angle: expr("lens angle in radians, e.g. PI/5 (smaller is stronger)"), mode: enumOf("darken the edges (forward) or brighten them (backward)", ["forward", "backward"]) } },
|
|
90
|
+
palettegen: { summary: "Work out the best 256-color palette for a GIF (feed it to paletteuse).", pads: fixed([V], [V]), positional: ["max_colors", "reserve_transparent"], options: { max_colors: int("colors in the palette, 2 to 256", 2, 256), reserve_transparent: bool("keep one color for transparency"), stats_mode: enumOf("measure the whole video, only what changes, or every frame alone", ["full", "diff", "single"]) } },
|
|
91
|
+
paletteuse: { summary: "Reduce the first video to the palette on the second (palettegen makes it).", pads: fixed([V, V], [V]), positional: ["dither", "bayer_scale", "diff_mode"], options: { dither: enumOf("how color is spread where the palette is short", ["bayer", "heckbert", "floyd_steinberg", "sierra2", "sierra2_4a", "sierra3", "burkes", "atkinson", "none"]), bayer_scale: int("pattern size of the bayer dither, 0 to 5", 0, 5), diff_mode: enumOf("redraw only the changed rectangle", ["none", "rectangle"]) } },
|
|
92
|
+
null: { summary: "Pass video through unchanged.", pads: fixed([V], [V]), options: {} },
|
|
93
|
+
// ── audio ──
|
|
94
|
+
volume: { summary: "Change the loudness.", pads: fixed([A], [A]), positional: ["volume"], options: { volume: expr("a factor (0.5) or decibels (-6dB)"), precision: enumOf("sample math", ["fixed", "float", "double"]) } },
|
|
95
|
+
atrim: { summary: "Keep one stretch of the audio.", pads: fixed([A], [A]), options: { start: time("first second to keep"), end: time("first second to drop"), duration: time("longest stretch to keep") } },
|
|
96
|
+
asetpts: { summary: "Change audio timestamps.", pads: fixed([A], [A]), positional: ["expr"], options: { expr: expr("timestamp expression, e.g. PTS-STARTPTS") } },
|
|
97
|
+
atempo: { summary: "Change the speed without changing the pitch.", pads: fixed([A], [A]), positional: ["tempo"], options: { tempo: float("0.5 to 100 (1 = unchanged)", 0.5, 100) } },
|
|
98
|
+
afade: { summary: "Fade the audio in or out.", pads: fixed([A], [A]), positional: ["type"], options: { type: enumOf("in or out", ["in", "out"]), start_time: time("when the fade starts"), duration: time("how long it lasts"), curve: enumOf("fade shape", ["tri", "qsin", "hsin", "esin", "log", "ipar", "qua", "cub", "squ", "cbr", "par", "exp", "iqsin", "ihsin", "dese", "desi", "losi", "sinc", "isinc", "nofade"]) } },
|
|
99
|
+
aresample: { summary: "Change the sample rate.", pads: fixed([A], [A]), positional: ["sample_rate"], options: { sample_rate: int("samples per second", 800, 768_000) } },
|
|
100
|
+
aformat: { summary: "Convert the sample format, rate or channel layout.", pads: fixed([A], [A]), positional: ["sample_fmts", "sample_rates", "channel_layouts"], options: { sample_fmts: token("e.g. s16 or fltp"), sample_rates: token("e.g. 44100"), channel_layouts: token("e.g. stereo or mono") } },
|
|
101
|
+
amix: { summary: "Mix several audio streams into one.", pads: (o) => ({ in: repeat(A, count(o.inputs, 2, 2, 8)), out: [A] }), positional: ["inputs", "duration"], options: { inputs: int("how many streams (2 to 8)", 2, 8), duration: enumOf("when the mix ends", ["longest", "shortest", "first"]), normalize: bool("scale each input down by the number of inputs") } },
|
|
102
|
+
asplit: { summary: "Copy an audio stream to several outputs.", pads: (o) => ({ in: [A], out: repeat(A, count(o.outputs, 2, 2, 8)) }), positional: ["outputs"], options: { outputs: int("how many copies (2 to 8)", 2, 8) } },
|
|
103
|
+
areverse: { summary: "Play the audio backwards (holds all of it in memory: only for short clips).", pads: fixed([A], [A]), options: {} },
|
|
104
|
+
highpass: { summary: "Cut the low frequencies.", pads: fixed([A], [A]), positional: ["f"], options: { f: float("cutoff in hertz, 1 to 192000", 1, 192000), poles: int("1 (gentle) or 2 (steeper)", 1, 2), width_type: enumOf("how width is read: h hertz, q Q-factor, o octaves, s slope, k kilohertz", ["h", "q", "o", "s", "k"]), width: float("band width, in the unit width_type names", 0, 192000) } },
|
|
105
|
+
lowpass: { summary: "Cut the high frequencies.", pads: fixed([A], [A]), positional: ["f"], options: { f: float("cutoff in hertz, 1 to 192000", 1, 192000), poles: int("1 (gentle) or 2 (steeper)", 1, 2), width_type: enumOf("how width is read: h hertz, q Q-factor, o octaves, s slope, k kilohertz", ["h", "q", "o", "s", "k"]), width: float("band width, in the unit width_type names", 0, 192000) } },
|
|
106
|
+
loudnorm: { summary: "Even out the loudness to a target (EBU R128, one pass).", pads: fixed([A], [A]), positional: ["I", "LRA", "TP"], options: { I: float("integrated loudness target in LUFS, -70 to -5 (default -24)", -70, -5), LRA: float("loudness range target, 1 to 50 (default 7)", 1, 50), TP: float("true-peak ceiling in dBTP, -9 to 0 (default -2)", -9, 0) } },
|
|
107
|
+
adelay: { summary: "Delay the audio, per channel.", pads: fixed([A], [A]), positional: ["delays", "all"], options: { delays: token("milliseconds for each channel, joined by |, e.g. 300|500"), all: bool("use the first delay for every channel") } },
|
|
108
|
+
apad: { summary: "Add silence after the audio.", pads: fixed([A], [A]), options: { pad_dur: time("how much silence to add"), whole_dur: time("pad until the audio is this long") } },
|
|
109
|
+
anull: { summary: "Pass audio through unchanged.", pads: fixed([A], [A]), options: {} },
|
|
110
|
+
// ── both ──
|
|
111
|
+
concat: {
|
|
112
|
+
summary: "Join segments one after another. n segments, each with v video and a audio streams, in that order.",
|
|
113
|
+
pads: (o) => {
|
|
114
|
+
const n = count(o.n, 2, 2, 8);
|
|
115
|
+
const v = count(o.v, 1, 0, 1);
|
|
116
|
+
const a = count(o.a, 0, 0, 1);
|
|
117
|
+
const per = [...repeat(V, v), ...repeat(A, a)];
|
|
118
|
+
return { in: Array.from({ length: n }, () => per).flat(), out: per };
|
|
119
|
+
},
|
|
120
|
+
positional: ["n", "v", "a"],
|
|
121
|
+
options: { n: int("how many segments (2 to 8)", 2, 8), v: int("video streams per segment (0 or 1)", 0, 1), a: int("audio streams per segment (0 or 1)", 0, 1) },
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/** An option that sets a pad count: its value (or the filter's default) when it is a whole number in range, else the default (validation reports the bad value). */
|
|
126
|
+
function count(value, fallback, min, max) {
|
|
127
|
+
if (value === undefined || value === "") return fallback;
|
|
128
|
+
const n = typeof value === "number" ? value : /^-?\d+$/.test(String(value)) ? Number(value) : NaN;
|
|
129
|
+
return Number.isInteger(n) && n >= min && n <= max ? n : fallback;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The catalog as a plain list (for help text and the page): name, summary, pad kinds at defaults, options. */
|
|
133
|
+
export function catalog() {
|
|
134
|
+
return Object.entries(FILTERS).map(([name, f]) => {
|
|
135
|
+
const pads = f.pads({});
|
|
136
|
+
return {
|
|
137
|
+
name,
|
|
138
|
+
summary: f.summary,
|
|
139
|
+
in: pads.in,
|
|
140
|
+
out: pads.out,
|
|
141
|
+
options: Object.entries(f.options).map(([key, o]) => ({ name: key, type: o.type, help: o.help, ...(o.min !== undefined ? { min: o.min, max: o.max } : {}), ...(o.values ? { values: [...o.values] } : {}) })),
|
|
142
|
+
positional: f.positional ?? [],
|
|
143
|
+
};
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ── what the output may be ───────────────────────────────────────────────────
|
|
148
|
+
|
|
149
|
+
/** Containers and the codecs each takes: the limits of what an exported command (and any build that runs it) is asked to do. */
|
|
150
|
+
export const CONTAINERS = Object.freeze({
|
|
151
|
+
mp4: { ext: ["mp4", "m4v", "mov"], video: ["libx264", "libx265", "mpeg4"], audio: ["aac", "libmp3lame", "flac"] },
|
|
152
|
+
matroska: { ext: ["mkv", "mka"], video: ["libx264", "libx265", "libvpx", "libvpx-vp9", "mpeg4"], audio: ["aac", "libopus", "libvorbis", "libmp3lame", "flac", "pcm_s16le"] },
|
|
153
|
+
webm: { ext: ["webm"], video: ["libvpx", "libvpx-vp9"], audio: ["libopus", "libvorbis"] },
|
|
154
|
+
gif: { ext: ["gif"], video: ["gif"], audio: [] },
|
|
155
|
+
wav: { ext: ["wav"], video: [], audio: ["pcm_s16le"] },
|
|
156
|
+
mp3: { ext: ["mp3"], video: [], audio: ["libmp3lame"] },
|
|
157
|
+
ogg: { ext: ["ogg", "oga", "opus"], video: [], audio: ["libopus", "libvorbis"] },
|
|
158
|
+
});
|
|
159
|
+
const PRESETS = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"];
|
|
160
|
+
const PIX_FMTS = ["yuv420p", "yuv422p", "yuv444p", "yuva420p", "rgb24", "rgba", "gray"];
|
|
161
|
+
const OUTPUT_KEYS = ["file", "maps", "container", "videoCodec", "audioCodec", "crf", "preset", "videoBitrate", "audioBitrate", "pixelFormat", "metadata"];
|
|
162
|
+
const INPUT_KEYS = ["file", "ss", "t"];
|
|
163
|
+
const GRAPH_KEYS = ["format", "version", "inputs", "nodes", "output", "extraOutputs"];
|
|
164
|
+
const NODE_KEYS = ["id", "filter", "options", "in", "out", "unsupported", "raw"];
|
|
165
|
+
|
|
166
|
+
// ── validation ───────────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
const ID = /^[A-Za-z_][A-Za-z0-9_-]{0,31}$/;
|
|
169
|
+
const LABEL = /^[A-Za-z_][A-Za-z0-9_]{0,31}$/;
|
|
170
|
+
const STREAM = /^(\d{1,2}):([va])(?::(\d{1,2}))?$/;
|
|
171
|
+
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/; // every control character except tab and newline (text allows those; nothing else does)
|
|
172
|
+
const CONTROL_STRICT = /[\u0000-\u001f\u007f]/;
|
|
173
|
+
const TIME = /^(?:\d+(?:\.\d+)?(?:ms|us|s)?|(?:\d{1,3}:)?\d{1,2}:\d{1,2}(?:\.\d+)?)$/;
|
|
174
|
+
const COLOR = /^(?:(?:0x|#)[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?|[a-z]{3,20})(?:@(?:0|1|0?\.\d+|\d(?:\.\d+)?))?$/;
|
|
175
|
+
const TOKEN = /^[A-Za-z0-9_.|+-]{1,64}$/;
|
|
176
|
+
const BITRATE = /^\d{1,7}(?:\.\d+)?[kKmM]?$/;
|
|
177
|
+
const PROTOCOL = /^[A-Za-z][A-Za-z0-9+.-]+:/; // two or more letters: a Windows drive letter (C:\) is not one
|
|
178
|
+
|
|
179
|
+
/** Seconds in a time TIME accepts (12.5, 500ms, 1:02:03.5). */
|
|
180
|
+
function inSeconds(text) {
|
|
181
|
+
const m = /^(\d+(?:\.\d+)?)(ms|us|s)?$/.exec(text);
|
|
182
|
+
if (m) return Number(m[1]) * (m[2] === "ms" ? 1e-3 : m[2] === "us" ? 1e-6 : 1);
|
|
183
|
+
return text.split(":").reduce((total, part) => total * 60 + Number(part), 0);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const isObject = (x) => x && typeof x === "object" && !Array.isArray(x);
|
|
187
|
+
const clip = (s, n = 60) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
188
|
+
const show = (v) => clip(typeof v === "string" ? JSON.stringify(v) : String(v));
|
|
189
|
+
|
|
190
|
+
/** A usable file name for ffmpeg: a non-empty string, no control characters, no URL or protocol. Returns a problem text or "". */
|
|
191
|
+
export function pathProblem(path, what) {
|
|
192
|
+
if (typeof path !== "string" || !path) return `${what} needs a file name`;
|
|
193
|
+
if (path.length > LIMITS.path) return `${what} is longer than ${LIMITS.path} characters`;
|
|
194
|
+
if (CONTROL_STRICT.test(path)) return `${what} has a control character in it`;
|
|
195
|
+
if (/^\s|\s$/.test(path)) return `${what} starts or ends with a space; ffmpeg would take the name as written, but most shells hide the difference`;
|
|
196
|
+
if (path.includes("://") || (PROTOCOL.test(path) && !/^file:/i.test(path))) return `${what} looks like a URL or an ffmpeg protocol (${show(path.split(":")[0] + ":")}); only local files are exported. Use ./name to name a local file that has a colon`;
|
|
197
|
+
return "";
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The argument ffmpeg gets for a file name: never an option (a leading "-") and never a protocol (a "name:" prefix). */
|
|
201
|
+
export function safePath(path) {
|
|
202
|
+
if (path === "-" || path.startsWith("-")) return `./${path}`;
|
|
203
|
+
if (/^file:/i.test(path)) return path;
|
|
204
|
+
if (path.includes(":") && !/^[A-Za-z]:[\\/]/.test(path) && !path.startsWith("/") && !path.startsWith("./")) return `./${path}`;
|
|
205
|
+
return path;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function checkOption(filter, key, spec, value, add) {
|
|
209
|
+
const where = `${filter}.${key}`;
|
|
210
|
+
const bad = (message) => add("error", "bad-option", `${where}: ${message}`);
|
|
211
|
+
const isStr = typeof value === "string";
|
|
212
|
+
const isNum = typeof value === "number";
|
|
213
|
+
if (!isStr && !isNum && typeof value !== "boolean") return bad(`expected a ${spec.type}, got ${value === null ? "null" : typeof value}`);
|
|
214
|
+
if (isNum && !Number.isFinite(value)) return bad("not a finite number");
|
|
215
|
+
const s = String(value);
|
|
216
|
+
switch (spec.type) {
|
|
217
|
+
case "int": {
|
|
218
|
+
if (!(isNum ? Number.isInteger(value) : /^-?\d+$/.test(s))) return bad(`${show(value)} is not a whole number`);
|
|
219
|
+
const n = Number(s);
|
|
220
|
+
if (n < spec.min || n > spec.max) bad(`${n} is outside ${spec.min} to ${spec.max}`);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
case "float": {
|
|
224
|
+
if (!(isNum || /^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(s))) return bad(`${show(value)} is not a number`);
|
|
225
|
+
const n = Number(s);
|
|
226
|
+
if (n < spec.min || n > spec.max) bad(`${n} is outside ${spec.min} to ${spec.max}`);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
case "bool":
|
|
230
|
+
if (!(typeof value === "boolean" || ["0", "1", "true", "false"].includes(s))) bad(`${show(value)} is not true or false`);
|
|
231
|
+
return;
|
|
232
|
+
case "enum":
|
|
233
|
+
if (!spec.values.includes(s)) bad(`${show(value)} is not one of ${spec.values.join(", ")}`);
|
|
234
|
+
return;
|
|
235
|
+
case "time":
|
|
236
|
+
if (!TIME.test(s)) bad(`${show(value)} is not a time (seconds like 12.5, or [HH:]MM:SS[.m])`);
|
|
237
|
+
return;
|
|
238
|
+
case "color":
|
|
239
|
+
if (!COLOR.test(s)) bad(`${show(value)} is not a color (a name like white, 0xRRGGBB or #RRGGBB, optionally @alpha)`);
|
|
240
|
+
return;
|
|
241
|
+
case "token":
|
|
242
|
+
if (!TOKEN.test(s)) bad(`${show(value)} is not a plain name list (letters, digits and _ . | + -)`);
|
|
243
|
+
return;
|
|
244
|
+
case "text": {
|
|
245
|
+
if (s.length > (spec.max ?? LIMITS.longText)) return bad(`longer than ${spec.max ?? LIMITS.longText} characters`);
|
|
246
|
+
if (CONTROL.test(s)) return bad("has a control character in it");
|
|
247
|
+
if (/%\{|\\/.test(s)) add("warning", "text-expansion", `${where}: drawtext treats a backslash and %{...} in the text specially; they are passed on exactly as written`);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
default: {
|
|
251
|
+
// "expr": a string ffmpeg evaluates; nothing is evaluated here
|
|
252
|
+
if (s.length > LIMITS.text) return bad(`longer than ${LIMITS.text} characters`);
|
|
253
|
+
if (CONTROL_STRICT.test(s)) return bad("has a control character in it");
|
|
254
|
+
let depth = 0;
|
|
255
|
+
for (const c of s) if (c === "(" ? ++depth : c === ")" ? --depth : 0) if (depth < 0) break;
|
|
256
|
+
if (depth !== 0) bad(`unbalanced parentheses in ${show(s)}`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The options of a node as ffmpeg's text shows them: catalog order first, then anything else, as strings. */
|
|
262
|
+
function orderedOptions(spec, options) {
|
|
263
|
+
const known = Object.keys(spec?.options ?? {});
|
|
264
|
+
const keys = Object.keys(options ?? {});
|
|
265
|
+
return [...known.filter((k) => k in options), ...keys.filter((k) => !known.includes(k)).sort()];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const optionText = (v) => (typeof v === "boolean" ? (v ? "1" : "0") : String(v));
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Check a graph. `{ ok, problems: [{ level: "error" | "warning", code, message, node? }], unsupported: [node ids], order: [node ids] }`.
|
|
272
|
+
* `ok` means there is no error: the graph can be exported as a command. A node whose filter or option is not in the catalog
|
|
273
|
+
* is an error (`unsupported-filter`, `unsupported-option`): it stays readable in the graph but is never approximated.
|
|
274
|
+
*/
|
|
275
|
+
export function validate(graph) {
|
|
276
|
+
const problems = [];
|
|
277
|
+
const unsupported = [];
|
|
278
|
+
let truncated = false;
|
|
279
|
+
const add = (level, code, message, node) => {
|
|
280
|
+
if (problems.length >= LIMITS.problems) return void (truncated = true);
|
|
281
|
+
problems.push({ level, code, message, ...(node ? { node } : {}) });
|
|
282
|
+
};
|
|
283
|
+
const done = (order = []) => {
|
|
284
|
+
if (truncated) problems.push({ level: "warning", code: "more", message: `more than ${LIMITS.problems} problems; fix these first` });
|
|
285
|
+
return { ok: !problems.some((p) => p.level === "error"), problems, unsupported, order };
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
if (!isObject(graph)) {
|
|
289
|
+
add("error", "shape", "a graph is an object: { format, version, inputs, nodes, output }");
|
|
290
|
+
return done();
|
|
291
|
+
}
|
|
292
|
+
for (const k of Object.keys(graph)) if (!GRAPH_KEYS.includes(k)) add("error", "shape", `unknown field ${show(k)} in the graph (known: ${GRAPH_KEYS.join(", ")})`);
|
|
293
|
+
if (graph.format !== undefined && graph.format !== "mallory-filtergraph" && graph.format !== "viaframe-filtergraph") add("error", "shape", `format is ${show(graph.format)}, expected "mallory-filtergraph"`);
|
|
294
|
+
if (graph.version !== undefined && graph.version !== 1) add("error", "shape", `version ${show(graph.version)} is not one this reads (1)`);
|
|
295
|
+
|
|
296
|
+
// inputs
|
|
297
|
+
const inputs = Array.isArray(graph.inputs) ? graph.inputs : [];
|
|
298
|
+
if (!Array.isArray(graph.inputs) || !inputs.length) add("error", "inputs", "inputs is a list of at least one { file }");
|
|
299
|
+
if (inputs.length > LIMITS.inputs) add("error", "inputs", `at most ${LIMITS.inputs} inputs`);
|
|
300
|
+
inputs.forEach((input, i) => {
|
|
301
|
+
if (!isObject(input)) return add("error", "inputs", `input ${i} is an object { file }`);
|
|
302
|
+
for (const k of Object.keys(input)) if (!INPUT_KEYS.includes(k)) add("error", "inputs", `input ${i}: unknown field ${show(k)} (known: ${INPUT_KEYS.join(", ")})`);
|
|
303
|
+
const p = pathProblem(input.file, `input ${i}`);
|
|
304
|
+
if (p) add("error", "path", p);
|
|
305
|
+
for (const k of ["ss", "t"]) {
|
|
306
|
+
if (input[k] === undefined) continue;
|
|
307
|
+
const v = input[k];
|
|
308
|
+
const text = typeof v === "number" || typeof v === "string" ? String(v) : "";
|
|
309
|
+
if (!TIME.test(text)) add("error", "inputs", `input ${i}: ${k} is a time (seconds like 12.5, or [HH:]MM:SS[.m]); got ${show(v)}`);
|
|
310
|
+
else if (k === "t" && !(inSeconds(text) > 0)) add("error", "inputs", `input ${i}: t is how long to read, more than 0`);
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// nodes
|
|
315
|
+
const nodes = Array.isArray(graph.nodes) ? graph.nodes : [];
|
|
316
|
+
if (!Array.isArray(graph.nodes)) add("error", "nodes", "nodes is a list");
|
|
317
|
+
if (nodes.length > LIMITS.nodes) add("error", "nodes", `at most ${LIMITS.nodes} nodes`);
|
|
318
|
+
const ids = new Set();
|
|
319
|
+
const producer = new Map(); // label -> { id, kind }
|
|
320
|
+
const consumed = new Map(); // label -> node id (labels made by nodes: each is used once)
|
|
321
|
+
const pads = new Map(); // node id -> { in, out } kinds, or null when unknown
|
|
322
|
+
const usable = [];
|
|
323
|
+
nodes.slice(0, LIMITS.nodes).forEach((node, i) => {
|
|
324
|
+
if (!isObject(node)) return add("error", "nodes", `node ${i} is an object { id, filter, options, in, out }`);
|
|
325
|
+
const id = typeof node.id === "string" ? node.id : `#${i}`;
|
|
326
|
+
for (const k of Object.keys(node)) if (!NODE_KEYS.includes(k)) add("error", "nodes", `node ${id}: unknown field ${show(k)}`, id);
|
|
327
|
+
if (typeof node.id !== "string" || !ID.test(node.id)) add("error", "nodes", `node ${i}: id must be letters, digits, _ and - (starting with a letter or _), at most 32`, id);
|
|
328
|
+
else if (ids.has(node.id)) add("error", "nodes", `node id ${show(node.id)} is used twice`, id);
|
|
329
|
+
else ids.add(node.id);
|
|
330
|
+
const list = (key) => (Array.isArray(node[key]) && node[key].every((x) => typeof x === "string") ? node[key] : (add("error", "nodes", `node ${id}: ${key} is a list of labels`, id), []));
|
|
331
|
+
const nin = list("in");
|
|
332
|
+
const nout = list("out");
|
|
333
|
+
const options = node.options === undefined ? {} : isObject(node.options) ? node.options : (add("error", "nodes", `node ${id}: options is an object`, id), {});
|
|
334
|
+
const spec = Object.hasOwn(FILTERS, node.filter) ? FILTERS[node.filter] : undefined;
|
|
335
|
+
let known = Boolean(spec) && !node.unsupported;
|
|
336
|
+
if (typeof node.filter !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,31}$/.test(node.filter)) add("error", "nodes", `node ${id}: filter must be a filter name`, id);
|
|
337
|
+
else if (!spec) {
|
|
338
|
+
add("error", "unsupported-filter", `node ${id}: the filter ${show(node.filter)} is not in this catalog (${Object.keys(FILTERS).length} filters); it is kept as written, not approximated, and nothing is exported until it is replaced or removed`, id);
|
|
339
|
+
unsupported.push(id);
|
|
340
|
+
known = false;
|
|
341
|
+
} else if (node.unsupported) {
|
|
342
|
+
add("error", "unsupported-filter", `node ${id}: marked unsupported; it is kept as written, not approximated`, id);
|
|
343
|
+
unsupported.push(id);
|
|
344
|
+
}
|
|
345
|
+
if (node.raw !== undefined && typeof node.raw !== "string") add("error", "nodes", `node ${id}: raw is a string`, id);
|
|
346
|
+
if (spec && known) {
|
|
347
|
+
for (const key of Object.keys(options)) {
|
|
348
|
+
const o = spec.options[key];
|
|
349
|
+
if (!o) {
|
|
350
|
+
add("error", "unsupported-option", `node ${id}: ${node.filter} has no supported option ${show(key)} (supported: ${Object.keys(spec.options).join(", ") || "none"}); not approximated`, id);
|
|
351
|
+
if (!unsupported.includes(id)) unsupported.push(id);
|
|
352
|
+
} else {
|
|
353
|
+
checkOption(node.filter, key, o, options[key], (level, code, message) => add(level, code, `node ${id}: ${message}`, id));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
for (const required of REQUIRED[node.filter] ?? []) if (!(required in options)) add("error", "missing-option", `node ${id}: ${node.filter} needs ${required}`, id);
|
|
357
|
+
for (const note of semantics(node.filter, options)) add(note.level, note.code, `node ${id}: ${note.message}`, id);
|
|
358
|
+
}
|
|
359
|
+
const kinds = known ? spec.pads(options) : null;
|
|
360
|
+
pads.set(id, kinds);
|
|
361
|
+
if (kinds) {
|
|
362
|
+
if (nin.length !== kinds.in.length) add("error", "pads", `node ${id}: ${node.filter} takes ${kinds.in.length} input${kinds.in.length === 1 ? "" : "s"} (${kinds.in.join(", ") || "none"}) but in lists ${nin.length}`, id);
|
|
363
|
+
if (nout.length !== kinds.out.length) add("error", "pads", `node ${id}: ${node.filter} makes ${kinds.out.length} output${kinds.out.length === 1 ? "" : "s"} (${kinds.out.join(", ") || "none"}) but out lists ${nout.length}`, id);
|
|
364
|
+
}
|
|
365
|
+
nout.forEach((label, k) => {
|
|
366
|
+
if (!LABEL.test(label)) return add("error", "label", `node ${id}: ${show(label)} is not a label (letters, digits and _, starting with a letter or _, at most 32)`, id);
|
|
367
|
+
if (STREAM.test(label)) return;
|
|
368
|
+
if (producer.has(label)) return add("error", "label", `node ${id}: label ${show(label)} is already made by node ${producer.get(label).id}`, id);
|
|
369
|
+
producer.set(label, { id, kind: kinds?.out[k] ?? null });
|
|
370
|
+
});
|
|
371
|
+
usable.push({ id, node, nin, nout, kinds, valid: ID.test(String(node.id)) });
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
// edges
|
|
375
|
+
const used = (label, by) => {
|
|
376
|
+
if (consumed.has(label)) add("error", "label", `${show(label)} is used by both ${consumed.get(label)} and ${by}; ffmpeg lets a made label feed one place only (use split or asplit to copy it)`, by);
|
|
377
|
+
else consumed.set(label, by);
|
|
378
|
+
};
|
|
379
|
+
const checkSource = (label, by, wantKind) => {
|
|
380
|
+
const m = STREAM.exec(label);
|
|
381
|
+
if (m) {
|
|
382
|
+
if (Number(m[1]) >= inputs.length) add("error", "label", `${by}: ${label} names input ${m[1]} but there ${inputs.length === 1 ? "is 1 input" : `are ${inputs.length} inputs`}`, by);
|
|
383
|
+
const kind = m[2] === "v" ? V : A;
|
|
384
|
+
if (wantKind && wantKind !== kind) add("error", "kind", `${by}: ${label} is ${kind} but ${wantKind} is needed`, by);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
const p = producer.get(label);
|
|
388
|
+
if (!p) return add("error", "label", `${by}: ${show(label)} is not an input stream (like 0:v) or an output label of a node`, by);
|
|
389
|
+
used(label, by);
|
|
390
|
+
if (wantKind && p.kind && wantKind !== p.kind) add("error", "kind", `${by}: ${show(label)} is ${p.kind} (from ${p.id}) but ${wantKind} is needed`, by);
|
|
391
|
+
};
|
|
392
|
+
for (const { id, nin, kinds } of usable) nin.forEach((label, k) => checkSource(label, id, kinds?.in[k]));
|
|
393
|
+
|
|
394
|
+
// order: a node after the nodes whose labels it takes (stable: the listed order breaks ties)
|
|
395
|
+
const deps = new Map(usable.map((u) => [u.id, new Set(u.nin.map((l) => producer.get(l)?.id).filter(Boolean))]));
|
|
396
|
+
const order = [];
|
|
397
|
+
const placed = new Set();
|
|
398
|
+
for (let progress = true; progress && order.length < usable.length; ) {
|
|
399
|
+
progress = false;
|
|
400
|
+
for (const u of usable) {
|
|
401
|
+
if (placed.has(u.id) || ![...deps.get(u.id)].every((d) => placed.has(d))) continue;
|
|
402
|
+
placed.add(u.id);
|
|
403
|
+
order.push(u.id);
|
|
404
|
+
progress = true;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (order.length < usable.length) add("error", "cycle", `the graph loops back on itself (${usable.filter((u) => !placed.has(u.id)).map((u) => u.id).join(", ")})`);
|
|
408
|
+
|
|
409
|
+
// outputs: the output, then any extra ones (each its own file, maps and codecs)
|
|
410
|
+
const extra = graph.extraOutputs;
|
|
411
|
+
if (extra !== undefined && !Array.isArray(extra)) add("error", "output", "extraOutputs is a list of outputs");
|
|
412
|
+
const outputs = [graph.output, ...(Array.isArray(extra) ? extra : [])];
|
|
413
|
+
if (outputs.length > LIMITS.outputs) add("error", "output", `at most ${LIMITS.outputs} outputs (the output and extraOutputs together)`);
|
|
414
|
+
const files = new Map();
|
|
415
|
+
outputs.slice(0, LIMITS.outputs).forEach((out, n) => {
|
|
416
|
+
const name = n === 0 ? "the output" : `output ${n + 1}`;
|
|
417
|
+
const addOut = n === 0 ? add : (level, code, message, node) => add(level, code, `${name}: ${message}`, node);
|
|
418
|
+
if (!isObject(out)) return add("error", "output", n === 0 ? "output is an object { file, maps }" : `${name} is an object { file, maps }`);
|
|
419
|
+
for (const k of Object.keys(out)) if (!OUTPUT_KEYS.includes(k)) addOut("error", "output", `unknown output field ${show(k)} (known: ${OUTPUT_KEYS.join(", ")})`);
|
|
420
|
+
const p = pathProblem(out.file, name);
|
|
421
|
+
if (p) add("error", "path", p);
|
|
422
|
+
else {
|
|
423
|
+
if (files.has(out.file)) add("error", "output", `${name} writes the same file as ${files.get(out.file)} (${show(out.file)}); each output needs its own file`);
|
|
424
|
+
else files.set(out.file, name);
|
|
425
|
+
if (inputs.some((i) => isObject(i) && i.file === out.file)) add("error", "output", `${name} (${show(out.file)}) is also an input; ffmpeg would write over what it reads`);
|
|
426
|
+
}
|
|
427
|
+
const maps = Array.isArray(out.maps) && out.maps.every((m) => typeof m === "string") ? out.maps : [];
|
|
428
|
+
if (!maps.length || maps.length > LIMITS.maps) addOut("error", "output", `maps lists 1 to ${LIMITS.maps} labels or streams for the output`);
|
|
429
|
+
const kinds = [];
|
|
430
|
+
maps.forEach((label) => {
|
|
431
|
+
checkSource(label, name, undefined);
|
|
432
|
+
const m = STREAM.exec(label);
|
|
433
|
+
kinds.push(m ? (m[2] === "v" ? V : A) : producer.get(label)?.kind);
|
|
434
|
+
});
|
|
435
|
+
checkOutputOptions(out, kinds, addOut);
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
// every made label must go somewhere
|
|
439
|
+
for (const [label, p] of producer) if (!consumed.has(label)) add("error", "unconnected", `${show(label)} (from ${p.id}) is not used by any node or by the output; ffmpeg refuses a filter output that goes nowhere`, p.id);
|
|
440
|
+
return done(order);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const REQUIRED = { rotate: ["angle"], adelay: ["delays"], scale: [], crop: ["w", "h"], pad: ["w", "h"], setpts: ["expr"], fps: ["fps"], transpose: ["dir"], format: ["pix_fmts"], volume: ["volume"], asetpts: ["expr"], atempo: ["tempo"], aresample: ["sample_rate"], drawtext: ["text"], fade: ["type"], afade: ["type"], setsar: ["sar"], concat: [], gblur: ["sigma"] };
|
|
444
|
+
|
|
445
|
+
/** Rules between options of one filter. */
|
|
446
|
+
function semantics(filter, o) {
|
|
447
|
+
const notes = [];
|
|
448
|
+
if (filter === "scale" && o.w === undefined && o.h === undefined) notes.push({ level: "error", code: "missing-option", message: "scale needs w or h" });
|
|
449
|
+
if (filter === "trim" || filter === "atrim") {
|
|
450
|
+
if (o.start === undefined && o.end === undefined && o.duration === undefined && o.start_frame === undefined && o.end_frame === undefined) notes.push({ level: "error", code: "missing-option", message: `${filter} needs start, end or duration` });
|
|
451
|
+
if (o.end !== undefined && o.duration !== undefined) notes.push({ level: "warning", code: "ambiguous", message: `${filter} with both end and duration: ffmpeg uses the earlier` });
|
|
452
|
+
}
|
|
453
|
+
if (filter === "concat") {
|
|
454
|
+
const v = Number(o.v ?? 1);
|
|
455
|
+
const a = Number(o.a ?? 0);
|
|
456
|
+
if (v + a === 0) notes.push({ level: "error", code: "pads", message: "concat needs v or a to be 1" });
|
|
457
|
+
}
|
|
458
|
+
if (filter === "fade" && o.start_time === undefined && o.start_frame === undefined) notes.push({ level: "warning", code: "default", message: "fade starts at the beginning unless start_time or start_frame is set" });
|
|
459
|
+
if (filter === "tpad" && o.start_duration === undefined && o.stop_duration === undefined) notes.push({ level: "error", code: "missing-option", message: "tpad needs start_duration or stop_duration" });
|
|
460
|
+
if (filter === "apad" && o.pad_dur === undefined && o.whole_dur === undefined) notes.push({ level: "error", code: "missing-option", message: "apad needs pad_dur or whole_dur" });
|
|
461
|
+
if (filter === "reverse" || filter === "areverse") notes.push({ level: "warning", code: "memory", message: `${filter} holds the whole stream in memory; use trim or atrim first on anything long` });
|
|
462
|
+
if (filter === "drawtext") notes.push({ level: "warning", code: "build", message: "drawtext needs an ffmpeg built with libfreetype" });
|
|
463
|
+
return notes;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function checkOutputOptions(out, kinds, add) {
|
|
467
|
+
const ext = typeof out.file === "string" ? out.file.toLowerCase().split(".").pop() : "";
|
|
468
|
+
const inferred = Object.keys(CONTAINERS).find((c) => CONTAINERS[c].ext.includes(ext));
|
|
469
|
+
const containerName = out.container ?? inferred;
|
|
470
|
+
if (out.container !== undefined && !Object.hasOwn(CONTAINERS, out.container)) add("error", "output", `container ${show(out.container)} is not one of ${Object.keys(CONTAINERS).join(", ")}`);
|
|
471
|
+
else if (!containerName) add("error", "output", `the file extension ${show(ext)} is not one this exports (${Object.values(CONTAINERS).flatMap((c) => c.ext).join(", ")}); name a container or change the file name`);
|
|
472
|
+
const c = containerName && CONTAINERS[containerName];
|
|
473
|
+
if (out.container && inferred && out.container !== inferred && c) add("warning", "output", `the file name ends in .${ext} but the container is ${out.container}`);
|
|
474
|
+
const hasVideo = kinds.includes(V);
|
|
475
|
+
const hasAudio = kinds.includes(A);
|
|
476
|
+
const one = (key, list, label, none) => {
|
|
477
|
+
const v = out[key];
|
|
478
|
+
if (v === undefined) return;
|
|
479
|
+
if (v === "none") return;
|
|
480
|
+
if (!list.includes(v)) add("error", "output", `${key} ${show(v)} is not one of ${list.join(", ")}`);
|
|
481
|
+
else if (!none) add("error", "output", `${key} is set but no ${label} stream is mapped`);
|
|
482
|
+
else if (c && !c[label].includes(v)) add("error", "output", `${containerName} cannot hold ${v} (it takes ${c[label].join(", ") || "no " + label})`);
|
|
483
|
+
};
|
|
484
|
+
one("videoCodec", [...new Set(Object.values(CONTAINERS).flatMap((x) => x.video))], "video", hasVideo);
|
|
485
|
+
one("audioCodec", [...new Set(Object.values(CONTAINERS).flatMap((x) => x.audio))], "audio", hasAudio);
|
|
486
|
+
if (c) {
|
|
487
|
+
if (hasVideo && !c.video.length) add("error", "output", `${containerName} holds no video, but a video stream is mapped`);
|
|
488
|
+
if (hasAudio && !c.audio.length) add("error", "output", `${containerName} holds no audio, but an audio stream is mapped`);
|
|
489
|
+
}
|
|
490
|
+
if (out.crf !== undefined && !(Number.isInteger(out.crf) && out.crf >= 0 && out.crf <= 63)) add("error", "output", `crf is a whole number from 0 to 63`);
|
|
491
|
+
if (out.crf !== undefined && !hasVideo) add("error", "output", "crf is set but no video stream is mapped");
|
|
492
|
+
if (out.preset !== undefined && !PRESETS.includes(out.preset)) add("error", "output", `preset is one of ${PRESETS.join(", ")}`);
|
|
493
|
+
if (out.preset !== undefined && !["libx264", "libx265"].includes(out.videoCodec ?? "")) add("error", "output", "preset applies to libx264 and libx265; set videoCodec to one of them");
|
|
494
|
+
for (const key of ["videoBitrate", "audioBitrate"]) if (out[key] !== undefined && !BITRATE.test(String(out[key]))) add("error", "output", `${key} looks like 2500k or 1.5M`);
|
|
495
|
+
if (out.pixelFormat !== undefined && !PIX_FMTS.includes(out.pixelFormat)) add("error", "output", `pixelFormat is one of ${PIX_FMTS.join(", ")}`);
|
|
496
|
+
if (out.metadata !== undefined && out.metadata !== "keep" && out.metadata !== "strip") add("error", "output", 'metadata is "keep" or "strip"');
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// ── escaping ─────────────────────────────────────────────────────────────────
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* ffmpeg parses a filtergraph in two layers (its docs call them levels), each with the same
|
|
503
|
+
* escape: a backslash makes the next character literal, and '...' makes everything inside literal.
|
|
504
|
+
* - level 1: the options of one filter, `key=value:key=value`, are split at ":";
|
|
505
|
+
* - level 2: the filtergraph text is split at the characters [ ] , ; (and = after a name).
|
|
506
|
+
* A value is escaped for level 1, and the whole `key=value:...` string then for level 2. Leading and
|
|
507
|
+
* trailing whitespace of a token is stripped by ffmpeg unless escaped, so edge whitespace is escaped
|
|
508
|
+
* at both levels. Only backslashes are used (no quotes), so the result is the same in every shell
|
|
509
|
+
* once quoted for it.
|
|
510
|
+
*/
|
|
511
|
+
function escapeWith(text, specials) {
|
|
512
|
+
const ws = (c) => SPACES.includes(c);
|
|
513
|
+
let lead = 0;
|
|
514
|
+
while (lead < text.length && ws(text[lead])) lead++;
|
|
515
|
+
let trail = text.length;
|
|
516
|
+
while (trail > lead && ws(text[trail - 1])) trail--;
|
|
517
|
+
let out = "";
|
|
518
|
+
for (let i = 0; i < text.length; i++) {
|
|
519
|
+
const c = text[i];
|
|
520
|
+
out += c === "\\" || c === "'" || specials.includes(c) || (ws(c) && (i < lead || i >= trail)) ? `\\${c}` : c;
|
|
521
|
+
}
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
/** Escape one option value for level 1 (the "key=value:key=value" string of a filter). */
|
|
525
|
+
export const escapeOptionValue = (value) => escapeWith(String(value), ":");
|
|
526
|
+
/** Escape a whole filter's option string for level 2 (the filtergraph text). */
|
|
527
|
+
export const escapeFilterArgs = (args) => escapeWith(args, "[],;");
|
|
528
|
+
|
|
529
|
+
// ── compiling ────────────────────────────────────────────────────────────────
|
|
530
|
+
|
|
531
|
+
function nodeText(node, spec) {
|
|
532
|
+
const keys = orderedOptions(spec, node.options ?? {});
|
|
533
|
+
const args = keys.map((k) => `${k}=${escapeOptionValue(optionText(node.options[k]))}`).join(":");
|
|
534
|
+
return `${node.filter}${args ? `=${escapeFilterArgs(args)}` : ""}`;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const pad = (label) => `[${label}]`;
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* The `-filter_complex` string, nodes in dependency order (the listed order where it allows), one chain per node joined by ";".
|
|
541
|
+
* `{ ok: true, filterComplex }` or `{ ok: false, problems }` (the validation errors: an unsupported node is one).
|
|
542
|
+
*/
|
|
543
|
+
export function compileFilterComplex(graph) {
|
|
544
|
+
const v = validate(graph);
|
|
545
|
+
if (!v.ok) return { ok: false, problems: v.problems.filter((p) => p.level === "error"), unsupported: v.unsupported };
|
|
546
|
+
const byId = new Map(graph.nodes.map((n) => [n.id, n]));
|
|
547
|
+
const filterComplex = v.order.map((id) => {
|
|
548
|
+
const n = byId.get(id);
|
|
549
|
+
return `${n.in.map(pad).join("")}${nodeText(n, FILTERS[n.filter])}${n.out.map(pad).join("")}`;
|
|
550
|
+
}).join(";");
|
|
551
|
+
if (filterComplex.length > LIMITS.filterComplex) return { ok: false, problems: [{ level: "error", code: "too-long", message: `the filtergraph is longer than ${LIMITS.filterComplex} characters` }], unsupported: [] };
|
|
552
|
+
return { ok: true, filterComplex };
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** The graph as filter_complex text for reading, including unsupported stand-ins as they were written. Never a command. */
|
|
556
|
+
export function toText(graph) {
|
|
557
|
+
const nodes = Array.isArray(graph?.nodes) ? graph.nodes : [];
|
|
558
|
+
return nodes
|
|
559
|
+
.filter(isObject)
|
|
560
|
+
.map((n) => {
|
|
561
|
+
const spec = Object.hasOwn(FILTERS, n.filter) && !n.unsupported ? FILTERS[n.filter] : undefined;
|
|
562
|
+
const body = spec || !n.raw ? nodeText({ ...n, options: n.options ?? {} }, spec) : `${n.filter}=${escapeFilterArgs(n.raw)}`;
|
|
563
|
+
return `${(n.in ?? []).map(pad).join("")}${body}${(n.out ?? []).map(pad).join("")}`;
|
|
564
|
+
})
|
|
565
|
+
.join(";");
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// ── the command ──────────────────────────────────────────────────────────────
|
|
569
|
+
|
|
570
|
+
/** What a re-encode does to metadata, as a -style provenance record (no personal value in it). */
|
|
571
|
+
export function provenanceOf(graph) {
|
|
572
|
+
const outs = [graph?.output ?? {}, ...(Array.isArray(graph?.extraOutputs) ? graph.extraOutputs : [])].filter(isObject);
|
|
573
|
+
const stripped = outs.filter((o) => o.metadata === "strip");
|
|
574
|
+
const strip = stripped.length === outs.length;
|
|
575
|
+
const mixed = stripped.length > 0 && !strip;
|
|
576
|
+
const base = { pixels: "re-encoded" };
|
|
577
|
+
if (strip) {
|
|
578
|
+
return {
|
|
579
|
+
...base,
|
|
580
|
+
metadata: "removed",
|
|
581
|
+
removed: ["global tags (title, creation time, location)", "chapters", "attached pictures and cover art", "data, subtitle and other streams that are not mapped", "Content Credentials (C2PA)"],
|
|
582
|
+
note: "-map_metadata -1 and -map_chapters -1 ask ffmpeg to copy no file-level tags or chapters; ffmpeg writes its own encoder tag, and stream tags such as language may follow the stream",
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
return {
|
|
586
|
+
...base,
|
|
587
|
+
metadata: "partly-kept",
|
|
588
|
+
kept: ["file-level tags of input 0 (title, creation time, any location tag), chapters of input 0"],
|
|
589
|
+
removed: ["attached pictures and cover art", "data, subtitle and other streams that are not mapped", "Content Credentials (C2PA)", "display rotation: filters apply it and clear it"],
|
|
590
|
+
note: mixed
|
|
591
|
+
? `${outs.map((o, i) => (o.metadata === "strip" ? `output ${i + 1}` : "")).filter(Boolean).join(" and ")} copy no file-level tags (metadata "strip"); the others copy those of input 0 because their metadata is "keep"`
|
|
592
|
+
: 'file-level tags of input 0 are copied because metadata is "keep"; set it to "strip" to copy none',
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** Quote one argument for a POSIX shell (sh, bash, zsh, dash): bare when it is only safe characters, else in single quotes. */
|
|
597
|
+
export function shellQuote(arg) {
|
|
598
|
+
const s = String(arg);
|
|
599
|
+
if (s.includes("\u0000")) throw new RangeError("an argument can't contain a NUL character");
|
|
600
|
+
if (s === "") return "''";
|
|
601
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Quote one argument for cmd.exe, the way the Microsoft C runtime (and so ffmpeg.exe) splits a command line: double quotes, a
|
|
606
|
+
* quote as \", the backslashes before a quote doubled. Then every character cmd.exe itself reads (& | < > ( ) ^ ! and the quotes)
|
|
607
|
+
* gets a caret, so cmd.exe passes the line on untouched. A "%" can't be carried (cmd.exe expands %name% even inside quotes, and
|
|
608
|
+
* a command line has no escape for it) and neither can a line break: those throw a RangeError, and exportCommand leaves the form out.
|
|
609
|
+
*/
|
|
610
|
+
export function cmdQuote(arg) {
|
|
611
|
+
const s = String(arg);
|
|
612
|
+
if (s.includes("\u0000")) throw new RangeError("an argument can't contain a NUL character");
|
|
613
|
+
if (/[\r\n]/.test(s)) throw new RangeError("cmd.exe can't carry a line break inside an argument");
|
|
614
|
+
if (s.includes("%")) throw new RangeError('cmd.exe expands %name% even inside quotes and a command line has no escape for "%"');
|
|
615
|
+
if (s !== "" && /^[A-Za-z0-9_@+:./\\-]+$/.test(s)) return s;
|
|
616
|
+
let out = '"';
|
|
617
|
+
let slashes = 0;
|
|
618
|
+
for (const c of s) {
|
|
619
|
+
if (c === "\\") slashes++;
|
|
620
|
+
else if (c === '"') (out += `${"\\".repeat(slashes * 2 + 1)}"`, (slashes = 0));
|
|
621
|
+
else (out += "\\".repeat(slashes) + c, (slashes = 0));
|
|
622
|
+
}
|
|
623
|
+
out += `${"\\".repeat(slashes * 2)}"`;
|
|
624
|
+
return out.replace(/[()!^"<>&|]/g, (c) => `^${c}`);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Quote one argument for PowerShell: bare when it is only safe characters, else in single quotes (a quote, and PowerShell's curly
|
|
629
|
+
* single quotes, doubled). An empty argument and an argument with a double quote throw a RangeError: how PowerShell passes them to a
|
|
630
|
+
* program differs between 5.1 and 7 (the empty one is dropped by 5.1), so no one form is right for both.
|
|
631
|
+
*/
|
|
632
|
+
export function powershellQuote(arg) {
|
|
633
|
+
const s = String(arg);
|
|
634
|
+
if (s.includes("\u0000")) throw new RangeError("an argument can't contain a NUL character");
|
|
635
|
+
if (s === "") throw new RangeError("PowerShell 5.1 drops an empty argument when it starts a program");
|
|
636
|
+
if (s.includes('"')) throw new RangeError("PowerShell 5.1 and 7 pass a double quote inside an argument to a program differently");
|
|
637
|
+
return /^[A-Za-z0-9_+:./\\-]+$/.test(s) ? s : `'${s.replace(/['\u2018\u2019\u201a\u201b]/g, (c) => c + c)}'`;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const group = (argv) => {
|
|
641
|
+
// argv split into display lines: the program, each input, the filtergraph, each map, then each other option with its value
|
|
642
|
+
const lines = [];
|
|
643
|
+
let line = [];
|
|
644
|
+
const flush = () => (line.length ? lines.push(line) : 0, (line = []));
|
|
645
|
+
for (let i = 0; i < argv.length; i++) {
|
|
646
|
+
const a = argv[i];
|
|
647
|
+
if (i === 0) line.push(a);
|
|
648
|
+
else if (a.startsWith("-") && a.length > 1 && !/^-\d/.test(a) && line.length) (flush(), line.push(a));
|
|
649
|
+
else line.push(a);
|
|
650
|
+
}
|
|
651
|
+
flush();
|
|
652
|
+
return lines;
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
/** The arguments of one output (its maps, codecs and file) added to argv. */
|
|
656
|
+
function outputArgs(graph, out, argv) {
|
|
657
|
+
for (const m of out.maps) argv.push("-map", STREAM.test(m) ? m : `[${m}]`);
|
|
658
|
+
const kinds = out.maps.map((m) => {
|
|
659
|
+
const s = STREAM.exec(m);
|
|
660
|
+
return s ? (s[2] === "v" ? V : A) : mapKind(graph, m);
|
|
661
|
+
});
|
|
662
|
+
const hasVideo = kinds.includes(V);
|
|
663
|
+
const hasAudio = kinds.includes(A);
|
|
664
|
+
if (out.videoCodec === "none") argv.push("-vn");
|
|
665
|
+
else if (hasVideo && out.videoCodec) argv.push("-c:v", out.videoCodec);
|
|
666
|
+
if (out.audioCodec === "none") argv.push("-an");
|
|
667
|
+
else if (hasAudio && out.audioCodec) argv.push("-c:a", out.audioCodec);
|
|
668
|
+
if (out.crf !== undefined) argv.push("-crf", String(out.crf));
|
|
669
|
+
if (out.preset) argv.push("-preset", out.preset);
|
|
670
|
+
if (out.videoBitrate) argv.push("-b:v", String(out.videoBitrate));
|
|
671
|
+
if (out.audioBitrate) argv.push("-b:a", String(out.audioBitrate));
|
|
672
|
+
if (out.pixelFormat) argv.push("-pix_fmt", out.pixelFormat);
|
|
673
|
+
if (out.metadata === "strip") argv.push("-map_metadata", "-1", "-map_chapters", "-1");
|
|
674
|
+
else argv.push("-map_metadata", "0", "-map_chapters", "0");
|
|
675
|
+
const container = out.container ?? Object.keys(CONTAINERS).find((c) => CONTAINERS[c].ext.includes(out.file.toLowerCase().split(".").pop()));
|
|
676
|
+
if (container) argv.push("-f", container);
|
|
677
|
+
argv.push(safePath(out.file));
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** ffmpeg's argv (without a shell) for the graph. */
|
|
681
|
+
function argvOf(graph, filterComplex, options) {
|
|
682
|
+
const argv = ["ffmpeg", "-hide_banner", options.overwrite ? "-y" : "-n"];
|
|
683
|
+
for (const input of graph.inputs) {
|
|
684
|
+
if (input.ss !== undefined) argv.push("-ss", String(input.ss));
|
|
685
|
+
if (input.t !== undefined) argv.push("-t", String(input.t));
|
|
686
|
+
argv.push("-i", safePath(input.file));
|
|
687
|
+
}
|
|
688
|
+
if (graph.nodes.length) argv.push("-filter_complex", filterComplex);
|
|
689
|
+
for (const out of [graph.output, ...(graph.extraOutputs ?? [])]) outputArgs(graph, out, argv);
|
|
690
|
+
return argv;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function mapKind(graph, label) {
|
|
694
|
+
for (const n of graph.nodes) {
|
|
695
|
+
const k = n.out.indexOf(label);
|
|
696
|
+
if (k >= 0) return FILTERS[n.filter].pads(n.options ?? {}).out[k];
|
|
697
|
+
}
|
|
698
|
+
return undefined;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Export a graph as a command. `options`: `overwrite` (-y instead of -n), `multiline` (the POSIX form breaks lines at options).
|
|
703
|
+
* Returns `{ ok: true, argv, posix, filterComplex, graph (stable JSON text), provenance, warnings }` or `{ ok: false, problems }`.
|
|
704
|
+
* Nothing is executed: `argv` is for a caller that starts a process itself without a shell; `posix` is text for a person to paste.
|
|
705
|
+
*/
|
|
706
|
+
export function exportCommand(graph, options = {}) {
|
|
707
|
+
const c = compileFilterComplex(graph);
|
|
708
|
+
if (!c.ok) return c;
|
|
709
|
+
const v = validate(graph);
|
|
710
|
+
const argv = argvOf(graph, c.filterComplex, options);
|
|
711
|
+
const posix = options.multiline ? group(argv).map((l) => l.map(shellQuote).join(" ")).join(" \\\n ") : argv.map(shellQuote).join(" ");
|
|
712
|
+
// The Windows forms: a form is left out, with the reason, when an argument can't be carried (a % for cmd.exe, a " for PowerShell).
|
|
713
|
+
const unquotable = {};
|
|
714
|
+
const windows = (name, quote, join) => {
|
|
715
|
+
try {
|
|
716
|
+
return options.multiline ? group(argv).map((l) => l.map(quote).join(" ")).join(join) : argv.map(quote).join(" ");
|
|
717
|
+
} catch (error) {
|
|
718
|
+
unquotable[name] = `${error.message}; use the POSIX form or argv`;
|
|
719
|
+
return undefined;
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
const cmd = windows("cmd", cmdQuote, " ^\n ");
|
|
723
|
+
const powershell = windows("powershell", powershellQuote, " `\n ");
|
|
724
|
+
return { ok: true, argv, posix, ...(cmd !== undefined ? { cmd } : {}), ...(powershell !== undefined ? { powershell } : {}), unquotable, filterComplex: c.filterComplex, graph: graphToJSON(graph), provenance: provenanceOf(graph), warnings: v.problems.filter((p) => p.level === "warning") };
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// ── JSON ─────────────────────────────────────────────────────────────────────
|
|
728
|
+
|
|
729
|
+
/** Stable text for a graph: fixed key order, options in catalog order. The same graph always gives the same bytes. */
|
|
730
|
+
export function graphToJSON(graph) {
|
|
731
|
+
const nodes = (graph.nodes ?? []).map((n) => {
|
|
732
|
+
const spec = Object.hasOwn(FILTERS, n.filter) ? FILTERS[n.filter] : undefined;
|
|
733
|
+
const options = {};
|
|
734
|
+
for (const k of orderedOptions(spec, n.options ?? {})) options[k] = n.options[k];
|
|
735
|
+
return { id: n.id, filter: n.filter, ...(Object.keys(options).length ? { options } : {}), in: n.in ?? [], out: n.out ?? [], ...(n.unsupported ? { unsupported: true } : {}), ...(n.raw !== undefined ? { raw: n.raw } : {}) };
|
|
736
|
+
});
|
|
737
|
+
const o = graph.output ?? {};
|
|
738
|
+
const output = {};
|
|
739
|
+
for (const k of OUTPUT_KEYS) if (o[k] !== undefined) output[k] = o[k];
|
|
740
|
+
const stable = (o) => {
|
|
741
|
+
const r = {};
|
|
742
|
+
for (const k of OUTPUT_KEYS) if (o?.[k] !== undefined) r[k] = o[k];
|
|
743
|
+
return r;
|
|
744
|
+
};
|
|
745
|
+
const more = Array.isArray(graph.extraOutputs) ? graph.extraOutputs.map(stable) : [];
|
|
746
|
+
return JSON.stringify({ format: "mallory-filtergraph", version: 1, inputs: (graph.inputs ?? []).map((i) => ({ file: i.file, ...(i.ss !== undefined ? { ss: i.ss } : {}), ...(i.t !== undefined ? { t: i.t } : {}) })), nodes, output, ...(more.length ? { extraOutputs: more } : {}) }, null, 2);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** Read a graph from JSON text (or an object). `{ ok, graph, problems }`; a graph with problems is still returned so it can be shown and fixed. */
|
|
750
|
+
export function graphFromJSON(source) {
|
|
751
|
+
let graph = source;
|
|
752
|
+
if (typeof source === "string") {
|
|
753
|
+
if (source.length > LIMITS.json) return { ok: false, problems: [{ level: "error", code: "too-long", message: `the graph is longer than ${LIMITS.json} characters` }] };
|
|
754
|
+
try {
|
|
755
|
+
graph = JSON.parse(source);
|
|
756
|
+
} catch (error) {
|
|
757
|
+
return { ok: false, problems: [{ level: "error", code: "json", message: `not JSON: ${String(error?.message ?? error)}` }] };
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const v = validate(graph);
|
|
761
|
+
return { ok: v.ok, graph, problems: v.problems, unsupported: v.unsupported };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// ── reading filter_complex text ──────────────────────────────────────────────
|
|
765
|
+
|
|
766
|
+
const SPACES = " \n\t\r";
|
|
767
|
+
|
|
768
|
+
/** ffmpeg's av_get_token: `\x` is x, '...' is literal, edge spaces are trimmed unless escaped. Returns [token, next index]. */
|
|
769
|
+
export function getToken(s, i, terms) {
|
|
770
|
+
while (i < s.length && SPACES.includes(s[i])) i++;
|
|
771
|
+
let out = "";
|
|
772
|
+
let end = 0;
|
|
773
|
+
while (i < s.length && !terms.includes(s[i])) {
|
|
774
|
+
const c = s[i++];
|
|
775
|
+
if (c === "\\" && i < s.length) (out += s[i++], (end = out.length));
|
|
776
|
+
else if (c === "'") {
|
|
777
|
+
while (i < s.length && s[i] !== "'") out += s[i++];
|
|
778
|
+
if (i < s.length) (i++, (end = out.length));
|
|
779
|
+
} else out += c;
|
|
780
|
+
}
|
|
781
|
+
while (out.length > end && SPACES.includes(out[out.length - 1])) out = out.slice(0, -1);
|
|
782
|
+
return [out, i];
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** Split the options of a filter (level 1): `k=v:k=v` and bare values. Returns [{ key?, value }]. */
|
|
786
|
+
export function splitOptions(args) {
|
|
787
|
+
const items = [];
|
|
788
|
+
let i = 0;
|
|
789
|
+
while (i <= args.length) {
|
|
790
|
+
let token;
|
|
791
|
+
[token, i] = getToken(args, i, "=:");
|
|
792
|
+
if (args[i] === "=") {
|
|
793
|
+
let value;
|
|
794
|
+
[value, i] = getToken(args, i + 1, ":");
|
|
795
|
+
items.push({ key: token, value });
|
|
796
|
+
} else items.push({ value: token });
|
|
797
|
+
if (i >= args.length) break;
|
|
798
|
+
i++; // the ":"
|
|
799
|
+
}
|
|
800
|
+
return items;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* Read filter_complex text into a graph's `nodes` (and the labels of its inputs and outputs). Chains written with "," become nodes
|
|
805
|
+
* joined by generated labels (c1, c2, ...). A filter or option outside the catalog becomes an `unsupported` stand-in with its text kept in `raw`.
|
|
806
|
+
* Unlabelled pads are refused (name them), as is an unterminated label. `{ ok, nodes, problems }`.
|
|
807
|
+
*/
|
|
808
|
+
export function parseFilterComplex(text) {
|
|
809
|
+
const problems = [];
|
|
810
|
+
const fail = (message) => (problems.push({ level: "error", code: "parse", message }), { ok: false, nodes: [], problems });
|
|
811
|
+
if (typeof text !== "string") return fail("filter_complex text is a string");
|
|
812
|
+
if (text.length > LIMITS.source) return fail(`longer than ${LIMITS.source} characters`);
|
|
813
|
+
const nodes = [];
|
|
814
|
+
let generated = 0;
|
|
815
|
+
let i = 0;
|
|
816
|
+
const skip = () => {
|
|
817
|
+
while (i < text.length && SPACES.includes(text[i])) i++;
|
|
818
|
+
};
|
|
819
|
+
const labels = () => {
|
|
820
|
+
const out = [];
|
|
821
|
+
for (skip(); text[i] === "["; skip()) {
|
|
822
|
+
const close = text.indexOf("]", i);
|
|
823
|
+
if (close < 0) return null;
|
|
824
|
+
out.push(text.slice(i + 1, close).trim());
|
|
825
|
+
i = close + 1;
|
|
826
|
+
}
|
|
827
|
+
return out;
|
|
828
|
+
};
|
|
829
|
+
while (true) {
|
|
830
|
+
skip();
|
|
831
|
+
if (i >= text.length) break;
|
|
832
|
+
let previous = null; // the node a "," chains to
|
|
833
|
+
do {
|
|
834
|
+
skip();
|
|
835
|
+
const ins = labels();
|
|
836
|
+
if (!ins) return fail("a [label is never closed");
|
|
837
|
+
let name;
|
|
838
|
+
[name, i] = getToken(text, i, "=,;[");
|
|
839
|
+
if (!name) return fail(`expected a filter name at position ${i}`);
|
|
840
|
+
let args = "";
|
|
841
|
+
let hasArgs = false;
|
|
842
|
+
if (text[i] === "=") ([args, i] = getToken(text, i + 1, "[],;")), (hasArgs = true);
|
|
843
|
+
const outs = labels();
|
|
844
|
+
if (!outs) return fail("a [label is never closed");
|
|
845
|
+
if (nodes.length >= LIMITS.nodes) return fail(`more than ${LIMITS.nodes} filters`);
|
|
846
|
+
if (previous) {
|
|
847
|
+
const link = `c${++generated}`;
|
|
848
|
+
previous.out.push(link);
|
|
849
|
+
ins.unshift(link);
|
|
850
|
+
}
|
|
851
|
+
const spec = Object.hasOwn(FILTERS, name) ? FILTERS[name] : undefined;
|
|
852
|
+
const node = { id: `${name}${nodes.length + 1}`.slice(0, 32), filter: name, options: {}, in: ins, out: outs };
|
|
853
|
+
if (!spec) Object.assign(node, { unsupported: true, ...(hasArgs ? { raw: args } : {}) });
|
|
854
|
+
else {
|
|
855
|
+
const positional = [...(spec.positional ?? [])];
|
|
856
|
+
let at = 0;
|
|
857
|
+
let named = false;
|
|
858
|
+
for (const item of hasArgs && args !== "" ? splitOptions(args) : []) {
|
|
859
|
+
if (item.key !== undefined) {
|
|
860
|
+
named = true;
|
|
861
|
+
node.options[item.key] = item.value;
|
|
862
|
+
} else if (named || at >= positional.length) {
|
|
863
|
+
Object.assign(node, { unsupported: true, raw: args });
|
|
864
|
+
node.options = {};
|
|
865
|
+
problems.push({ level: "error", code: "positional", message: `${name}: ${named ? "an unnamed value after a named one" : "more unnamed values than this reads"}; write key=value`, node: node.id });
|
|
866
|
+
break;
|
|
867
|
+
} else node.options[positional[at++]] = item.value;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
nodes.push(node);
|
|
871
|
+
previous = node;
|
|
872
|
+
skip();
|
|
873
|
+
} while (text[i] === "," && (i++, true));
|
|
874
|
+
skip();
|
|
875
|
+
if (i < text.length) {
|
|
876
|
+
if (text[i] !== ";") return fail(`unexpected ${show(text[i])} at position ${i}`);
|
|
877
|
+
i++;
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
// unlabelled pads can't be placed in a graph that names every edge
|
|
881
|
+
for (const n of nodes) {
|
|
882
|
+
const spec = Object.hasOwn(FILTERS, n.filter) && !n.unsupported ? FILTERS[n.filter] : undefined;
|
|
883
|
+
if (!spec) continue;
|
|
884
|
+
const kinds = spec.pads(n.options);
|
|
885
|
+
if (n.in.length < kinds.in.length) problems.push({ level: "error", code: "unlabelled", message: `${n.id}: ${kinds.in.length - n.in.length} input pad(s) have no label; write [0:v] or [name] before the filter`, node: n.id });
|
|
886
|
+
if (n.out.length < kinds.out.length) problems.push({ level: "error", code: "unlabelled", message: `${n.id}: ${kinds.out.length - n.out.length} output pad(s) have no label; write [name] after the filter`, node: n.id });
|
|
887
|
+
}
|
|
888
|
+
const ids = new Set();
|
|
889
|
+
for (const n of nodes) {
|
|
890
|
+
let id = n.id;
|
|
891
|
+
for (let k = 2; ids.has(id); k++) id = `${n.id.slice(0, 28)}_${k}`;
|
|
892
|
+
ids.add((n.id = id));
|
|
893
|
+
}
|
|
894
|
+
return { ok: !problems.length, nodes, problems };
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/** Build a graph from filter_complex text and the files: `{ ok, graph, problems }` (problems of the parse, then of validation). */
|
|
898
|
+
export function graphFromFilterComplex(text, { inputs, output }) {
|
|
899
|
+
const parsed = parseFilterComplex(text);
|
|
900
|
+
const graph = { format: "mallory-filtergraph", version: 1, inputs: inputs.map((file) => ({ file })), nodes: parsed.nodes, output };
|
|
901
|
+
const v = validate(graph);
|
|
902
|
+
return { ok: parsed.ok && v.ok, graph, problems: [...parsed.problems, ...v.problems], unsupported: v.unsupported };
|
|
903
|
+
}
|