Video Stitching

Concatenate multiple video clips into a single video using the useVideoStitch hook.

Important: Like all React hooks, useVideoStitch must only be called at the top level of React function components — not inside loops, conditions, or nested functions.

Import

import { useVideoStitch } from "@/hooks/use-video-stitch";

When to Use

Use useVideoStitch for:

  • Joining two or more AI-generated video clips into one continuous video
  • Combining shots from a multi-step generation workflow into a final cut
  • Assembling a sequence of clips so the user can download a single file

Supported Video Sources

The hook accepts these video source types for each clip:

  • string — A video URL
  • Blob — Raw video data
  • File — A local video file
  • { url: string } — URL object shape for consistency with other platform APIs

All URL-based sources must be same-origin or CORS-enabled. Videos stored on the platform (from useVideoJobStatus or useFileUpload) work automatically.

API Reference

Returns

  • stitch ((params) => Promise<File | undefined>): Concatenate video sources into a single video file
  • isProcessing (boolean): true while a stitch operation is running
  • progress (number): Progress from 0 to 1 for the current operation
  • error (Error | null): Error state if stitching fails
  • cancel (() => void): Cancel a running stitch operation
  • clearError (() => void): Clear any existing error

stitch Input

  • sources (Array<string | Blob | File | { url: string }>, required): Two or more video sources to concatenate in order
  • width (number): Output width in pixels; defaults to the first video's native width
  • height (number): Output height in pixels; defaults to the first video's native height
  • muted (boolean, default: false): Whether to discard all source audio

When clips must be re-encoded (incompatible codecs or dimensions), the stitcher uses each clip's probed source bitrate when available, otherwise a fixed quality preset (CRF).

stitch Return Value

The returned File contains an MP4 video. Its name property already includes the .mp4 extension, so you can pass it directly to useDownload without specifying a filename. It also works with useFileUpload or any API that accepts File or Blob.

Example: Stitch Completed Videos

import { useVideoStitch } from "@/hooks/use-video-stitch";
import { useDownload } from "@/hooks/use-download";

export function StitchedVideoDownload({ clipUrls }: { clipUrls: string[] }) {
  const { stitch, isProcessing, progress } = useVideoStitch();
  const { download } = useDownload();

  const handleStitch = async () => {
    const result = await stitch({
      sources: clipUrls.map((url) => ({ url })),
    });

    if (result) {
      download(result);
    }
  };

  return (
    <div>
      <button
        onClick={handleStitch}
        disabled={isProcessing || clipUrls.length < 2}
      >
        Stitch and download
      </button>
      {isProcessing ? <progress value={progress * 100} /> : null}
    </div>
  );
}

Example: Stitch Without Audio

const result = await stitch({
  sources: [clip1Url, clip2Url],
  muted: true,
});

For an iterative workflow, use useVideoFrame to extract the last frame, submit the continuation with useSubmitVideoJob, and wait for useVideoJobStatus to complete. Then pass both completed video URLs to StitchedVideoDownload.

Key Behaviors

  1. Client-side processing — Processes media locally in the browser, so no server round-trip is required. The first operation may load browser-side processing assets
  2. Audio preserved by default — Original audio from each clip is included in the output. Pass muted: true to discard audio
  3. Processing time varies — Processing depends on clip length, resolution, codec compatibility, and device performance. Compatible clips may finish quickly; clips that need normalization can take longer
  4. Reusable file output — The returned File can be passed directly to useDownload (filename is optional; the file already has the correct name and extension), useFileUpload, or other platform APIs
  5. Progress tracking — The progress value (0 to 1) updates as each clip is processed
  6. Cancellable — Call cancel() to abort a running stitch operation
  7. Automatic error handling — Errors always toast. stitch resolves to undefined instead of rejecting.
  8. Output format — Produces an MP4 File. The returned File already includes the .mp4 extension in its name, so pass it to download(result) without hardcoding a file extension
  9. Exclusive processing — Only one video stitch or audio overlay operation can run at a time

Best Practices

  1. Generate all clips before calling stitch so the user sees generation progress separately from stitching progress
  2. Use the progress value to show a progress bar during stitching
  3. Use useDownload to let the user save the stitched result
  4. Use useFileUpload if you want to persist the stitched video to the platform
  5. All clips should have the same aspect ratio for best results; mismatched clips will be scaled to fit the output dimensions
  6. Wait for the current video utility operation to finish before starting another stitch or audio overlay

Error Handling

const result = await stitch({
  sources: [videoUrl1, videoUrl2],
});

if (!result) return;

Common errors:

  • "At least two video sources are required." — The sources array must contain 2 or more items
  • "Another video operation is already running." — Wait for the current stitch or audio overlay operation to finish before starting another
  • "Failed to fetch media source (...)." — A media URL could not be fetched (check CORS, URL validity, and network access)
  • "Failed to load video." — The browser could not load video metadata for a source
  • "Output dimensions must be positive numbers." — width and height, when provided, must be positive
  • "Video operation was cancelled." or "Media load was cancelled." — The operation was cancelled via cancel()