Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript
7.9 KB
Raw Blame
import { v4 as uuidv4 } from "uuid";
import type { StoreApi } from "zustand";
import type { ProjectState } from "../project-store";
import { useEngineStore } from "../engine-store";
import { loadEngineModules } from "../../services/lazy-engines";

type Get = StoreApi<ProjectState>["getState"];
type Set = StoreApi<ProjectState>["setState"];

type SubtitleSlice = Pick<
  ProjectState,
  | "addSubtitle"
  | "removeSubtitle"
  | "updateSubtitle"
  | "getSubtitle"
  | "importSRT"
  | "exportSRT"
  | "applySubtitleStylePreset"
  | "getSubtitleStylePresets"
>;

export function createSubtitleSlice(_set: Set, get: Get): SubtitleSlice {
  return {
    addSubtitle: async (subtitle, metadata) => {
      const { project, addTrack, createTextClip } = get();

      let captionsTrack = project.timeline.tracks.find(
        (track) =>
            !track.locked && !track.hidden && (track.role === "captions" || track.name === "Captions"),
      );

      if (!captionsTrack) {
        const existingTrackIds = new Set(
          project.timeline.tracks.map((track) => track.id),
        );
        // Front-most tracks are stored first. Captions must paint after their
        // source video in export, just as they do in the editor preview.
        const result = await addTrack("video", 0, {
          mode: "standard",
          role: "captions",
          name: "Captions",
        });
        if (!result?.success) return;

        const updatedProject = get().project;
        captionsTrack = updatedProject.timeline.tracks.find(
          (track) =>
            track.role === "captions" && !existingTrackIds.has(track.id),
        );
      }

      if (!captionsTrack) return;

      const duration = subtitle.endTime - subtitle.startTime;
      const style = subtitle.style;

      const created = createTextClip(
        captionsTrack.id,
        subtitle.startTime,
        subtitle.text,
        duration,
        {
          ...(style ? {
              fontFamily: style.fontFamily,
              fontSize: style.fontSize,
              color: style.color,
              backgroundColor: style.backgroundColor || undefined,
            } : {}),
          textAlign: "center",
        },
        metadata,
      );
      if (created) {
        get().updateTextTransform(created.id, { position: { x: 0.5, y: style?.position === "top" ? 0.15 : style?.position === "center" ? 0.5 : 0.85 } });
        if (subtitle.animationStyle === "word-by-word") {
          const wordTime = duration / Math.max(1, subtitle.text.trim().split(/\s+/).length);
          get().updateTextAnimation(created.id, {
            preset: "pop",
            unit: "word",
            stagger: wordTime,
            inDuration: duration - wordTime + Math.min(0.12, wordTime),
            outDuration: 0,
            params: { popOvershoot: 1.12 },
          });
        }
      }
      if (typeof metadata?.captionSourceClipId === "string") {
        const sourceTrack = get().project.timeline.tracks.find((track) =>
          track.clips.some((clip) => clip.id === metadata.captionSourceClipId),
        );
        if (created && sourceTrack) get().groupTracks(sourceTrack.id, captionsTrack.id);
      }
      return created ?? undefined;
    },

    removeSubtitle: (subtitleId) => {
      void get().executeAction({
        type: "subtitle/remove",
        id: uuidv4(),
        timestamp: Date.now(),
        params: { subtitleId },
      });
    },

    updateSubtitle: (subtitleId, updates) => {
      const current = get().project.timeline.subtitles.find(
        (s) => s.id === subtitleId,
      );
      if (!current) return;
      void get().executeAction({
        type: "subtitle/replace",
        id: uuidv4(),
        timestamp: Date.now(),
        params: { subtitleId, subtitle: { ...current, ...updates } },
      });
    },

    getSubtitle: (subtitleId) =>
      get().project.timeline.subtitles.find((s) => s.id === subtitleId),

    importSRT: async (
      srtContent: string,
      options?: { sourceClipId?: string; maxWordsPerLine?: number },
    ) => {
      const subtitleEngine = await useEngineStore
        .getState()
        .getSubtitleEngine();
      const { splitCaptionIntoSingleLineCues } = await loadEngineModules();
      const { project, addSubtitle } = get();
      const { result } = subtitleEngine.importSRT(project.timeline, srtContent);
      const errorMessages = result.errors.map(
        (err: { line: number; message: string }) =>
          `Line ${err.line}: ${err.message}`,
      );

      if (result.subtitles.length === 0) {
        return {
          success: false,
          errors:
            errorMessages.length > 0
              ? errorMessages
              : ["No valid subtitles were found in this SRT file."],
        };
      }

      for (const subtitle of result.subtitles) {
        const maxWordsPerLine = options?.maxWordsPerLine;
        const cues = maxWordsPerLine
          ? splitCaptionIntoSingleLineCues(
              subtitle.text,
              subtitle.startTime,
              subtitle.endTime,
              maxWordsPerLine,
            )
          : [subtitle];
        for (const cue of cues) {
          await addSubtitle(
            {
              ...subtitle,
              text: cue.text,
              startTime: cue.startTime,
              endTime: cue.endTime,
            },
            {
              captionSource: normalizedCaptionSource(srtContent),
              captionSourceClipId: options?.sourceClipId,
              captionMaxWordsPerLine: maxWordsPerLine,
            },
          );
        }
      }

      return { success: true, errors: errorMessages };
    },

    exportSRT: async () => {
      const subtitleEngine = await useEngineStore
        .getState()
        .getSubtitleEngine();
      const { project } = get();
      const captionsTrackIds = new Set(
        project.timeline.tracks
          .filter(
            (track) =>
              track.role === "captions" || track.name === "Captions",
          )
          .map((track) => track.id),
      );
      const subtitles = get()
        .getAllTextClips()
        .filter(
          (clip) =>
            captionsTrackIds.has(clip.trackId) ||
            typeof clip.metadata?.captionSource === "string",
        )
        .map((clip) => ({
          id: clip.id,
          text: clip.text,
          startTime: clip.startTime,
          endTime: clip.startTime + clip.duration,
          style: {
            fontFamily: clip.style.fontFamily,
            fontSize: clip.style.fontSize,
            color: clip.style.color,
            backgroundColor: clip.style.backgroundColor ?? "transparent",
            position: "bottom" as const,
          },
        }));
      return subtitleEngine.exportSRT({ ...project.timeline, subtitles });
    },

    applySubtitleStylePreset: async (presetName: string) => {
      const subtitleEngine = await useEngineStore
        .getState()
        .getSubtitleEngine();

      const preset = subtitleEngine.getStylePreset(presetName);
      if (!preset) {
        console.error(`Unknown style preset: ${presetName}`);
        return false;
      }
      const captionsTrackIds = new Set(
        get().project.timeline.tracks
          .filter(
            (track) =>
              track.role === "captions" || track.name === "Captions",
          )
          .map((track) => track.id),
      );
      for (const clip of get().getAllTextClips()) {
        if (!captionsTrackIds.has(clip.trackId)) continue;
        get().updateTextStyle(clip.id, {
          fontFamily: preset.fontFamily,
          fontSize: preset.fontSize,
          color: preset.color,
          backgroundColor: preset.backgroundColor,
        });
      }
      return true;
    },

    getSubtitleStylePresets: async () => {
      const subtitleEngine = await useEngineStore
        .getState()
        .getSubtitleEngine();
      return subtitleEngine.getStylePresets();
    },
  };
}

function normalizedCaptionSource(content: string): "srt" | "vtt" {
  return content.replace(/^\uFEFF/, "").trimStart().startsWith("WEBVTT")
    ? "vtt"
    : "srt";
}