File size: 8,795 Bytes
689359a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | import { downloadBlob } from "@/lib/clip-actions";
import {
clamp,
editDuration,
footageKey,
footageUrl,
mappedBroll,
outputSize,
renderSegments,
type EditDocument,
type EditorState,
} from "./document";
import { drawEditorFrame, loadEditorFont, type BRollLayer } from "./render";
export async function exportDraft(
url: string,
doc: EditDocument,
asset: EditorState,
preset: string,
signal: AbortSignal,
progress: (value: number) => void,
) {
// Preserve a continuous dissolve (and frame timestamps) through UI splits.
doc = { ...doc, segments: renderSegments(doc.segments) };
const m = await import("mediabunny");
const size = outputSize(doc, asset.width, asset.height);
const bitrate = preset === "reels" ? 12_000_000 : 10_000_000;
const audioCodec = (await m.canEncodeAudio("aac"))
? "aac"
: (await m.canEncodeAudio("opus"))
? "opus"
: null;
if (
!(await m.canEncodeVideo("avc", { ...size, bitrate })) ||
(asset.hasAudio && !audioCodec)
)
throw new Error(
"This browser cannot encode this video. Choose background export to render it on the server.",
);
await loadEditorFont(doc.captions.font);
const mediaUrl = asset.hasLayout && doc.framing.fit === "auto" && doc.framing.aspect === "vertical" ? url.replace(/clean\.mp4$/, "layout.mp4") : url;
const response = await fetch(mediaUrl, { signal });
if (!response.ok) throw new Error("Could not load the source video.");
const input = new m.Input({
source: new m.BlobSource(await response.blob()),
formats: m.ALL_FORMATS,
});
const output = new m.Output({
format: new m.Mp4OutputFormat(),
target: new m.BufferTarget(),
});
const canvas = document.createElement("canvas");
canvas.width = size.width;
canvas.height = size.height;
const ctx = canvas.getContext("2d");
if (!ctx) {
input.dispose();
throw new Error("Canvas is unavailable. Use background export.");
}
let finalized = false;
// Stock footage is decoded alongside the clip and drawn under the captions.
const pieces = mappedBroll(doc);
const footage = new Map<string, { input: InstanceType<typeof m.Input>; sink: InstanceType<typeof m.VideoSampleSink> }>();
const endpoint = url.replace(/\/media\/clean\.mp4$/, "");
try {
for (const piece of pieces) {
const key = footageKey(piece.clip.footage);
if (footage.has(key)) continue;
const response = await fetch(footageUrl(endpoint, piece.clip.footage), { signal });
if (!response.ok) throw new Error("Could not load B-roll footage. Use background export.");
const footageInput = new m.Input({
source: new m.BlobSource(await response.blob()),
formats: m.ALL_FORMATS,
});
const track = await footageInput.getPrimaryVideoTrack();
if (!track || !(await track.canDecode())) {
footageInput.dispose();
throw new Error("This browser cannot decode the B-roll. Use background export.");
}
footage.set(key, { input: footageInput, sink: new m.VideoSampleSink(track) });
}
const video = await input.getPrimaryVideoTrack(),
audio = await input.getPrimaryAudioTrack();
if (
!video ||
!(await video.canDecode()) ||
(audio && !(await audio.canDecode()))
)
throw new Error(
"This browser cannot decode the source. Use background export.",
);
const videoSource = new m.CanvasSource(canvas, { codec: "avc", bitrate });
output.addVideoTrack(videoSource);
if (audio && !audioCodec)
throw new Error("Audio encoding is unavailable. Use background export.");
const audioSource =
audio && audioCodec
? new m.AudioSampleSource({ codec: audioCodec, bitrate: 192_000 })
: null;
if (audioSource) output.addAudioTrack(audioSource);
await output.start();
const duration = editDuration(doc);
const renderVideo = async () => {
let cursor = 0;
for (const segment of doc.segments) {
const sink = new m.VideoSampleSink(video);
for await (const sample of sink.samples(segment.start, segment.end)) {
try {
signal.throwIfAborted();
const start = Math.max(segment.start, sample.timestamp),
end = Math.min(segment.end, sample.timestamp + sample.duration);
if (end <= start) continue;
const at = cursor + start - segment.start;
const piece = pieces.find((p) => at >= p.start && at < p.end);
const brollSample = piece
? await footage
.get(footageKey(piece.clip.footage))
?.sink.getSample(piece.offset + at - piece.start)
: null;
let layer: BRollLayer | null = null;
if (piece && brollSample) {
const fade = piece.fadeDuration;
const alpha = clamp(
Math.min(
piece.fadeIn && fade > 0 ? (at - piece.start) / fade : 1,
piece.fadeOut && fade > 0 ? (piece.end - at) / fade : 1,
),
0,
1,
);
layer = {
width: brollSample.displayWidth,
height: brollSample.displayHeight,
alpha,
draw: (x, y, w, h) => brollSample.draw(ctx, x, y, w, h),
};
}
try {
drawEditorFrame(
ctx,
doc,
sample.displayWidth,
sample.displayHeight,
at,
(rect) =>
sample.draw(ctx, rect.x, rect.y, rect.width, rect.height),
asset.captionLooks,
layer,
);
} finally {
brollSample?.close();
}
await videoSource.add(at, end - start);
progress(
Math.min(99, Math.round(((at + end - start) / duration) * 100)),
);
} finally {
sample.close();
}
}
cursor += segment.end - segment.start;
}
videoSource.close();
};
const renderAudio = async () => {
if (!audio || !audioSource) return;
let cursor = 0;
for (const segment of doc.segments) {
const sink = new m.AudioSampleSink(audio);
for await (const sample of sink.samples(segment.start, segment.end)) {
try {
signal.throwIfAborted();
const startFrame = Math.max(
0,
Math.ceil((segment.start - sample.timestamp) * sample.sampleRate),
);
const endFrame = Math.min(
sample.numberOfFrames,
Math.floor((segment.end - sample.timestamp) * sample.sampleRate),
);
if (endFrame <= startFrame) continue;
const full = new Float32Array(
sample.allocationSize({ planeIndex: 0, format: "f32" }) / 4,
);
sample.copyTo(full, { planeIndex: 0, format: "f32" });
const data = full.slice(
startFrame * sample.numberOfChannels,
endFrame * sample.numberOfChannels,
);
const gain = doc.muted ? 0 : doc.volume;
for (let i = 0; i < data.length; i++) data[i] *= gain;
const next = new m.AudioSample({
data,
format: "f32",
numberOfChannels: sample.numberOfChannels,
sampleRate: sample.sampleRate,
timestamp:
cursor +
sample.timestamp +
startFrame / sample.sampleRate -
segment.start,
});
try {
await audioSource.add(next);
} finally {
next.close();
}
} finally {
sample.close();
}
}
cursor += segment.end - segment.start;
}
audioSource.close();
};
// Await both producers before releasing input/output, including on failure.
const outcomes = await Promise.allSettled([renderVideo(), renderAudio()]);
const failed = outcomes.find(
(r): r is PromiseRejectedResult => r.status === "rejected",
);
if (failed) throw failed.reason;
signal.throwIfAborted();
await output.finalize();
finalized = true;
if (!output.target.buffer) throw new Error("Export produced no video.");
signal.throwIfAborted();
downloadBlob(
new Blob([output.target.buffer], { type: "video/mp4" }),
`supoclip-${preset}.mp4`,
);
progress(100);
} finally {
if (!finalized) await output.cancel().catch(() => {});
input.dispose();
for (const { input: footageInput } of footage.values()) footageInput.dispose();
}
}
|