Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/guides/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ Select a node, then choose an action from its toolbar.

- **Images**: Crop, rotate, flip, adjust colors, work with layers, add text, shapes, or annotations, and edit selections.
- **Video and audio**: Extract frames, trim, extract audio tracks, and process clips.
When trimming a video, choose WebM (the default) or MP4 under **Output format**. Choose MP4 if your model requires MP4 reference video.
- **AI tools**: Extend images, erase content, remove backgrounds, edit images with AI, upscale, and more. Availability depends on the connected models.

For a local edit, mark an area or create a selection first, then enter your instructions and confirm the action. If a required model capability is missing, follow the tool's instructions to configure it. Hover over a disabled control for an explanation.
Expand Down
1 change: 1 addition & 0 deletions docs/guides/user-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制

- **图片**:裁剪、旋转、翻转、调色、图层、文字、形状、标注和选区编辑。
- **视频与音频**:取帧、裁剪、音轨提取和片段处理。
使用「时长修剪」时,可在「保存格式」中选择 WebM(默认)或 MP4。如果模型要求参考视频为 MP4,请选择 MP4。
- **AI 工具**:扩图、消除、抠图、智能改图、超清等,是否可用取决于已接入模型。

需要局部修改时先标记区域或创建选区,再填写要求并确认执行。缺少所需模型能力时,按工具提示补充配置;灰色入口以悬停提示为准。
Expand Down
65 changes: 51 additions & 14 deletions src/canvas/LocalMediaEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
mediaBlobDataUrl,
recordLocalVideoRange,
} from "./localMediaRuntime.ts";
import { renderTrimmedMp4, type VideoTrimFormat } from "./videoActionRuntime.ts";
import { useT } from "../i18n/I18nProvider.tsx";
import "./local-media-tools.css";
import {
Expand Down Expand Up @@ -84,6 +85,7 @@ export function LocalMediaEditor({
[error, setError] = useState("");
const [crop, setCrop] = useState<VideoCrop | null>(null);
const [cropRatio, setCropRatio] = useState("free");
const [outputFormat, setOutputFormat] = useState<VideoTrimFormat>("webm");
const [probingDuration, setProbingDuration] = useState(false);
const durationProbe = useRef<AbortController | null>(null);
const probeAttempted = useRef(false);
Expand All @@ -100,6 +102,7 @@ export function LocalMediaEditor({
abort = useRef<AbortController | null>(null),
previewing = useRef(false);
const isAudio = node.type === "audio" || mode === "extract-audio";
const videoTrimFormat = mode === "trim" && !isAudio ? outputFormat : undefined;
useEffect(() => {
active.current = true;
const element = media.current;
Expand All @@ -111,6 +114,7 @@ export function LocalMediaEditor({
probeAttempted.current = false;
setCrop(null);
setCropRatio("free");
setOutputFormat("webm");
setDimensions({ width: 0, height: 0 });
setDuration(node.data.media?.durationSeconds ?? 0);
setEnd(node.data.media?.durationSeconds ?? 0);
Expand Down Expand Up @@ -296,6 +300,7 @@ export function LocalMediaEditor({
start,
end,
crop,
outputFormat: videoTrimFormat,
position: mode === "frame" ? position : undefined,
});
const commit = async (output: LocalMediaOutput) => {
Expand All @@ -315,7 +320,13 @@ export function LocalMediaEditor({
? "audio-trim"
: "video-trim",
[node.id],
{ start, end, frameTime: element.currentTime, ...(crop ?? {}) },
{
start,
end,
frameTime: element.currentTime,
...(crop ?? {}),
...(videoTrimFormat ? { outputFormat: videoTrimFormat } : {}),
},
),
)) === false
)
Expand Down Expand Up @@ -384,30 +395,39 @@ export function LocalMediaEditor({
return;
}
const video = element as HTMLVideoElement;
const blob = await recordLocalVideoRange(
video,
start,
end,
controller.signal,
(seconds) => {
if (owns(controller)) setPosition(seconds);
},
mode === "crop" ? { crop: crop! } : undefined,
);
const onPosition = (seconds: number) => {
if (owns(controller)) setPosition(seconds);
};
const blob =
videoTrimFormat === "mp4"
? await renderTrimmedMp4(
node.data.src,
{ start, end },
controller.signal,
onPosition,
)
: await recordLocalVideoRange(
video,
start,
end,
controller.signal,
onPosition,
mode === "crop" ? { crop: crop! } : undefined,
);
const src = await mediaBlobDataUrl(blob, controller.signal);
const measured = await withMediaDuration(
{
id: node.id,
kind: "video",
title: node.data.title,
src,
mimeType: "video/webm",
mimeType: blob.type,
},
controller.signal,
);
await commit({
src,
mimeType: "video/webm",
mimeType: blob.type,
kind: "video",
title: `${node.data.title} · ${
mode === "crop"
Expand Down Expand Up @@ -458,7 +478,9 @@ export function LocalMediaEditor({
? t("tools.localMedia.subtitle.frame")
: isAudio
? t("tools.localMedia.subtitle.audio")
: t("tools.localMedia.subtitle.video")
: videoTrimFormat === "mp4"
? t("tools.localMedia.subtitle.mp4")
: t("tools.localMedia.subtitle.video")
}
onClose={onClose}
onApply={() => void apply()}
Expand Down Expand Up @@ -666,6 +688,21 @@ export function LocalMediaEditor({
duration: duration.toFixed(2),
})}
</span>
{videoTrimFormat && (
<label>
{t("tools.videoEditor.outputFormat")}
<select
value={videoTrimFormat}
disabled={busy}
onChange={(event) =>
setOutputFormat(event.target.value === "mp4" ? "mp4" : "webm")
}
>
<option value="webm">WebM</option>
<option value="mp4">MP4</option>
</select>
</label>
)}
{mode === "frame" ? (
<>
<ControlSlider
Expand Down
18 changes: 16 additions & 2 deletions src/canvas/VideoActionEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,14 @@ function VideoActionSession({
if (active.current && !operation.signal.aborted)
setCurrentPosition(seconds);
},
tool === "video-crop" ? cropRef.current! : undefined,
{
crop: tool === "video-crop" ? cropRef.current! : undefined,
mp4Source:
tool === "video-trim" &&
frozenTask.parameters.outputFormat === "mp4"
? node.data.src
: undefined,
},
);
exported.current = { key: outputKey, output };
if (
Expand Down Expand Up @@ -745,6 +752,7 @@ function VideoActionSession({
<select
aria-label={label}
value={String(parameters[field] ?? "")}
disabled={busy}
onChange={(event) => {
const selected = values.find(
([value]) => String(value) === event.target.value,
Expand Down Expand Up @@ -1304,7 +1312,13 @@ function VideoActionSession({
{tool === "extract-audio" && (
<p className="cw-va-hint">{t("tools.videoEditor.extract.hint")}</p>
)}
{(tool === "video-trim" || tool === "video-crop") && (
{tool === "video-trim" &&
choices(t("tools.videoEditor.outputFormat"), "outputFormat", [
["webm", "WebM"],
["mp4", "MP4"],
])}
{(tool === "video-crop" ||
(tool === "video-trim" && parameters.outputFormat !== "mp4")) && (
<p className="cw-va-hint">{t("tools.videoEditor.local.hint")}</p>
)}
{probing && (
Expand Down
93 changes: 84 additions & 9 deletions src/canvas/videoActionRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,82 @@ import { withMediaDuration } from "./editorMedia.ts";
import { tNow } from "../i18n/messages.ts";
import type { VideoCrop } from "./videoCrop.ts";
import { fetchMediaSource } from "../backend/creationClient.ts";
import { prepareSoftwareAac } from "./softwareAac.ts";

export interface VideoTimeRange {
start: number;
end: number;
}

export type VideoTrimFormat = "webm" | "mp4";

export async function renderTrimmedMp4(
src: string,
range: VideoTimeRange,
signal: AbortSignal,
onPosition: (seconds: number) => void,
): Promise<Blob> {
const {
ALL_FORMATS,
BlobSource,
BufferTarget,
Conversion,
Input,
Mp4OutputFormat,
Output,
} = await import("mediabunny");
signal.throwIfAborted();
const response = await fetchMediaSource(src, { signal });
if (!response.ok) throw new Error(tNow("errors.videoAction.mp4TrimFailed"));
const source = await response.blob();
signal.throwIfAborted();
const input = new Input({ source: new BlobSource(source), formats: ALL_FORMATS });
try {
const audio = await input.getPrimaryAudioTrack();
if (audio) await prepareSoftwareAac();
signal.throwIfAborted();
const target = new BufferTarget();
const conversion = await Conversion.init({
input,
output: new Output({
format: new Mp4OutputFormat({ fastStart: "in-memory" }),
target,
}),
tracks: "primary",
trim: range,
video: { codec: "avc" },
audio: { codec: "aac" },
showWarnings: false,
});
signal.throwIfAborted();
if (
!conversion.isValid ||
!conversion.utilizedTracks.some((track) => track.isVideoTrack()) ||
(audio && !conversion.utilizedTracks.includes(audio))
)
throw new Error(tNow("errors.videoAction.mp4TrimFailed"));
conversion.onProgress = (fraction) => {
onPosition(range.start + fraction * (range.end - range.start));
};
const cancel = () => void conversion.cancel().catch(() => {});
signal.addEventListener("abort", cancel, { once: true });
try {
await conversion.execute();
signal.throwIfAborted();
} finally {
signal.removeEventListener("abort", cancel);
}
if (!target.buffer?.byteLength)
throw new Error(tNow("errors.videoAction.mp4TrimFailed"));
return new Blob([target.buffer], { type: "video/mp4" });
} catch {
signal.throwIfAborted();
throw new Error(tNow("errors.videoAction.mp4TrimFailed"));
} finally {
input.dispose();
}
}

export function fitVideoTimeRange(
range: VideoTimeRange,
duration: number,
Expand All @@ -36,6 +106,8 @@ export function initialVideoActionParameters(
tool: CanvasToolId,
): ToolParameters {
switch (tool) {
case "video-trim":
return { outputFormat: "webm" };
case "video-upscale":
return { resolution: "4K" };
case "video-depth-capture":
Expand Down Expand Up @@ -277,16 +349,19 @@ export async function exportVideoRange(
range: VideoTimeRange,
signal: AbortSignal,
onPosition: (seconds: number) => void,
crop?: VideoCrop,
options: { crop?: VideoCrop; mp4Source?: string } = {},
): Promise<LinkedMediaResult> {
const blob = await recordLocalVideoRange(
video,
range.start,
range.end,
signal,
onPosition,
{ crop },
);
const { crop, mp4Source } = options;
const blob = mp4Source
? await renderTrimmedMp4(mp4Source, range, signal, onPosition)
: await recordLocalVideoRange(
video,
range.start,
range.end,
signal,
onPosition,
{ crop },
);
const mimeType = blob.type;
const src = await mediaBlobDataUrl(blob, signal);
const measured = await withMediaDuration(
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/messages/en-US/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,8 @@ export const errors = {
"errors.videoAction.audioTrack": "audio track",
"errors.videoAction.cropTitle": "Frame crop",
"errors.videoAction.trimTitle": "Duration trim",
"errors.videoAction.mp4TrimFailed":
"Could not encode the selected clip as MP4. Check the source video or choose WebM.",
"errors.text.noAgent":
"Configure and select an Agent model in Settings first.",
"errors.text.promptRequired": "Enter a generation request.",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/messages/en-US/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ export const tools = {
"Extract the original audio track from the selected range and save it as WAV.",
"tools.videoEditor.local.hint":
"Processed locally into WebM. Processing plays back the selected clip.",
"tools.videoEditor.outputFormat": "Output format",
"tools.videoEditor.probing": "Locating the end of the media to read its real duration…",
"tools.videoEditor.unavailableFallback":
"No AI service is connected for this action yet.",
Expand Down Expand Up @@ -394,6 +395,7 @@ export const tools = {
"Decode the local audio track and export WAV for the sampled range.",
"tools.localMedia.subtitle.video":
"Re-encodes to WebM in the browser at normal speed; range precision depends on browser frame scheduling.",
"tools.localMedia.subtitle.mp4": "Save the selected clip as MP4 in the browser.",
"tools.localMedia.apply.busy": "Processing…",
"tools.localMedia.apply.frame": "Add current frame to canvas",
"tools.localMedia.apply.default": "Process and add to canvas",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/messages/zh-CN/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ export const errors = {
"errors.videoAction.audioTrack": "音轨",
"errors.videoAction.cropTitle": "画面裁剪",
"errors.videoAction.trimTitle": "时长修剪",
"errors.videoAction.mp4TrimFailed": "无法将所选片段编码为 MP4。请检查源视频,或选择 WebM。",
"errors.text.noAgent": "请先在设置中配置并选择 Agent 模型",
"errors.text.promptRequired": "请输入生成要求",
"errors.text.maxTokens": "最大输出长度应为 1–32768",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/messages/zh-CN/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ export const tools = {
"tools.videoEditor.separation.description": "按描述",
"tools.videoEditor.extract.hint": "提取所选范围的原音轨,保存为 WAV。",
"tools.videoEditor.local.hint": "本地处理后生成 WebM。处理需要播放所选片段。",
"tools.videoEditor.outputFormat": "保存格式",
"tools.videoEditor.probing": "正在读取实际视频时长…",
"tools.videoEditor.unavailableFallback": "当前未连接此操作的 AI 服务。",
"tools.videoEditor.unavailableHint": "可保存设置或导入处理结果。",
Expand Down Expand Up @@ -364,6 +365,7 @@ export const tools = {
"tools.localMedia.subtitle.audio": "解码本地音轨并按采样范围导出 WAV。",
"tools.localMedia.subtitle.video":
"以正常速度在浏览器内重编码为 WebM;范围精度受浏览器帧调度影响。",
"tools.localMedia.subtitle.mp4": "在浏览器内将所选片段保存为 MP4。",
"tools.localMedia.apply.busy": "处理中…",
"tools.localMedia.apply.frame": "把当前帧加入画布",
"tools.localMedia.apply.default": "处理并加入画布",
Expand Down
Loading