Files
CenaForge/panel/src/components/clipper-client.ts
T
MateuusandClaude Opus 5.5 439e111052 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>
2026-11-18 03:59:44 -03:00

643 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Cliente do Clipador no navegador: tipos do contrato de /api/clipper/* (repassado a /v1/* do serviço
// Python em 127.0.0.1:4520), rótulos, formatação e o gancho de ações com retorno. Não importa de
// lib/clipper.ts, que roda só no servidor.
import { useCallback, useState } from "react";
import { apiCall, type ApiResult } from "./api-client";
import type { Tone } from "./ui";
export type ClipperPlatform = "twitch" | "youtube" | "kick";
export type JudgeProvider = "codex" | "claude" | "gemini" | "off";
export type ClipperStatus = {
version: string;
tools: { streamlink: string | null; ffmpeg: string | null };
voice: { configured: boolean; online: boolean };
judge: { provider: JudgeProvider; model: string; available: boolean; path: string | null; minScore: number };
recording: number;
settings: { quality: string; segmentS: number; pollS: number; keepHours: number; language: string };
};
export type JudgeModel = { id: string; label: string; description?: string };
/** `faceTrack` é opcional: o serviço antigo (antes do rastreio de reação) não manda. */
export type JudgeOptions = { scanEnabled: boolean; scanIntervalS: number; vision: boolean; camDetect: boolean; faceTrack?: boolean };
export type JudgeConfig = {
provider: JudgeProvider;
/** Modelo do EDITOR (2º juiz). null com o juiz desligado. */
model: string | null;
/** Modelo do ANALISTA (1º juiz, vê os frames); vem resolvido (igual ao editor quando não há um próprio). */
analystModel?: string | null;
available: boolean | null;
path: string | null;
minScore: number;
options?: JudgeOptions;
lastScanError?: string | null;
/** `gemini` é opcional: o serviço antigo (antes do Gemini) não manda. */
models: { codex: JudgeModel[]; claude: JudgeModel[]; gemini?: JudgeModel[]; defaults: { codex: string; claude: string; gemini?: string } };
/** Por que a IA escolhida não roda (desligada em Configurações → IA, sem CLI, sem chave); null = pronta. */
unavailableReason?: string | null;
/** Modo de login da IA escolhida (Configurações → IA). */
authMode?: "oauth" | "apiKey" | null;
/** IA reserva: ordem efetiva em que o juiz tenta (a escolhida primeiro). Serviço antigo não manda. */
fallback?: { enabled: boolean; cooldownMin: number; chain: Exclude<JudgeProvider, "off">[] };
/** IAs em pausa depois de falha de indisponibilidade (`until` em ISO, UTC). */
pauses?: JudgePause[];
};
export type JudgePause = { provider: Exclude<JudgeProvider, "off">; until: string; reason: string };
export type ClipperChannel = {
id: string;
platform: ClipperPlatform;
channel: string;
url: string;
displayName: string;
monitor: boolean;
authorized: boolean;
lastCheckAt: string | null;
lastStatus: "ao vivo" | "offline" | "";
createdAt: string;
/** Idioma falado na live (transcrição e textos da IA). Opcional: o serviço antigo não manda (= padrão do serviço). */
language?: string;
/** Monitor pausado por você ter parado uma sessão à mão: não grava de novo até religar. Opcional (serviço antigo). */
monitorPausedAt?: string | null;
/** Sessão que você parou e motivou a pausa. */
monitorPausedBySession?: number | null;
};
export type SessionStatus = "starting" | "recording" | "processing" | "done" | "stopped" | "error" | "interrupted";
export type ClipStatus = "candidate" | "pending" | "rendering" | "ready" | "approved" | "rejected" | "discarded" | "published" | "error";
export type ClipperSession = {
id: number;
channelId: string | null;
platform: ClipperPlatform;
kind: "live" | "vod";
url: string;
title: string;
status: SessionStatus;
/** "connected" | "connecting" | "unsupported" | "off" | "error: …" */
chatStatus: string;
chatMessages: number;
durationS: number;
startedAt: string;
endedAt: string | null;
error: string | null;
segments: { total: number; analyzed: number; transcriptErrors: number };
clips: Partial<Record<ClipStatus, number>>;
// Fase 2 (opcionais: o serviço antigo não manda).
game?: string;
gameSource?: GameSource;
/** O que a IA viu na tela; pode divergir da categoria da plataforma. */
screenGame?: string;
gameHistory?: { game: string; source: GameSource; atS: number; at: string }[];
gameProfileReady?: boolean;
/** Até onde (s) a varredura da IA já assistiu. */
scannedUntilS?: number;
memory?: MemoryEntry[];
camDetect?: CamDetect | null;
roomId?: string | null;
hasOwnSettings?: boolean;
/** O que a captura gravou de fato (1º bloco de cada execução). null = sessão antiga ou ainda sem bloco; ausente = serviço antigo. */
capture?: CaptureInfo | null;
/** Idioma falado na live (copiado da fonte ao criar a sessão). Opcional: o serviço antigo não manda. */
language?: string;
};
export type GameSource = "platform" | "screen" | "user" | "";
/** `summaryPt`: fonte em inglês — o resumo em português para o painel (`summary` é o inglês que vai à IA). */
export type MemoryEntry = { fromS: number; toS: number; summary: string; summaryPt?: string };
export type CamDetect = {
hasWebcam: boolean; cam: Rect | null; gameOnScreen?: boolean; frame?: string; at?: string;
/** Quem achou: yunet = local (rosto no quadro, sem IA) · ai = IA olhando quadros · manual = você marcou. */
source?: "yunet" | "ai" | "manual";
confidence?: number; fullFrame?: boolean;
};
/** Reação no rosto do streamer (rastreio local, reaction.py): pico, início e intensidade (z relativo ao normal dele). */
export type FaceReaction = {
peakS: number; onsetS: number; endS: number; intensity: number; strong: boolean;
label: "risada" | "grito" | "susto" | "choque" | "confuso" | "raiva" | "neutro";
};
export type Situation = "lag_ou_bug" | "jogada" | "falha_engracada" | "morte" | "susto" | "treta" | "conversa_engracada"
| "historia" | "informacao_do_jogo" | "reacao" | "outro";
/** O que o ANALISTA (1º juiz) viu: tela + fala + chat. */
export type ClipAnalysis = {
situation: string;
what_happened: string;
screen: string;
speech: string;
chat_meaning: string;
/** 0–1 */
confidence: number;
action_start_s: number;
reaction_end_s: number;
hook: string;
/** Fonte em inglês: os textos traduzidos para o painel (o vídeo usa os originais, em inglês). */
pt?: { what_happened: string; screen: string; speech: string; chat_meaning: string; hook: string };
};
/** 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;
/** `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
| {
model: string; keep: boolean; score: number; reason: string; analysis?: ClipAnalysis | null; analystModel?: string;
/** Fonte em inglês: título, legenda e motivo em português (só para ler; o post sai em inglês). */
pt?: { title?: string; caption?: string; reason?: string };
}
| { error: string };
export type ClipTags = { risada?: number; susto?: number; hype?: number; clip?: number };
export type Clip = {
id: number;
sessionId: number;
peakS: number;
startS: number;
endS: number;
durationS: number;
score: number;
source: "chat" | "audio" | "manual" | "ai" | "face";
reasons: {
peakRatio?: number; messages?: number; tags?: ClipTags; topMessages?: string[];
/** Emotes do chat no pico: nome → quantidade. */
emotes?: Record<string, number>;
// Cortes da varredura da IA (source "ai").
proposalTitle?: string; proposalScore?: number; proposalReason?: string; scanFromS?: number; scanToS?: number;
/** Fonte em inglês: a proposta da varredura em português. */
proposalTitlePt?: string; proposalReasonPt?: string;
/** Reação no rosto do streamer dentro do trecho (opcional: só com câmera e rastreio ligado). */
face?: FaceReaction;
/** Corte de fonte "face": o apoio do áudio (sinal suavizado) e do chat (mensagens de reação) que deixou o rosto virar corte. */
support?: { audioZ: number; chatReactions: number };
};
judge: ClipJudge;
title: string;
caption: string;
transcript: string;
/** Fonte em inglês: fala traduzida por frase; null = sessão em português ou ainda não traduzida. */
translation?: ClipTranslation | null;
status: ClipStatus;
file: string | null;
thumb: string | null;
error: string | null;
createdAt: string;
updatedAt: string;
channelId: string | null;
platform: ClipperPlatform;
sessionUrl: string;
/** Editor de cortes: há projeto de edição (o render usa ele); capa gerada no export. Opcional: serviço antigo não manda. */
edit?: { updatedAt: string; exportedAt: string | null; cover: string | null; origin?: "ai" | "user" | null } | null;
/** Formato do vídeo renderizado. Opcional: o serviço antigo não manda (ausente = vertical). */
aspect?: Aspect;
/** Idioma da sessão de origem (resolvido pelo serviço). Opcional: o serviço antigo não manda (= padrão, pt-BR). */
language?: string;
/** Vídeo de revisão (`file`): camadas de teste que entraram nele ([] = nenhuma; null = não se sabe). doc/clipador/REVISAO.md */
review?: { devLayers: string[] | null };
/** Vídeo final, gerado ao aprovar (sem as camadas de teste); null = ainda não aprovado. */
final?: ClipFinal | null;
/** O único arquivo que vai para as redes: o final pronto. null = ainda não (a publicação espera). */
publishFile?: string | null;
};
export type ClipFinal = {
status: "pending" | "rendering" | "ready" | "error";
file: string | null;
thumb: string | null;
cover: string | null;
error: string | null;
at: string | null;
/** O vídeo de revisão não tinha camada de teste: ele mesmo virou o final (sem render novo). */
reused: boolean;
};
/** Nome das camadas de teste do vídeo de revisão (grupo `dev` da configuração do corte). */
export const DEV_LAYER_LABEL: Record<string, string> = { translation: "tradução em português", dub: "dublagem em português" };
/** O vídeo de revisão (o da fila) tem camadas de teste? null = não se sabe (corte antigo). */
export function reviewHasDevLayers(clip: Pick<Clip, "review">): boolean | null {
const layers = clip.review?.devLayers;
return layers == null ? null : layers.length > 0;
}
/* ---------- Configuração do corte ---------- */
/** Retângulo normalizado (0–1) sobre o quadro original 16:9; x, y = canto superior esquerdo. */
export type Rect = { x: number; y: number; w: number; h: number };
export type LayoutMode = "auto" | "blur" | "cam_top" | "game_only" | "cam_only";
/** Formato do corte: vertical = 1080×1920 (Shorts/Reels/TikTok); horizontal = 1920×1080 (YouTube, jogo em tela cheia). */
export type Aspect = "vertical" | "horizontal";
export type CutSettings = {
layout: { mode: LayoutMode; cam: Rect | null; game: Rect | null; camHeight: number };
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;
};
/** Camadas só de desenvolvimento (vídeo de revisão); o vídeo final, depois de aprovar, sai sem elas. */
dev?: {
translation: boolean; dub: boolean;
/** Dublagem (doc/clipador/DUBLAGEM.md): voz TTS pronta do serviço de voz — nunca clone do streamer. */
dubVoice?: string;
/** Voz das falas marcadas como de outra pessoa (`speaker: "other"`). */
dubVoiceOther?: string;
/** Volume do áudio original enquanto a dublagem toca (0–1). */
dubDuck?: number;
};
credit: { enabled: boolean; position: "top" | "bottom"; size: number };
duration: { minS: number; maxS: number; backtrackS: number };
/** O serviço antigo não manda este grupo: use `withFormat` para preencher com vertical. */
format: { aspect: Aspect };
/** Estilo do gancho que o projeto da IA põe no começo. Opcional: o serviço antigo não manda (use `hookOf`). */
hook?: HookSettings;
/** Qualidade de gravação da live (vale na próxima gravação ou retomada). Opcional: o serviço antigo não manda. */
capture?: { quality: CaptureQuality };
};
/** Camada parcial (canal ou sessão): só o que ela fixa. */
export type CutLayer = { [G in keyof CutSettings]?: Partial<CutSettings[G]> };
export type SettingsPayload = {
own: CutLayer;
effective: CutSettings;
defaults: CutSettings;
modes: LayoutMode[];
fonts: string[];
/** Só nas configurações da sessão: a camada do canal (null se a sessão não tem canal). */
channel?: CutLayer | null;
// Opcionais (o serviço antigo não manda): formatos, fontes empacotadas e opções do gancho.
aspects?: Aspect[];
/** {família: "assets/fonts/….ttf"} das fontes empacotadas, relativo à raiz do repositório. */
fontFiles?: Record<string, string>;
hookStyles?: HookStyle[];
hookAnims?: HookAnim[];
/** Tamanho do vídeo e quadro lógico dos textos (ASS) de cada formato. */
frames?: Record<Aspect, FrameSize>;
/** Opções de qualidade de gravação, com o disco por hora medido (serviço antigo não manda). */
captureQualities?: CaptureOption[];
};
export type FrameResult = { t: number; file: string; version: string };
export type PreviewResult = { t: number; file: string; mode: LayoutMode; version: string; aspect?: Aspect };
/** Formato de um corte ou configuração; ausente (serviço antigo) = vertical. */
export function aspectOf(value: { aspect?: Aspect | null } | null | undefined): Aspect {
return value?.aspect === "horizontal" ? "horizontal" : "vertical";
}
/** Completa uma configuração vinda do serviço antigo (sem o grupo `format`) com o formato vertical. */
export function withFormat(settings: CutSettings): CutSettings {
return { ...settings, format: { aspect: aspectOf(settings.format) } };
}
/** Mescla campo a campo: base ← camadas (igual ao serviço). */
export function mergeSettings(base: CutSettings, ...layers: (CutLayer | null | undefined)[]): CutSettings {
const out = structuredClone(base);
for (const layer of layers) {
if (!layer) continue;
for (const group of new Set([...Object.keys(out), "format"]) as Set<keyof CutSettings>) {
const values = layer[group];
// Grupo que a base não tem (ex.: `format` com o serviço antigo): cria em vez de quebrar.
if (values) (out as Record<string, unknown>)[group] = { ...(out[group] ?? {}), ...values };
}
}
return out;
}
/**
* Camada mínima para salvar: campos que diferem da base de baixo, mais os que a camada já fixava
* (para não "soltar" um valor que o usuário fixou de propósito, mesmo igual ao herdado).
*/
export function layerFrom(draft: CutSettings, base: CutSettings, own: CutLayer | null | undefined): CutLayer {
const out: Record<string, Record<string, unknown>> = {};
for (const group of Object.keys(draft) as (keyof CutSettings)[]) {
const values = (draft[group] ?? {}) as Record<string, unknown>;
const under = (base[group] ?? {}) as Record<string, unknown>;
const pinned = (own?.[group] ?? {}) as Record<string, unknown>;
for (const key of Object.keys(values)) {
if (key in pinned || JSON.stringify(values[key]) !== JSON.stringify(under[key])) (out[group] ??= {})[key] = values[key];
}
}
return out as CutLayer;
}
/* ---------- Jogos e emotes ---------- */
/** Missão do jogo (só quando a lista já é pública): nome oficial, capítulo/ato, resumo e o que marca o fim dela. */
export type GameMission = { name: string; chapter: string; summary: string; completion_triggers: string[] };
export type GameProfile = {
name: string; summary: string; genre: string;
mechanics: string[]; clip_worthy: string[]; avoid: string[]; jargon: string[]; news: string[]; sources: string[];
/** Hashtags do jogo (a 1ª é a principal): entram em toda legenda de corte deste jogo, depois da do canal. */
hashtags?: string[];
// Opcionais: perfis antigos e o serviço antigo não mandam.
/** Outros nomes do jogo ("GTA 6", "GTA VI"): categoria e tela caem no mesmo perfil. */
aliases?: string[];
/** [] = a lista de missões ainda não é pública. */
missions?: GameMission[];
/** Sinais gerais de fim de missão/objetivo (banner, tela de resultado, fala): a IA termina o corte logo depois. */
end_triggers?: string[];
};
export type Game = {
id: string; name: string; status: "pending" | "ready" | "error"; error: string | null;
model: string | null; researchedAt: string | null;
/** Perfil em português: o que o painel mostra. */
profile: GameProfile | null;
/** Perfil em inglês: o que vai para a IA. null/ausente = ainda não traduzido (a IA usa o `profile`). */
profileAi?: GameProfile | null;
/** Idioma do `profileAi` ("en-US"). */
aiLanguage?: string;
/** Quando uma versão foi gerada a partir da outra. */
translatedAt?: string | null;
/** União dos aliases das duas versões. */
aliases?: string[];
/** Última edição à mão ou por pedido seu à IA (serviço antigo não manda). */
editedAt?: string | null;
/** Pedidos que você fez à IA; voltam em toda pesquisa nova. */
notes?: { text: string; at: string; section?: string }[];
};
export type Emote = { name: string; source: string; uses: number; weight: number; lastSeen: string | null };
/** Id do jogo no serviço (mesma regra de intel.game_id). */
export function gameIdOf(name: string): string {
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "desconhecido";
}
/** Chave do canal para os emotes: "<plataforma>-<login>" (ex.: twitch-skipnho). */
export function channelKeyOf(session: Pick<ClipperSession, "channelId" | "platform" | "url">): string {
if (session.channelId) return session.channelId;
const login = channelFromUrl(session.url).replace(/^@/, "").toLowerCase();
return login ? `${session.platform}-${login}` : "";
}
export type Timeline = { durationS: number; messagesPerS: number[]; ratio: number[]; loudnessDb: (number | null)[] };
/* ---------- Chamadas ---------- */
/** Chama /api/clipper/<path>. O erro do serviço ({error}) vira a mensagem. */
export function clipperCall<T>(path: string, method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" = "GET", body?: unknown): Promise<ApiResult<T>> {
return apiCall<T>(`/api/clipper/${path}`, method, body);
}
/** O painel responde "Clipador fora do ar…" (ou "não instalado") quando não alcança o serviço. */
export function isOfflineError(message: string): boolean {
return /fora do ar|não instalado/i.test(message);
}
export type ActionMessage = { ok: boolean; text: string } | null;
/**
* Ações com retorno: guarda qual está rodando (para o spinner certo), mostra sucesso/erro e,
* se deu certo, chama `onDone` (normalmente recarregar os dados).
*/
export function useClipperAction(onDone?: () => void) {
const [pending, setPending] = useState<string | null>(null);
const [message, setMessage] = useState<ActionMessage>(null);
const run = useCallback(async <T,>(key: string, call: () => Promise<ApiResult<T>>, success: string | ((data: T) => string)) => {
setPending(key);
setMessage(null);
const result = await call();
setPending(null);
if (!result.ok) {
setMessage({ ok: false, text: result.error });
return null;
}
setMessage({ ok: true, text: typeof success === "function" ? success(result.data) : success });
onDone?.();
return result.data;
}, [onDone]);
return { pending, message, setMessage, run };
}
/* ---------- Idiomas ---------- */
/** Idiomas que o Clipador conhece (transcrição, textos da IA e público dos canais). O 1º é o padrão. */
export const LANGUAGES: { id: string; label: string; short: string }[] = [
{ id: "pt-BR", label: "Português (Brasil)", short: "PT" },
{ id: "en-US", label: "English (US)", short: "EN" },
{ id: "es-419", label: "Español (Latinoamérica)", short: "ES" },
];
/** Nome legível do idioma ("Português (Brasil)"); código desconhecido volta como está. */
export function languageLabel(code: string | null | undefined): string {
return LANGUAGES.find((l) => l.id === code)?.label ?? (code || "—");
}
/** Sigla curta do idioma ("PT", "EN"); código desconhecido vira a parte antes do hífen em maiúsculas. */
export function languageShort(code: string | null | undefined): string {
return LANGUAGES.find((l) => l.id === code)?.short ?? (code ? code.split("-")[0].toUpperCase() : "—");
}
/* ---------- Rótulos ---------- */
export const PLATFORM_LABEL: Record<ClipperPlatform, string> = { twitch: "Twitch", youtube: "YouTube", kick: "Kick" };
export const SESSION_STATUS: Record<SessionStatus, { label: string; tone: Tone; pulse?: boolean }> = {
starting: { label: "iniciando", tone: "info", pulse: true },
recording: { label: "gravando", tone: "danger", pulse: true },
processing: { label: "processando", tone: "info", pulse: true },
done: { label: "concluída", tone: "success" },
stopped: { label: "parada", tone: "neutral" },
error: { label: "erro", tone: "danger" },
interrupted: { label: "interrompida", tone: "warning" },
};
export const CLIP_STATUS: Record<ClipStatus, { label: string; tone: Tone; pulse?: boolean }> = {
candidate: { label: "esperando a IA", tone: "violet", pulse: true },
pending: { label: "na fila de render", tone: "info" },
rendering: { label: "renderizando", tone: "info", pulse: true },
ready: { label: "pronto para aprovar", tone: "accent" },
approved: { label: "aprovado", tone: "success" },
rejected: { label: "rejeitado", tone: "neutral" },
discarded: { label: "descartado pela IA", tone: "warning" },
published: { label: "publicado", tone: "success" },
error: { label: "erro", tone: "danger" },
};
export const CLIP_STATUS_ORDER: ClipStatus[] = ["candidate", "pending", "rendering", "ready", "approved", "published", "rejected", "discarded", "error"];
export const SOURCE_LABEL: Record<Clip["source"], string> = {
chat: "pico do chat", audio: "pico do áudio", manual: "corte manual", ai: "IA viu na tela", face: "reação no rosto",
};
export const FACE_LABEL: Record<FaceReaction["label"], string> = {
risada: "risada", grito: "grito", susto: "susto", choque: "choque", confuso: "confuso", raiva: "raiva", neutro: "neutro",
};
export const SITUATION_LABEL: Record<Situation, string> = {
lag_ou_bug: "lag ou bug", jogada: "jogada", falha_engracada: "falha engraçada", morte: "morte", susto: "susto", treta: "treta",
conversa_engracada: "conversa engraçada", historia: "história", informacao_do_jogo: "informação do jogo", reacao: "reação", outro: "outro",
};
export const GAME_SOURCE_LABEL: Record<GameSource, string> = {
platform: "categoria da plataforma", screen: "a IA viu na tela", user: "confirmado por você", "": "",
};
export const MODE_LABEL: Record<LayoutMode, { label: string; hint: string }> = {
auto: { label: "Automático", hint: "câmera em cima se houver" },
cam_top: { label: "Câmera em cima", hint: "webcam + jogo" },
blur: { label: "Desfoque", hint: "vídeo inteiro" },
game_only: { label: "Só o jogo", hint: "recorta o jogo" },
cam_only: { label: "Câmera inteira", hint: "só o streamer" },
};
export const TAG_LABEL: Record<keyof ClipTags, string> = { risada: "risada", susto: "susto", hype: "hype", clip: "“clip” no chat" };
export const PROVIDER_LABEL: Record<JudgeProvider, string> = { codex: "Codex (GPT)", claude: "Claude", gemini: "Gemini", off: "Desligado" };
/** Sessões que ainda mudam sozinhas (vale consultar de novo). */
export const ACTIVE_SESSION: SessionStatus[] = ["starting", "recording", "processing"];
/** Cortes que ainda mudam sozinhos (IA ou render). */
export const ACTIVE_CLIP: ClipStatus[] = ["candidate", "pending", "rendering"];
export function chatStatusInfo(status: string): { label: string; tone: Tone } {
if (status === "connected") return { label: "chat conectado", tone: "success" };
if (status === "connecting") return { label: "conectando ao chat", tone: "info" };
if (status === "unsupported") return { label: "sem chat (plataforma)", tone: "neutral" };
if (status === "off" || status === "") return { label: "chat desligado", tone: "neutral" };
return { label: "erro no chat", tone: "danger" };
}
/* ---------- Formatação ---------- */
/** Relógio "m:ss" ou "h:mm:ss". */
export function formatClock(seconds: number): string {
const total = Math.max(0, Math.round(seconds));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = String(total % 60).padStart(2, "0");
return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
}
/** Duração curta: "42 s", "4 min 30 s", "1 h 05 min". */
export function formatDuration(seconds: number): string {
const total = Math.max(0, Math.round(seconds));
if (total < 60) return `${total} s`;
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
if (h > 0) return `${h} h ${String(m).padStart(2, "0")} min`;
const s = total % 60;
return s ? `${m} min ${s} s` : `${m} min`;
}
export function formatScore(score: number): string {
return score.toLocaleString("pt-BR", { maximumFractionDigits: 1 });
}
/** Nome do canal a partir do link da live/VOD (twitch.tv/<canal>, kick.com/<canal>, youtube.com/@canal). */
export function channelFromUrl(url: string): string {
try {
const u = new URL(url);
const first = u.pathname.split("/").filter(Boolean)[0] ?? "";
if (u.hostname.includes("youtu")) return first.startsWith("@") ? first : u.hostname.replace(/^www\./, "");
return first === "videos" ? u.hostname.replace(/^www\./, "") : first || u.hostname;
} catch {
return url;
}
}
/** Rótulo de quem é a live: o nome do canal cadastrado ou o que dá para tirar do link. */
export function sourceName(channelId: string | null, url: string, channels: ClipperChannel[]): string {
const channel = channelId ? channels.find((c) => c.id === channelId) : undefined;
return channel?.displayName || channel?.channel || channelFromUrl(url);
}
/* ---------- Gancho, fontes e formatos (editor de cortes e "Configuração do corte") ---------- */
/** `plain` = texto solto (com caixa opcional); `banner` = tarja na largura toda, texto em maiúsculas em até 2 linhas. */
export type HookStyle = "plain" | "banner";
/** `slide`: a tarja atravessa a tela e o texto entra deslizando, borrado, e assenta nítido. */
export type HookAnim = "pop" | "fade" | "none" | "slide";
/** `y` = centro do gancho em fração da altura (0,04–0,96); null = automático (logo abaixo da câmera). */
export type HookSettings = { style: HookStyle; bg: string; color: string; font: string; anim: HookAnim; seconds: number; y: number | null };
/** Tamanho do vídeo de saída e quadro lógico do ASS (no horizontal os textos são contados em 2560×1440). */
export type FrameSize = { width: number; height: number; canvasWidth: number; canvasHeight: number };
/** Espelho de `layout.DEFAULTS["hook"]` do serviço, só para quando ele não manda o grupo (serviço antigo). */
export const HOOK_FALLBACK: HookSettings = { style: "banner", bg: "#00FF00", color: "#FFFFFF", font: "Luckiest Guy", anim: "slide", seconds: 3, y: null };
/** Grupo `hook` efetivo (o serviço antigo não manda: usa o espelho do padrão). */
export function hookOf(settings: Pick<CutSettings, "hook"> | null | undefined): HookSettings {
return { ...HOOK_FALLBACK, ...(settings?.hook ?? {}) };
}
export const HOOK_STYLE_LABEL: Record<HookStyle, { label: string; hint: string }> = {
banner: { label: "Tarja", hint: "faixa colorida na largura toda" },
plain: { label: "Simples", hint: "texto solto, com caixa opcional" },
};
export const HOOK_ANIM_LABEL: Record<HookAnim, string> = {
slide: "Deslizar com desfoque", pop: "Entrada pop", fade: "Aparecer suave", none: "Sem animação",
};
/** Fontes do Windows que o serviço sempre aceita (as empacotadas vêm de `fontFiles`). */
export const SYSTEM_FONTS = ["Arial Black", "Arial", "Impact", "Verdana", "Segoe UI Black", "Trebuchet MS"];
/* ---------- Qualidade de gravação (grupo `capture`) ---------- */
/** `best` = a maior resolução que a live oferece; as outras são teto (a maior variante que não passa dele). */
export type CaptureQuality = "best" | "1440p" | "1080p" | "720p" | "480p";
/** Uma opção do seletor, como o serviço manda em `captureQualities`. */
export type CaptureOption = {
id: CaptureQuality; label: string; maxHeight: number | null; gbPerHour: number; gbPerHourMax: number; hint: string;
};
/** Resolução, fps, codec e taxa lidos do 1º bloco da gravação (ffprobe). `mixed` = blocos em mais de uma resolução. */
export type CaptureInfo = {
quality: CaptureQuality; width: number; height: number; fps: number | null; codec: string;
kbps: number | null; gbPerHour: number | null; fromIdx: number; at: string; mixed: boolean;
runs?: { fromIdx: number; quality: CaptureQuality; width: number; height: number; fps: number | null; codec: string }[];
};
/** "2560×1440 · 60 fps". */
export function captureLabel(info: Pick<CaptureInfo, "width" | "height" | "fps">): string {
return `${info.width}×${info.height}${info.fps ? ` · ${info.fps} fps` : ""}`;
}
/** "3,2 GB/h" (ou "3,2–4,5 GB/h" quando a opção tem faixa). */
export function gbPerHourLabel(min: number, max?: number | null): string {
const f = (v: number) => v.toLocaleString("pt-BR", { maximumFractionDigits: v < 1 ? 2 : 1 });
return max && max - min >= 0.2 ? `${f(min)}–${f(max)} GB/h` : `${f(min)} GB/h`;
}
/* ---------- Apagar cortes (DELETE clips/<id> · POST clips/delete) ---------- */
/** Por que um corte não foi apagado. `busy_*` = o motor está mexendo nele; `published` = falta confirmar. */
export type ClipDeleteCode = "not_found" | "busy_candidate" | "busy_rendering" | "published" | "changed";
/** Arquivo que ficou no disco (fora das pastas do Clipador, ou em uso). */
export type ClipLeftFile = { file: string; reason: string };
export type ClipDeleted = { id: number; sessionId: number; status: ClipStatus; removedFiles: number; left: ClipLeftFile[] };
export type ClipDeleteFailure = { id: number; code: ClipDeleteCode; reason: string };
/** Resposta do lote: `remaining` = quantos passaram do limite de uma chamada (500). */
export type ClipDeleteResult = { requested: number; remaining: number; deleted: ClipDeleted[]; failed: ClipDeleteFailure[] };
/** Máximo de cortes numa chamada de lote (`clip_delete.MAX_BATCH` do serviço). */
export const CLIP_DELETE_MAX = 500;
/** Estados que o serviço recusa apagar (a IA ou o render está trabalhando no corte). */
export const UNDELETABLE_CLIP: ClipStatus[] = ["candidate", "rendering"];
/** "12 apagados, 1 não pôde: está renderizando" (motivos iguais agrupados). */
export function deleteSummary(result: Pick<ClipDeleteResult, "deleted" | "failed">): string {
const n = result.deleted.length;
const parts = [n === 1 ? "1 corte apagado" : `${n} cortes apagados`];
if (result.failed.length) {
const reasons = new Map<string, number>();
for (const f of result.failed) reasons.set(f.reason, (reasons.get(f.reason) ?? 0) + 1);
const why = [...reasons].map(([reason, k]) => (reasons.size > 1 ? `${k} ${reason}` : reason)).join("; ");
parts.push(`${result.failed.length} não pôde${result.failed.length === 1 ? "" : "ram"}: ${why}`);
}
const left = result.deleted.reduce((sum, d) => sum + (d.left?.length ?? 0), 0); // resposta sem `left` = nada ficou
if (left) parts.push(`${left} arquivo${left === 1 ? " ficou" : "s ficaram"} no disco`);
return parts.join(", ");
}