Integração: falantes + dublagem + vídeo final

- editor_api: importa dub e speakers juntos.
- voice_chunks (falantes) vira a migração v15, depois da v14 do vídeo final (antes era criada fora das migrações).
- dub.voice_for: qualquer voz que não é o streamer (other1, other2…) usa a segunda voz da dublagem.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mateuus
2026-11-18 03:59:44 -03:00
co-authored by Claude Opus 5.5
24 changed files with 1671 additions and 129 deletions
+51 -14
View File
@@ -10,7 +10,8 @@ import {
/** `muted` = trecho sem o som da live (a narração e a música continuam). */
export type EditCut = { start: number; end: number; mode: LayoutMode | null; muted?: boolean };
export type EditWord = { s: number; e: number; w: string; emph?: boolean; hidden?: boolean };
/** `sp` = quem fala (doc/clipador/FALANTES.md): ausente/"streamer" = o streamer; "other1", "other2"… = outra pessoa. */
export type EditWord = { s: number; e: number; w: string; emph?: boolean; hidden?: boolean; sp?: string };
export type CaptionPreset = "classic" | "pop" | "karaoke" | "single" | "minimal";
export type TextAnim = HookAnim;
/** Gancho: tempo de SAÍDA (vale a partir do 1º quadro). Texto: tempo da SESSÃO (gruda no conteúdo). */
@@ -278,7 +279,35 @@ export function removeSilences(cuts: EditCut[], words: EditWord[], minGap: numbe
/* ---------- legenda (prévia no navegador) ---------- */
export type OutWord = { start: number; end: number; word: string; emph: boolean };
export type OutWord = { start: number; end: number; word: string; emph: boolean; sp?: string };
/** Fala de outra pessoa (qualquer `sp` que não seja vazio nem "streamer"). */
export function isOther(sp: string | undefined | null): boolean {
return Boolean(sp) && sp !== "streamer";
}
/** Faixa da legenda: a do streamer (posição normal) ou a de outra pessoa (logo abaixo). */
export type CaptionLane = "streamer" | "other";
export function laneOf(sp: string | undefined | null): CaptionLane {
return isOther(sp) ? "other" : "streamer";
}
/** Rótulo de quem fala, para o painel. */
export function speakerLabel(sp: string | undefined | null): string {
if (!isOther(sp)) return "Streamer";
const n = /^other(\d+)$/.exec(sp ?? "");
return n ? `Outra pessoa ${n[1]}` : "Outra pessoa";
}
/** Tamanho da fala de outra pessoa (`caption.otherSize` ou 85 % do tamanho), como `subtitles.other_size`. */
export function otherSize(cap: CutSettings["caption"]): number {
return cap.otherSize ? cap.otherSize : Math.max(30, Math.round(cap.size * 0.85));
}
/** Distância do centro da linha do streamer ao centro da de outra pessoa, como `subtitles.other_offset`. */
export function otherOffset(size: number, osize: number): number {
return Math.round(0.6 * size + 0.6 * osize) + 10;
}
export function outputWords(project: EditProject): OutWord[] {
const ps = pieces(project.cuts);
@@ -291,7 +320,7 @@ export function outputWords(project: EditProject): OutWord[] {
const s = p.out + Math.max(w.s, p.start) - p.start;
const e = p.out + Math.min(w.e, p.end) - p.start;
// Arredondado a 3 casas como `editor.output_words` (o agrupamento compara esses números).
out.push({ start: round3(s), end: round3(Math.max(e, s + 0.05)), word: w.w, emph: Boolean(w.emph) });
out.push({ start: round3(s), end: round3(Math.max(e, s + 0.05)), word: w.w, emph: Boolean(w.emph), sp: w.sp ?? "" });
}
return out;
}
@@ -350,7 +379,8 @@ export function groupWords(words: OutWord[], maxWords: number = CAPTION_TIMING.M
const groups: OutWord[][] = [];
for (const word of cleanWords(words)) {
const cur = groups[groups.length - 1];
if (cur && word.start - cur[cur.length - 1].end <= MAX_GAP_S && word.end - cur[0].start <= MAX_BLOCK_S) {
const same = cur && (cur[cur.length - 1].sp || "streamer") === (word.sp || "streamer"); // bloco nunca mistura falantes
if (cur && same && word.start - cur[cur.length - 1].end <= MAX_GAP_S && word.end - cur[0].start <= MAX_BLOCK_S) {
const fits = [...cur, word].map((w) => w.word).join(" ").length <= maxChars;
// Fala rápida: o bloco cheio passaria voando; uma palavra a mais (se couber) dá tempo de ler.
const room = cur.length < maxWords || (maxWords >= 2 && cur.length === maxWords && word.end - cur[0].start < FAST_BLOCK_S);
@@ -363,22 +393,29 @@ export function groupWords(words: OutWord[], maxWords: number = CAPTION_TIMING.M
export type CaptionBlock = { words: OutWord[]; end: number };
/** Blocos com o fim: nunca passa do início do bloco seguinte (dois eventos ativos o libass empilharia). */
/**
* Blocos com o fim: nunca passa do início do bloco seguinte DA MESMA FAIXA (streamer / outra pessoa), como
* `subtitles.caption_blocks`. Os dois falando juntos = um bloco em cada faixa ao mesmo tempo.
*/
export function captionBlocks(words: OutWord[], maxWords: number = CAPTION_TIMING.MAX_WORDS): CaptionBlock[] {
const groups = groupWords(words, maxWords);
return groups.map((g, k) => {
let end = Math.max(g[g.length - 1].end, g[g.length - 1].start + CAPTION_TIMING.MIN_HOLD_S);
if (k + 1 < groups.length) end = Math.min(end, groups[k + 1][0].start);
return { words: g, end: pyRound3(end) };
});
const out: CaptionBlock[] = [];
for (const lane of ["streamer", "other"] as const) {
const groups = groupWords(words.filter((w) => laneOf(w.sp) === lane), maxWords);
groups.forEach((g, k) => {
let end = Math.max(g[g.length - 1].end, g[g.length - 1].start + CAPTION_TIMING.MIN_HOLD_S);
if (k + 1 < groups.length) end = Math.min(end, groups[k + 1][0].start);
out.push({ words: g, end: pyRound3(end) });
});
}
return out.sort((a, b) => a.words[0].start - b.words[0].start);
}
/**
* Bloco e palavra destacada no instante `t` (saída), como os eventos do ASS: o bloco vale de `[0].start` até `end`;
* a palavra i vale do início dela até o início da seguinte (a última, até o fim do bloco).
* a palavra i vale do início dela até o início da seguinte (a última, até o fim do bloco). `lane` = faixa.
*/
export function captionAt(blocks: CaptionBlock[], t: number): { block: CaptionBlock; active: number } | null {
const block = blocks.find((b) => t >= b.words[0].start && t < b.end);
export function captionAt(blocks: CaptionBlock[], t: number, lane: CaptionLane = "streamer"): { block: CaptionBlock; active: number } | null {
const block = blocks.find((b) => laneOf(b.words[0].sp) === lane && t >= b.words[0].start && t < b.end);
if (!block) return null;
let active = 0;
for (let i = 0; i < block.words.length; i++) if (t >= block.words[i].start) active = i;
+17 -5
View File
@@ -19,7 +19,7 @@ import type { CutSettings, Rect } from "./clipper-client";
import { canvasFont, fontMetrics } from "./clip-editor-fonts";
import {
BANNER_SLIDE_MS, CHAT_HOLD_S, INSET_ANIM_S, INSET_SHADOW_ALPHA, INSET_SLIDE_S, TEXT_SLIDE_MS, bannerLayout, camPanelHeight, captionY,
captionAt, captionBlocks, chatDefault, clamp, cutAt, easeAt, ffmpegCropFill, gameWindowAt, insetAt, insetHeight, outputDuration, outputWords, plainLines, produce, resolvedMode,
captionAt, captionBlocks, chatDefault, clamp, otherOffset, otherSize, type CaptionLane, cutAt, easeAt, ffmpegCropFill, gameWindowAt, insetAt, insetHeight, outputDuration, outputWords, plainLines, produce, resolvedMode,
round3, setInsetPlace, toOutput, zoomAt, type ChatItem, type EditProject, type Frame, type InsetOverlay, type OutWord, type Selection, type TextOverlay,
} from "./clip-editor-model";
import { cx } from "./ui";
@@ -277,8 +277,15 @@ function renderFrame(ctx: CanvasRenderingContext2D, comp: HTMLCanvasElement, vid
if (fontsReady) {
const cap = cfg.caption;
if (cap.enabled && inside) {
const box = drawCaption(ctx, project, cfg, tOut, captionY(cfg, mode, frame) * k, k, cw);
// Fala de outra pessoa (colega no Discord, voz do jogo): logo abaixo, na cor dela (FALANTES.md). Sem espaço
// embaixo, a linha do streamer sobe (como no render: a ordem nunca inverte).
const two = project.captions.words.some((w) => w.sp && w.sp !== "streamer");
const offset = otherOffset(cap.size, otherSize(cap));
const capY = two ? Math.min(captionY(cfg, mode, frame), frame.canvasHeight - 8 - offset - Math.trunc(0.6 * otherSize(cap)))
: captionY(cfg, mode, frame);
const box = drawCaption(ctx, project, cfg, tOut, capY * k, k, cw);
if (box) hits.push({ key: "caption", ...box });
if (two) drawCaption(ctx, project, cfg, tOut, (capY + offset) * k, k, cw, "other");
}
for (const o of project.overlays) {
if (o.kind === "zoom" || o.kind === "inset") continue;
@@ -547,10 +554,15 @@ function drawBanner(ctx: CanvasRenderingContext2D, o: TextOverlay, frame: Frame,
* comportamento de cada preset de `editor_render.build_project_ass`. `y` = centro em px do canvas. Estilo "Caption":
* negrito, contorno e sombra 3 (meio preto).
*/
function drawCaption(ctx: CanvasRenderingContext2D, project: EditProject, cfg: CutSettings, t: number, y: number, k: number, cw: number): Box {
const cap = cfg.caption;
function drawCaption(ctx: CanvasRenderingContext2D, project: EditProject, cfg: CutSettings, t: number, y: number, k: number, cw: number,
lane: CaptionLane = "streamer"): Box {
// A linha de outra pessoa usa a cor e o tamanho dela (`otherColor`/`otherSize`), como o estilo CaptionOther do ASS.
const cap = lane === "other"
? { ...cfg.caption, color: cfg.caption.otherColor ?? "#5CE1FF", size: otherSize(cfg.caption),
outlineWidth: cfg.caption.outlineWidth ? Math.max(2, Math.floor((cfg.caption.outlineWidth * otherSize(cfg.caption)) / cfg.caption.size)) : 0 }
: cfg.caption;
const preset = project.captions.preset;
const now = captionAt(captionBlocks(outputWords(project), cap.maxWords), t);
const now = captionAt(captionBlocks(outputWords(project), cap.maxWords), t, lane);
const group = now?.block.words;
const m = fontMetrics(cap.font);
const size = cap.size * k;
@@ -4,10 +4,13 @@
// Com palavras selecionadas, a barra oferece tirar/manter no corte e ênfase (o resto fica em Propriedades).
// Palavras fora do corte aparecem riscadas. Ferramentas: remover silêncios maiores que X s e re-transcrever um
// trecho com o Whisper do serviço de voz. Chat: as mensagens da janela, com o tempo; clique = ir ao instante.
// Quem fala (doc/clipador/FALANTES.md): cada parágrafo é de um falante só; a fala de outra pessoa (colega no Discord,
// voz do jogo) vem marcada e na cor dela; "Falante" troca as palavras selecionadas entre streamer e outra pessoa.
import { useEffect, useRef, useState } from "react";
import { clipperCall } from "./clipper-client";
import {
cutAt, keepRange, produce, removeRange, removeSilences, sessionClock, type ChatItem, type EditProject, type EditWord, type Selection,
cutAt, isOther, keepRange, produce, removeRange, removeSilences, sessionClock, speakerLabel, type ChatItem, type EditProject, type EditWord,
type Selection,
} from "./clip-editor-model";
import { Btn } from "./clip-editor-ui";
import { MicIcon, ScissorsIcon } from "./icons";
@@ -62,9 +65,10 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
if (!parts.length || parts.join(" ") === sel.map((w) => w.w).join(" ")) return;
const weight = parts.reduce((n, w) => n + w.length + 1, 0);
let cursor = selA;
const sp = sel[0].sp; // o texto novo continua de quem falava
const fresh: EditWord[] = parts.map((w) => {
const dur = Math.max(0.06, ((selB - selA) * (w.length + 1)) / weight);
const item = { s: Math.round(cursor * 1000) / 1000, e: Math.round(Math.min(selB, cursor + dur) * 1000) / 1000, w: w.slice(0, 40) };
const item: EditWord = { s: Math.round(cursor * 1000) / 1000, e: Math.round(Math.min(selB, cursor + dur) * 1000) / 1000, w: w.slice(0, 40), ...(sp ? { sp } : {}) };
cursor += dur;
return item;
}).filter((w) => w.e > w.s);
@@ -92,11 +96,13 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
onNotice(true, `Whisper transcreveu ${sessionClock(a)}–${sessionClock(b)} de novo: ${r.data.words.length} palavras em ${r.data.seconds.toLocaleString("pt-BR")} s.`);
}
// Parágrafos: quebra quando a fala para mais de 1,2 s (fica mais fácil achar onde cortar).
// Parágrafos: quebra quando a fala para mais de 1,2 s (fica mais fácil achar onde cortar) ou quando muda quem fala.
const paragraphs: number[][] = [];
const speakerOf = (w: EditWord) => (isOther(w.sp) ? w.sp : "streamer");
const anyOther = words.some((w) => isOther(w.sp));
words.forEach((w, i) => {
const last = paragraphs[paragraphs.length - 1];
if (!last || w.s - words[i - 1].e > 1.2) paragraphs.push([i]);
if (!last || w.s - words[i - 1].e > 1.2 || speakerOf(w) !== speakerOf(words[i - 1])) paragraphs.push([i]);
else last.push(i);
});
@@ -120,6 +126,11 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
const on = !sel.every((w) => w.emph);
setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, emph: on || undefined } : w)));
}}>Ênfase</Btn>
<Btn variant="ghost" className="px-2" title="Trocar quem fala estas palavras: streamer ↔ outra pessoa (legenda de baixo, outra cor)" onClick={() => {
const toStreamer = sel.every((w) => isOther(w.sp));
setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, sp: toStreamer ? "streamer" : "other1" } : w)));
onNotice(true, toStreamer ? "Palavras marcadas como do streamer." : "Palavras marcadas como de outra pessoa (legenda de baixo).");
}}>{sel.every((w) => isOther(w.sp)) ? "É o streamer" : "Outra pessoa"}</Btn>
</>
) : (
<>
@@ -160,8 +171,15 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
{paragraphs.map((para) => (
<p key={para[0]} className="mb-1.5 grid grid-cols-[52px_minmax(0,1fr)] gap-x-2">
<button type="button" tabIndex={-1} onClick={() => onSeek(words[para[0]].s)}
className="cursor-pointer pt-[3px] text-left font-mono text-[10.5px] text-nle-hot/80 hover:text-nle-hot">{sessionClock(words[para[0]].s)}</button>
<span>
className="grid cursor-pointer content-start pt-[3px] text-left font-mono text-[10.5px] text-nle-hot/80 hover:text-nle-hot">
{sessionClock(words[para[0]].s)}
{anyOther && (
<span className={cx("font-sans text-[10px] leading-tight", isOther(words[para[0]].sp) ? "text-[#5ce1ff]" : "text-nle-dim")}>
{speakerLabel(words[para[0]].sp)}
</span>
)}
</button>
<span className={cx(isOther(words[para[0]].sp) && "text-[#9fe9ff]")}>
{para.map((i) => {
const w = words[i];
const kept = cutAt(project.cuts, (w.s + w.e) / 2) >= 0;
+4 -1
View File
@@ -141,7 +141,8 @@ export type ClipAnalysis = {
/** Fonte em inglês: a fala do corte em frases (tempo da sessão) com a tradução em português. */
export type ClipTranslation = {
language: string; startS: number; endS: number; model?: string;
lines: { s: number; e: number; text: string; pt: string }[];
/** `speaker` = quem fala a frase ("streamer" ou "other1", "other2"…; ausente nas traduções antigas = streamer). */
lines: { s: number; e: number; text: string; pt: string; speaker?: string }[];
};
export type ClipJudge = null
@@ -238,6 +239,8 @@ export type CutSettings = {
caption: {
enabled: boolean; font: string; size: number; color: string; highlight: string; outline: string;
outlineWidth: number; y: number | null; uppercase: boolean; maxWords: number;
/** Fala de outra pessoa (colega no Discord, voz do jogo): cor e tamanho (null = 85 % de `size`). Serviço antigo não manda. */
otherColor?: string; otherSize?: number | null;
/** Legado: virou `dev.translation`. */
translation?: boolean;
};
+12 -2
View File
@@ -8,6 +8,7 @@ import { CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, la
import {
ChatSignals, ClipActions, ClipMedia, ClipVideoState, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip,
} from "./clipper-clip-parts";
import { isOther, speakerLabel } from "./clip-editor-model";
import { Dialog } from "./dialog";
import { ArrowLeftIcon, ArrowRightIcon, CheckIcon, ClockIcon } from "./icons";
import type { PublishJob } from "./publishing-client";
@@ -171,6 +172,8 @@ function Portuguese({ clip, pending, run }: {
const pt = clip.judge && "pt" in clip.judge ? clip.judge.pt : undefined;
const lines = clip.translation?.lines ?? [];
const english = (clip.language ?? "").toLowerCase().startsWith("en");
// Quem fala cada frase (doc/clipador/FALANTES.md): o streamer ou outra pessoa (colega no Discord, voz do jogo).
const others = lines.some((l) => isOther(l.speaker));
if (!english && !pt && !lines.length) return null;
const translate = () => run("translate", () => clipperCall<Clip>(`clips/${clip.id}/translate`, "POST"), "Fala traduzida.");
return (
@@ -183,12 +186,19 @@ function Portuguese({ clip, pending, run }: {
{pt?.caption && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{pt.caption}</p>}
{lines.length > 0 ? (
<details className="text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">O que ele fala ({lines.length} frases)</summary>
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">
{others ? "O que falam" : "O que ele fala"} ({lines.length} frases)
</summary>
<ol className="mt-2 grid gap-2">
{lines.map((line, i) => (
<li key={i} className="grid grid-cols-[3.25rem_minmax(0,1fr)] gap-2">
<span className="pt-px font-mono text-[0.6875rem] text-fg-subtle tabular-nums">{formatClock(line.s - clip.startS)}</span>
<span className="grid gap-0.5">
<span className={cx("grid gap-0.5", isOther(line.speaker) && "border-l-2 border-info/60 pl-2")}>
{others && (
<span className={cx("text-[0.6875rem] font-semibold", isOther(line.speaker) ? "text-info" : "text-fg-muted")}>
{speakerLabel(line.speaker)}
</span>
)}
<span className="text-fg">{line.pt}</span>
<span className="text-xs text-fg-subtle italic">{line.text}</span>
</span>
@@ -506,6 +506,21 @@ function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
</div>
<RangeField label="Espessura do contorno" min={0} max={14} step={1} value={draft.caption.outlineWidth}
onChange={(outlineWidth) => update("caption", { outlineWidth })} format={(v) => `${v} px`} />
<h4 className="pt-2 text-eyebrow font-semibold text-fg-subtle uppercase">Fala de outra pessoa</h4>
<p className="-mt-2 text-xs text-fg-subtle">
Colega no Discord ou outro jogador no chat de voz: a legenda dele sai logo abaixo da do streamer, nesta cor.
</p>
<div className="grid grid-cols-3 gap-2">
<ColorField label="Cor da outra pessoa" value={draft.caption.otherColor ?? "#5CE1FF"}
onChange={(otherColor) => update("caption", { otherColor })} />
</div>
<Switch label="Tamanho automático" checked={!draft.caption.otherSize}
onChange={(auto) => update("caption", { otherSize: auto ? null : Math.round(draft.caption.size * 0.85) })}
hint="85% do tamanho da legenda do streamer." />
{Boolean(draft.caption.otherSize) && (
<RangeField label="Tamanho da outra pessoa" min={30} max={140} step={2} value={draft.caption.otherSize ?? 70}
onChange={(otherSize) => update("caption", { otherSize })} format={(v) => `${v} px`} />
)}
</div>
<div className="grid content-start gap-4">
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Ritmo e posição</h4>
@@ -980,6 +995,11 @@ function CaptionSample({ caption }: { caption: CutSettings["caption"] }) {
}}>
{words.map((w, i) => <span key={w} style={i === 1 ? { color: caption.highlight } : undefined}>{w}{i < words.length - 1 ? " " : ""}</span>)}
</span>
{/* A fala de outra pessoa (colega no Discord), logo abaixo e na cor dela. */}
<span className="text-center text-lg leading-tight" style={{
fontFamily: fontStack(caption.font), fontWeight: 900, color: caption.otherColor ?? "#5CE1FF",
WebkitTextStroke: stroke ? `${stroke}px ${caption.outline}` : undefined, paintOrder: "stroke fill",
}}>{caption.uppercase ? "E O COLEGA" : "e o colega"}</span>
</div>
);
}