Clipador (fila de cortes) - Seletor "Ordenar": mais novos, mais antigos, maior/menor nota da IA, sinal mais forte e mais longos; a escolha fica lembrada no navegador. - A fila abre filtrada pela sessão que está gravando. - Gancho automático logo abaixo da câmera e legenda desviada enquanto o gancho a cobriria; posição do gancho editável no painel. Publicação - "Publicar este corte" ganha "Horário específico": um dia e hora para todas as redes ou um diferente por rede (timing "at" + scheduledAt por rede na rota POST /api/publishing/clips/[id]), com validação e testes. - Capa do vídeo publicado copiada para output/publishing/covers/: apagar a sessão no Clipador não quebra mais a miniatura do dashboard; jobs antigos migram no ciclo de sincronização. - Dashboard só usa capa que existe no disco; corrige a regex do número do episódio (link do episódio). - Canais de publicação: seletor compacto de canais e detalhe reorganizado. - Publicador: confirmação pela página pública quando o YouTube Studio fica com a caixa de envio aberta; estatísticas por rede. Skill cenaforge 1.44.0 com as regras e a armadilha das capas. Testes: painel 68/68, Clipador 279, Publicador 84. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
754 lines
40 KiB
Python
754 lines
40 KiB
Python
"""Render do projeto de edição (editor.py) com FFmpeg: legenda animada e textos em ASS, filtergraph com trechos,
|
||
layout por trecho, zoom (punch-in), narração/música/efeitos, proxy 480p, forma de onda e capa.
|
||
|
||
Regras herdadas do Clipador (gotchas 57/58/71): `-ss` ANTES do `-i`; maiúsculas só no texto (nunca nas tags);
|
||
cores `&H00BBGGRR&` na linha Style e `&HBBGGRR&` nas tags. Formato: o vídeo sai em `layout.frame_size` (1080×1920
|
||
ou 1920×1080) e os textos são contados no quadro lógico `layout.canvas_size` (no horizontal, 2560×1440). Subprocesso sem shell, argumentos em lista; no filtro
|
||
só entram números formatados aqui e nomes de arquivo relativos gerados por nós.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import shutil
|
||
from array import array
|
||
from pathlib import Path
|
||
|
||
from . import layout, media, reframe
|
||
from .editor import Piece, effective_settings, emphasized, output_duration, output_words, pieces, slice_pieces, to_output
|
||
from .scoring import Word
|
||
from .subtitles import _escape, _ts, caption_blocks, clean_words
|
||
|
||
W, H = layout.W, layout.H # quadro do vertical (padrão dos parâmetros); o formato real vem da configuração
|
||
FPS = 30
|
||
PEAKS_PER_S = 50
|
||
COVER_BOX = "#E11D48" # mesma cor da caixa do gancho padrão
|
||
|
||
|
||
# ---------------------------------------------------------------- ASS (legenda animada + textos + barra)
|
||
def _wrap(text: str, size: int, width: int = W - 120) -> str:
|
||
"""Quebra manual (o cabeçalho usa WrapStyle 2 = sem quebra automática). Escapa cada pedaço."""
|
||
max_chars = max(6, int(width / (size * 0.58)))
|
||
lines, line = [], ""
|
||
for word in text.split():
|
||
if line and len(line) + 1 + len(word) > max_chars:
|
||
lines.append(line)
|
||
line = word
|
||
else:
|
||
line = f"{line} {word}".strip()
|
||
if line:
|
||
lines.append(line)
|
||
return "\\N".join(_escape(x) for x in lines[:4])
|
||
|
||
|
||
BANNER_MAX_LINES = 2
|
||
BANNER_SLIDE_MS = 240 # a tarja atravessa a tela
|
||
TEXT_SLIDE_MS = (90, 430) # o texto entra deslizando, borrado, e assenta nítido nesse intervalo
|
||
|
||
|
||
def _lines(text: str, size: int, width: int, char_w: float = 0.6) -> list[str]:
|
||
"""Quebra em linhas pela largura estimada (nunca no meio da palavra)."""
|
||
max_chars = max(4, int(width / (size * char_w)))
|
||
lines, line = [], ""
|
||
for word in text.split():
|
||
if line and len(line) + 1 + len(word) > max_chars:
|
||
lines.append(line)
|
||
line = word
|
||
else:
|
||
line = f"{line} {word}".strip()
|
||
if line:
|
||
lines.append(line)
|
||
return lines
|
||
|
||
|
||
def banner_layout(o: dict, canvas: tuple[int, int]) -> dict:
|
||
"""Geometria da tarja do gancho no quadro lógico: linhas (no máximo 2, sem cortar palavra: a fonte diminui até
|
||
caber), tamanho, topo e altura da faixa."""
|
||
cw, ch = canvas
|
||
text = o["text"].upper()
|
||
size = int(o["size"])
|
||
lines = _lines(text, size, int(cw * 0.9))
|
||
while len(lines) > BANNER_MAX_LINES and size > 24:
|
||
size = max(24, int(size * 0.9))
|
||
lines = _lines(text, size, int(cw * 0.9))
|
||
line_h = size * 1.18
|
||
pad = size * 0.42
|
||
height = int(round(len(lines) * line_h + 2 * pad))
|
||
cy = int(ch * o["y"])
|
||
top = max(0, min(ch - height, cy - height // 2))
|
||
return {"lines": lines, "size": size, "top": top, "height": height, "cy": top + height // 2}
|
||
|
||
|
||
def hook_dodges(project: dict, canvas: tuple[int, int], cap_y: int, cap_size: int,
|
||
total: float) -> list[tuple[float, float, int]]:
|
||
"""Onde a legenda vai enquanto cada gancho está na tela, se ele a cobriria: [(início, fim, y do centro)].
|
||
Com a câmera em cima, o gancho fica logo abaixo dela (layout.hook_y) — o mesmo lugar da legenda automática
|
||
(emenda câmera/jogo). Nesses segundos a legenda desce para logo abaixo do gancho; depois volta ao lugar."""
|
||
_, ch = canvas
|
||
out = []
|
||
for o in project["overlays"]:
|
||
if o["kind"] != "hook":
|
||
continue
|
||
if o.get("style") == "banner":
|
||
g = banner_layout(o, canvas)
|
||
top, bottom = g["top"], g["top"] + g["height"]
|
||
else:
|
||
cy, half = int(ch * o["y"]), int(o["size"] * 0.9)
|
||
top, bottom = cy - half, cy + half
|
||
if cap_y + cap_size <= top or cap_y - cap_size >= bottom:
|
||
continue # não se encostam
|
||
below = bottom + cap_size + 12
|
||
y = below if below + cap_size <= ch else max(cap_size, top - cap_size - 12)
|
||
out.append((float(o["start"]), float(min(o["end"], total)), y))
|
||
return out
|
||
|
||
|
||
def banner_events(o: dict, canvas: tuple[int, int]) -> list[tuple[int, str, str, tuple[float, float | None] | None]]:
|
||
"""Gancho em TARJA (referência do dono, 17/11/2026): faixa na largura toda, na cor `bg`, que atravessa a tela, e o
|
||
texto em maiúsculas (cor `color`, contorno preto grosso, fonte `font`) que entra deslizando com desfoque de
|
||
movimento e assenta nítido. Tudo em ASS (desenho \\p1, \\move e \\t com \\blur): sem filtro extra no FFmpeg.
|
||
|
||
Com contorno, o \\blur do libass desfoca só a borda e o preenchimento fica nítido (achado ao comparar com o modelo
|
||
do dono). Por isso, na ENTRADA (`slide`, até 430 ms) o texto vem em duas camadas: o preenchimento sem contorno, com
|
||
o desfoque animado, e o contorno, também borrado, que aparece junto. Do fim da entrada em diante entra o MESMO
|
||
evento assentado de antes (posição, quebra, tamanho, contorno), para a prévia do editor continuar batendo.
|
||
|
||
Devolve [(camada, estilo, texto ASS, janela)]; janela = None (o tempo todo do gancho) ou (início, fim) em segundos
|
||
relativos ao início do gancho (fim None = até o fim)."""
|
||
cw, _ = canvas
|
||
g = banner_layout(o, canvas)
|
||
bg = layout.ass_inline_color(o.get("bg") or layout.DEFAULTS["hook"]["bg"])
|
||
color = layout.ass_inline_color(o.get("color") or "#FFFFFF")
|
||
font = o.get("font") or layout.HOOK_FONT
|
||
slide = o.get("anim") == "slide"
|
||
out_fade = "\\fad(0,180)"
|
||
band_pos = (f"\\move({-cw},{g['top']},0,{g['top']},0,{BANNER_SLIDE_MS})" if slide else f"\\pos(0,{g['top']})")
|
||
band_anim = out_fade if slide else _anim(o.get("anim", "none")).replace("\\fscx70\\fscy70", "")
|
||
band = (f"{{\\an7{band_pos}\\p1\\bord0\\shad0\\1c{bg}{band_anim}}}"
|
||
f"m 0 0 l {cw} 0 {cw} {g['height']} 0 {g['height']}{{\\p0}}")
|
||
cx = cw // 2
|
||
a, b = TEXT_SLIDE_MS
|
||
border = max(3, int(round(g["size"] * 0.1)))
|
||
lines = "\\N".join(_escape(x) for x in g["lines"])
|
||
look = f"\\fn{font}\\fs{g['size']}\\1c{color}\\3c&H000000&\\4c&H000000&"
|
||
settled_tags = f"\\bord{border}\\shad{max(2, border // 2)}"
|
||
if not slide:
|
||
text = f"{{\\an5\\pos({cx},{g['cy']}){_anim(o.get('anim', 'none'))}{look}{settled_tags}}}{lines}"
|
||
return [(2, "Bar", band, None), (4, "Text", text, None)]
|
||
move = f"\\move({cx + int(cw * 0.55)},{g['cy']},{cx},{g['cy']},{a},{b})"
|
||
entry = (0.0, b / 1000)
|
||
# Preenchimento sem contorno: o desfoque pega a letra inteira (como no modelo).
|
||
fill = f"{{\\an5{move}\\blur18\\t({a},{b},\\blur0){look}\\bord0\\shad0}}{lines}"
|
||
# Contorno (e sombra) sem preenchimento, borrado e surgindo junto; por baixo do preenchimento.
|
||
outline = (f"{{\\an5{move}\\1a&HFF&\\3a&HC0&\\4a&HFF&\\blur18\\t({a},{b},\\blur0\\3a&H00&\\4a&H00&)"
|
||
f"{look}{settled_tags}}}{lines}")
|
||
# Assentado: o mesmo evento de antes, parado na posição final (a saída com \\fad continua no fim do gancho).
|
||
settled = f"{{\\an5\\pos({cx},{g['cy']}){out_fade}{look}{settled_tags}}}{lines}"
|
||
return [(2, "Bar", band, None), (5, "Text", fill, entry), (4, "Text", outline, entry), (4, "Text", settled, (b / 1000, None))]
|
||
|
||
|
||
def _anim(kind: str) -> str:
|
||
if kind == "pop":
|
||
return "\\fad(80,120)\\fscx70\\fscy70\\t(0,140,\\fscx108\\fscy108)\\t(140,220,\\fscx100\\fscy100)"
|
||
if kind == "fade":
|
||
return "\\fad(250,250)"
|
||
if kind == "slide":
|
||
return "\\blur14\\t(0,320,\\blur0)\\fad(0,180)"
|
||
return ""
|
||
|
||
|
||
CHAT_HOLD_S = 9.0 # quanto uma mensagem fica na tela se não chegar outra
|
||
CHAT_COLORS = ("#FF7A7A", "#7AD7FF", "#9BE77A", "#FFD36B", "#C9A2FF", "#FF9FD6")
|
||
|
||
|
||
def chat_events(project: dict, chat: list | None, total: float,
|
||
canvas: tuple[int, int] = (W, H)) -> list[tuple[float, float, str]]:
|
||
"""Chat da live na tela: (início, fim, texto ASS) em tempo de saída. A cada mensagem nova o bloco mostra as
|
||
últimas `lines` (uma linha por mensagem, cortada na largura do bloco), ancorado pela base em (x, y).
|
||
`canvas` = quadro lógico do ASS (largura, altura)."""
|
||
cw, ch = canvas
|
||
cfg = project.get("chat") or {}
|
||
if not cfg.get("enabled") or not chat:
|
||
return []
|
||
cuts = project["cuts"]
|
||
msgs = []
|
||
for m in chat:
|
||
t_out, inside = to_output(m.t, cuts)
|
||
if inside and m.text.strip():
|
||
msgs.append((t_out, m.user, " ".join(m.text.split())))
|
||
msgs.sort(key=lambda x: x[0])
|
||
max_chars = max(8, int(cw * cfg["width"] / (cfg["size"] * 0.54)))
|
||
pos = f"\\an1\\pos({int(cw * cfg['x'])},{int(ch * cfg['y'])})"
|
||
|
||
def line(user: str, text: str) -> str:
|
||
name = user[:16] if cfg["showUser"] and user else ""
|
||
room = max_chars - (len(name) + 2 if name else 0)
|
||
body = text if len(text) <= room else text[: max(1, room - 1)].rstrip() + "…"
|
||
if not name:
|
||
return _escape(body)
|
||
color = layout.ass_inline_color(CHAT_COLORS[sum(map(ord, user)) % len(CHAT_COLORS)])
|
||
return f"{{\\1c{color}}}{_escape(name)}:{{\\1c&HFFFFFF&}} {_escape(body)}"
|
||
|
||
out = []
|
||
for i, (t, _user, _text) in enumerate(msgs):
|
||
nxt = msgs[i + 1][0] if i + 1 < len(msgs) else total
|
||
end = min(total, nxt, t + CHAT_HOLD_S)
|
||
if end - t < 0.03:
|
||
continue
|
||
shown = [m for m in msgs[max(0, i - cfg["lines"] + 1): i + 1] if t - m[0] <= CHAT_HOLD_S * 2]
|
||
out.append((t, end, f"{{{pos}}}" + "\\N".join(line(u, x) for _, u, x in shown)))
|
||
return out
|
||
|
||
|
||
def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1: float | None = None,
|
||
chat: list | None = None) -> str:
|
||
"""ASS do projeto em tempo de saída. [t0, t1] recorta a janela (prévia real de poucos segundos).
|
||
`chat` = mensagens da sessão (ChatMessage) para o bloco de chat na tela, se o projeto pedir."""
|
||
cap, cred = cfg["caption"], cfg["credit"]
|
||
total = output_duration(project["cuts"])
|
||
t1 = total if t1 is None else min(t1, total)
|
||
length = t1 - t0
|
||
base, high, outline = layout.ass_color(cap["color"]), layout.ass_color(cap["highlight"]), layout.ass_color(cap["outline"])
|
||
credit_align, credit_side, credit_margin = layout.credit_placement(cfg)
|
||
cw, ch = layout.canvas_size(cfg)
|
||
font, size, ow = cap["font"], cap["size"], cap["outlineWidth"]
|
||
header = f"""[Script Info]
|
||
ScriptType: v4.00+
|
||
PlayResX: {cw}
|
||
PlayResY: {ch}
|
||
WrapStyle: 2
|
||
ScaledBorderAndShadow: yes
|
||
|
||
[V4+ Styles]
|
||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||
Style: Caption,{font},{size},{base},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{ow},3,5,60,60,0,1
|
||
Style: Karaoke,{font},{size},{high},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{ow},3,5,60,60,0,1
|
||
Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,1,{credit_align},{credit_side},{credit_side},{credit_margin},1
|
||
Style: Text,Arial Black,64,&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,6,2,5,60,60,0,1
|
||
Style: Box,Arial Black,64,&H00FFFFFF,&H00FFFFFF,&H004D1DE1,&H00000000,-1,0,0,0,100,100,0,0,3,18,0,5,60,60,0,1
|
||
Style: Bar,Arial,10,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,7,0,0,0,1
|
||
Style: Chat,Arial,{(project.get('chat') or {}).get('size', 34)},&H00FFFFFF,&H00FFFFFF,&H78000000,&H00000000,-1,0,0,0,100,100,0,0,3,5,0,1,0,0,0,1
|
||
|
||
[Events]
|
||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||
"""
|
||
lines: list[str] = []
|
||
|
||
def event(layer: int, s: float, e: float, style: str, text: str) -> None:
|
||
s, e = max(s, t0) - t0, min(e, t1) - t0
|
||
if e - s > 0.01:
|
||
lines.append(f"Dialogue: {layer},{_ts(s)},{_ts(e)},{style},,0,0,0,,{text}")
|
||
|
||
if credit and cred["enabled"]:
|
||
event(1, 0, total, "Credit", _escape(credit))
|
||
|
||
if cap["enabled"]:
|
||
preset = project["captions"]["preset"]
|
||
emph = emphasized(project)
|
||
emph_c = layout.ass_inline_color(project["captions"]["emphColor"])
|
||
hi_c, base_c = layout.ass_inline_color(cap["highlight"]), layout.ass_inline_color(cap["color"])
|
||
pos = f"\\pos({cw // 2},{layout.caption_y(cfg)})"
|
||
dodges = hook_dodges(project, (cw, ch), layout.caption_y(cfg), int(cap["size"]), total)
|
||
|
||
def at(t: float) -> str:
|
||
"""Posição da legenda no instante t (saída): desviada enquanto um gancho a cobriria."""
|
||
for s, e, y in dodges:
|
||
if s <= t < e:
|
||
return f"\\pos({cw // 2},{y})"
|
||
return pos
|
||
# Ênfase: palavra de saída ↔ palavra marcada no projeto (mesmo texto, mesmo instante), casada nos tempos
|
||
# ORIGINAIS. Depois as palavras são saneadas (ordem, sem sobreposição, duração mínima) — `clean_words` devolve
|
||
# a mesma quantidade, na mesma ordem — e os blocos abaixo nunca ficam dois na tela ao mesmo tempo.
|
||
raw = sorted((w for w in output_words(project) if w.word.strip()), key=lambda w: (w.start, w.end))
|
||
raw_emph = _match_emphasis(raw, project, emph)
|
||
words = clean_words(raw)
|
||
|
||
def txt(w: Word) -> str:
|
||
return _escape(w.word.upper() if cap["uppercase"] else w.word)
|
||
|
||
def key(w: Word) -> tuple[float, str]:
|
||
return round(w.start, 3), w.word # depois de clean_words, cada início é único
|
||
|
||
emph_keys = {key(words[i]) for i in raw_emph}
|
||
for group, g_end in caption_blocks(words, cap["maxWords"]):
|
||
if preset == "karaoke":
|
||
parts, cursor = [], group[0].start
|
||
for w in group:
|
||
gap = max(0, int(round((w.start - cursor) * 100)))
|
||
dur = max(1, int(round((w.end - w.start) * 100)))
|
||
color = f"\\1c{emph_c}" if key(w) in emph_keys else ""
|
||
parts.append((f"{{\\k{gap}}}" if gap else "") + f"{{\\kf{dur}{color}}}{txt(w)}")
|
||
cursor = w.end
|
||
event(0, group[0].start, g_end, "Karaoke", f"{{{at(group[0].start)}}}" + " ".join(parts))
|
||
continue
|
||
for i, word in enumerate(group):
|
||
start = word.start
|
||
end = group[i + 1].start if i + 1 < len(group) else g_end
|
||
if end <= start:
|
||
continue
|
||
if preset == "single":
|
||
color = emph_c if key(word) in emph_keys else (hi_c if len(group) > 1 else base_c)
|
||
event(0, start, end, "Caption", f"{{{at(start)}{_anim('pop')}\\c{color}}}{txt(word)}")
|
||
continue
|
||
parts = []
|
||
for j, w in enumerate(group):
|
||
is_emph = key(w) in emph_keys
|
||
if preset == "minimal":
|
||
parts.append(f"{{\\c{emph_c}}}{txt(w)}{{\\c{base_c}}}" if is_emph else txt(w))
|
||
elif j == i:
|
||
color = emph_c if is_emph else hi_c
|
||
pop = "\\fscx118\\fscy118\\t(0,130,\\fscx100\\fscy100)" if preset == "pop" else ""
|
||
parts.append(f"{{\\c{color}{pop}}}{txt(w)}{{\\c{base_c}\\fscx100\\fscy100}}")
|
||
else:
|
||
parts.append(f"{{\\c{emph_c}}}{txt(w)}{{\\c{base_c}}}" if is_emph else txt(w))
|
||
intro = "\\fscx85\\fscy85\\t(0,90,\\fscx100\\fscy100)" if preset == "pop" and i == 0 else ""
|
||
event(0, start, end, "Caption", f"{{{at(start)}{intro}}}" + " ".join(parts))
|
||
|
||
cuts = project["cuts"]
|
||
for o in project["overlays"]:
|
||
if o["kind"] in ("zoom", "inset"):
|
||
continue
|
||
if o["kind"] == "hook":
|
||
s, e = o["start"], min(o["end"], total)
|
||
else:
|
||
s, e = to_output(o["start"], cuts)[0], to_output(o["end"], cuts)[0]
|
||
if o.get("style") == "banner":
|
||
for layer, style, text, window in banner_events(o, (cw, ch)):
|
||
a0, b0 = (s, e) if window is None else (s + window[0], e if window[1] is None else min(e, s + window[1]))
|
||
event(layer, a0, b0, style, text)
|
||
continue
|
||
style = "Box" if o["box"] else "Text"
|
||
x, y = int(cw * o.get("x", 0.5)), int(ch * o["y"])
|
||
if o["anim"] == "slide": # entra deslizando da direita, borrado, e assenta nítido
|
||
a, b = TEXT_SLIDE_MS
|
||
pos = f"\\move({x + int(cw * 0.5)},{y},{x},{y},{a},{b})"
|
||
else:
|
||
pos = f"\\pos({x},{y})"
|
||
tags = f"{pos}\\fs{o['size']}\\1c{layout.ass_inline_color(o['color'])}"
|
||
if o.get("font"):
|
||
tags += f"\\fn{o['font']}"
|
||
if o["box"]:
|
||
tags += f"\\3c{layout.ass_inline_color(o['box'])}"
|
||
event(2, s, e, style, f"{{{tags}{_anim(o['anim'])}}}{_wrap(o['text'], o['size'], cw - 120)}")
|
||
|
||
for s, e, text in chat_events(project, chat, total, (cw, ch)):
|
||
event(2, s, e, "Chat", text)
|
||
|
||
prog = project["progress"]
|
||
if prog["enabled"] and total > 0:
|
||
h = prog["height"]
|
||
a, b = 100 * t0 / total, 100 * t1 / total
|
||
draw = f"m 0 0 l {cw} 0 {cw} {h} 0 {h}"
|
||
lines.append(f"Dialogue: 3,{_ts(0)},{_ts(length)},Bar,,0,0,0,,"
|
||
f"{{\\an7\\pos(0,{ch - h})\\p1\\1c{layout.ass_inline_color(prog['color'])}\\fscx{a:.2f}"
|
||
f"\\t(0,{int(length * 1000)},\\fscx{b:.2f})}}{draw}{{\\p0}}")
|
||
return header + "\n".join(lines) + "\n"
|
||
|
||
|
||
def _match_emphasis(words: list[Word], project: dict, emph: set[tuple[float, str]]) -> set[int]:
|
||
"""Índices (em `words`, tempo de saída) das palavras marcadas com ênfase no projeto (tempo da sessão)."""
|
||
if not emph:
|
||
return set()
|
||
marked = [w for w in project["captions"]["words"] if not w.get("hidden") and w["w"].strip()]
|
||
out_times = {}
|
||
for w in marked:
|
||
if (round(w["s"], 3), w["w"]) in emph:
|
||
out_times[(round(to_output((w["s"] + w["e"]) / 2, project["cuts"])[0], 2), w["w"])] = True
|
||
result = set()
|
||
for i, w in enumerate(words):
|
||
mid = round((w.start + w.end) / 2, 2)
|
||
if any(abs(mid - t) <= 0.06 and text == w.word for (t, text) in out_times):
|
||
result.add(i)
|
||
return result
|
||
|
||
|
||
# ---------------------------------------------------------------- filtergraph
|
||
def zoom_filter(project: dict, t0: float = 0.0, size: tuple[int, int] = (W, H)) -> str | None:
|
||
"""zoompan com escala por expressão do tempo de saída (`it` + t0). Rampa suave na entrada e na saída.
|
||
`size` = tamanho do vídeo de saída (formato do corte)."""
|
||
zooms = [o for o in project["overlays"] if o["kind"] == "zoom"]
|
||
if not zooms:
|
||
return None
|
||
cuts = project["cuts"]
|
||
z_terms, x_terms, y_terms = [], [], []
|
||
for z in zooms:
|
||
a, b = to_output(z["start"], cuts)[0], to_output(z["end"], cuts)[0]
|
||
if b - a < 0.1:
|
||
continue
|
||
r = max(0.001, min(z["ramp"], (b - a) / 2))
|
||
env = f"clip((T-{a:.3f})/{r:.3f},0,1)*clip(({b:.3f}-T)/{r:.3f},0,1)"
|
||
z_terms.append(f"{z['scale'] - 1:.4f}*{env}")
|
||
x_terms.append(f"{z['x'] - 0.5:.4f}*{env}")
|
||
y_terms.append(f"{z['y'] - 0.5:.4f}*{env}")
|
||
if not z_terms:
|
||
return None
|
||
t = f"(it+{t0:.3f})"
|
||
zexpr = ("1+" + "+".join(z_terms)).replace("T", t)
|
||
fx = ("0.5+" + "+".join(x_terms)).replace("T", t)
|
||
fy = ("0.5+" + "+".join(y_terms)).replace("T", t)
|
||
# x/y = canto do recorte; o foco (fx, fy) fica no centro do recorte, preso dentro do quadro.
|
||
return (f"zoompan=z='{zexpr}':x='max(0,min(iw-iw/zoom,iw*({fx})-iw/zoom/2))'"
|
||
f":y='max(0,min(ih-ih/zoom,ih*({fy})-ih/zoom/2))':d=1:s={size[0]}x{size[1]}:fps={FPS}")
|
||
|
||
|
||
class AudioInput:
|
||
"""Entrada de áudio extra (narração, música, efeito): arquivo + onde entra (tempo de saída) + volume."""
|
||
|
||
def __init__(self, file: Path, at: float, volume: float, kind: str, trim_start: float = 0.0, duck: float = 1.0,
|
||
length: float = 0.0):
|
||
self.file, self.at, self.volume, self.kind = file, at, volume, kind
|
||
self.trim_start, self.duck, self.length = trim_start, duck, length
|
||
|
||
|
||
COVER_INTRO_S = 2 / FPS # capa nos 2 primeiros quadros (as redes usam o quadro 0 como miniatura padrão)
|
||
|
||
|
||
def build_filter(project: dict, cfg: dict, ps: list[Piece], in0: float, ass_name: str | None, extras: list[AudioInput],
|
||
has_audio: bool = True, t0: float = 0.0, original_volume: float = 1.0, cover_input: int | None = None,
|
||
ass_text: str | None = None, insets: list | None = None,
|
||
inset_inputs: list[dict] | None = None) -> str:
|
||
"""filter_complex completo. Entrada 0 = blocos concatenados começando em `in0` (tempo da sessão); entradas 1..N
|
||
= `extras` na ordem; `cover_input` = índice da entrada com a imagem da capa (vai por cima dos 2 primeiros
|
||
quadros); `ass_text` = conteúdo do ASS (com fonte empacotada, o filtro ganha `fontsdir`). `insets` =
|
||
`reframe.InsetPlan` das camadas inseridas e `inset_inputs` = índices das entradas PNG de cada uma. O
|
||
reenquadramento (`project.reframe`) entra por trecho no layout. Sem os dois, o grafo é o mesmo de antes.
|
||
Saídas [v] e [a]."""
|
||
n = len(ps)
|
||
out_len = sum(p.length for p in ps)
|
||
g: list[str] = []
|
||
g.append(f"[0:v]split={n}" + "".join(f"[sv{i}]" for i in range(n)) if n > 1 else "[0:v]null[sv0]")
|
||
if has_audio:
|
||
g.append(f"[0:a]asplit={n}" + "".join(f"[sa{i}]" for i in range(n)) if n > 1 else "[0:a]anull[sa0]")
|
||
for i, p in enumerate(ps):
|
||
a, b = p.start - in0, p.end - in0
|
||
g.append(f"[sv{i}]trim=start={a:.3f}:end={b:.3f},setpts=PTS-STARTPTS,fps={FPS}[tv{i}]")
|
||
src = f"tv{i}"
|
||
if insets: # as camadas recortam o quadro ORIGINAL: uma cópia do trecho vai para elas
|
||
g.append(f"[tv{i}]split=2[tl{i}][tr{i}]")
|
||
src = f"tl{i}"
|
||
g.append(layout.layout_chain(cfg, src, f"pv{i}", ",setsar=1", suffix=f"_{i}", mode=p.mode,
|
||
reframe=reframe.piece_reframe(project, p.start, p.end)))
|
||
fade = min(0.02, p.length / 4)
|
||
if has_audio:
|
||
g.append(f"[sa{i}]atrim=start={a:.3f}:end={b:.3f},asetpts=PTS-STARTPTS,"
|
||
f"aformat=sample_rates=48000:channel_layouts=stereo,"
|
||
f"afade=t=in:d={fade:.3f},afade=t=out:st={max(0.0, p.length - fade):.3f}:d={fade:.3f}"
|
||
+ (",volume=0" if p.muted else "") + f"[pa{i}]")
|
||
else:
|
||
g.append(f"aevalsrc=0|0:s=48000:d={p.length:.3f},aformat=channel_layouts=stereo[pa{i}]")
|
||
g.append("".join(f"[pv{i}][pa{i}]" for i in range(n)) + f"concat=n={n}:v=1:a=1[vcat][acat]")
|
||
fw, fh = layout.frame_size(cfg)
|
||
zoom = zoom_filter(project, t0, (fw, fh))
|
||
last = "[v]" if cover_input is None else "[vbase]"
|
||
head = "[vcat]"
|
||
if insets:
|
||
# Vídeo (com zoom) → camadas inseridas (na ordem do projeto) → texto (ASS) por cima de tudo.
|
||
g.append("".join(f"[tr{i}]" for i in range(n)) + f"concat=n={n}:v=1:a=0[vraw]" if n > 1 else "[tr0]null[vraw]")
|
||
g.append(f"[vcat]{zoom or 'null'}[vzoom]")
|
||
g += reframe.inset_graph(insets, inset_inputs or [], "vzoom", "vraw", t0, (fw, fh), "vins")
|
||
head, zoom = "[vins]", None
|
||
vchain = head + (f"{zoom}," if zoom else "") + (f"{layout.ass_filter(ass_name, ass_text)}," if ass_name else "") + f"fps={FPS},format=yuv420p{last}"
|
||
g.append(vchain)
|
||
if cover_input is not None:
|
||
g.append(f"[{cover_input}:v]scale={fw}:{fh},setsar=1,format=yuv420p[cv]")
|
||
g.append(f"[vbase][cv]overlay=enable='lt(t,{COVER_INTRO_S:.4f})':eof_action=pass,format=yuv420p[v]")
|
||
|
||
# Áudio: original (com volume e abaixado sob a narração) + narração + efeitos; música por baixo com ducking.
|
||
narr = [(k, x) for k, x in enumerate(extras, start=1) if x.kind == "narration"]
|
||
vol_expr = f"{original_volume:.3f}"
|
||
for _, x in narr:
|
||
end = x.at + (x.length or 0)
|
||
if x.duck < 1 and x.length:
|
||
vol_expr = f"{vol_expr}*if(between(t,{x.at:.3f},{end:.3f}),{x.duck:.3f},1)"
|
||
g.append(f"[acat]volume='{vol_expr}':eval=frame[aorig]")
|
||
voice_labels = ["[aorig]"]
|
||
music_label = None
|
||
for k, x in enumerate(extras, start=1):
|
||
chain = f"[{k}:a]aresample=48000,aformat=sample_rates=48000:channel_layouts=stereo"
|
||
if x.trim_start > 0:
|
||
chain += f",atrim=start={x.trim_start:.3f},asetpts=PTS-STARTPTS"
|
||
chain += f",volume={x.volume:.3f}"
|
||
if x.kind == "music":
|
||
g.append(chain + f",atrim=end={out_len:.3f}[m{k}]")
|
||
music_label = f"[m{k}]"
|
||
continue
|
||
delay = int(round(max(0.0, x.at) * 1000))
|
||
g.append(chain + f",adelay=delays={delay}:all=1[x{k}]")
|
||
voice_labels.append(f"[x{k}]")
|
||
if len(voice_labels) > 1:
|
||
g.append("".join(voice_labels) + f"amix=inputs={len(voice_labels)}:duration=first:normalize=0[voice]")
|
||
else:
|
||
g.append("[aorig]anull[voice]")
|
||
if music_label:
|
||
music = next(x for x in extras if x.kind == "music")
|
||
if music.duck < 1: # duck guardado como 0 = sem ducking; < 1 = abaixa sob a voz
|
||
g.append("[voice]asplit=2[voice1][side]")
|
||
g.append(f"{music_label}[side]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=350[mduck]")
|
||
g.append("[voice1][mduck]amix=inputs=2:duration=first:normalize=0[a]")
|
||
else:
|
||
g.append(f"[voice]{music_label}amix=inputs=2:duration=first:normalize=0[a]")
|
||
else:
|
||
g.append("[voice]anull[a]")
|
||
return ";".join(g)
|
||
|
||
|
||
# ---------------------------------------------------------------- execução
|
||
def _segments_for(segments: list[tuple[Path, float, float]], a: float, b: float) -> list[tuple[Path, float, float]]:
|
||
return [s for s in segments if s[2] > a and s[1] < b]
|
||
|
||
|
||
# ---------------------------------------------------------------- blocos de resolução/codec diferentes
|
||
# Uma retomada pode gravar em outra qualidade (ou o streamer muda a resolução da fonte). Medido (17/11/2026, blocos
|
||
# reais 720p60 + 1080p60 do skipnho): o concat demuxer + filter_complex corta o VÍDEO na emenda, sem erro — corte de
|
||
# 35 s saiu com 20 s de vídeo (troca de tamanho: o FFmpeg reinicia o grafo) ou 15 s (H.264 → HEVC). Nesse caso (e só
|
||
# nele) os blocos do trecho viram um intermediário uniforme: maior tamanho do trecho, 30 qps, quadro-chave a cada
|
||
# 0,5 s. Trecho com blocos iguais (o normal) segue pelo caminho de sempre, idêntico.
|
||
_STREAM_CACHE: dict[tuple[str, int, int], tuple[str, int, int, bool] | None] = {}
|
||
|
||
|
||
def _stream_key(ffprobe: str, file: Path) -> tuple[str, int, int, bool] | None:
|
||
"""(codec, largura, altura, tem áudio) do bloco, em cache pelo arquivo (caminho, tamanho, data)."""
|
||
try:
|
||
st = file.stat()
|
||
except OSError:
|
||
return None
|
||
key = (str(file), st.st_size, int(st.st_mtime))
|
||
if key not in _STREAM_CACHE:
|
||
if len(_STREAM_CACHE) > 4000:
|
||
_STREAM_CACHE.clear()
|
||
try:
|
||
out = media.run([ffprobe, "-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height",
|
||
"-of", "csv=p=0", str(file)], 30).decode("utf-8", errors="replace")
|
||
except media.MediaError:
|
||
_STREAM_CACHE[key] = None
|
||
return None
|
||
video, audio = None, False
|
||
for line in out.splitlines():
|
||
parts = [x.strip() for x in line.split(",")]
|
||
if "video" in parts and video is None:
|
||
nums = [int(x) for x in parts if x.isdigit()]
|
||
codec = next((x for x in parts if x and not x.isdigit() and x != "video"), "")
|
||
video = (codec, nums[0], nums[1]) if len(nums) >= 2 else None
|
||
elif "audio" in parts:
|
||
audio = True
|
||
_STREAM_CACHE[key] = (*video, audio) if video else None
|
||
return _STREAM_CACHE[key]
|
||
|
||
|
||
def _ffprobe_near(ffmpeg: str) -> str | None:
|
||
"""ffprobe ao lado do ffmpeg (mesma instalação) ou no PATH."""
|
||
sibling = Path(ffmpeg).with_name("ffprobe" + Path(ffmpeg).suffix)
|
||
return str(sibling) if sibling.is_file() else shutil.which("ffprobe")
|
||
|
||
|
||
def uniform_segments(ffmpeg: str, ffprobe: str | None, segs: list[tuple[Path, float, float]], work: Path,
|
||
stem: str) -> tuple[list[tuple[Path, float, float]], Path | None]:
|
||
"""Blocos do trecho num formato só. Devolve (blocos, intermediário criado ou None); quem chama apaga o arquivo."""
|
||
if not ffprobe or len(segs) < 2:
|
||
return segs, None
|
||
keys = [_stream_key(ffprobe, f) for f, _, _ in segs]
|
||
if any(k is None for k in keys) or len({k[:3] for k in keys}) == 1: # type: ignore[index]
|
||
return segs, None
|
||
w, h = max(((k[1], k[2]) for k in keys), key=lambda size: size[1]) # type: ignore[index]
|
||
out = work / f"{stem}.uniform.mkv"
|
||
args: list[str] = [ffmpeg, "-y", "-v", "error"]
|
||
graph: list[str] = []
|
||
for i, ((file, a, b), k) in enumerate(zip(segs, keys)):
|
||
args += ["-i", str(file)]
|
||
graph.append(f"[{i}:v]scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,"
|
||
f"setsar=1,fps={FPS},format=yuv420p[v{i}]")
|
||
graph.append(f"[{i}:a]aresample=48000,aformat=sample_rates=48000:channel_layouts=stereo[a{i}]" if k[3] # type: ignore[index]
|
||
else f"aevalsrc=0|0:s=48000:d={b - a:.3f}[a{i}]")
|
||
graph.append("".join(f"[v{i}][a{i}]" for i in range(len(segs))) + f"concat=n={len(segs)}:v=1:a=1[v][a]")
|
||
media.run([*args, "-filter_complex", ";".join(graph), "-map", "[v]", "-map", "[a]", "-c:v", "libx264",
|
||
"-preset", "ultrafast", "-crf", "14", "-g", "15", "-c:a", "aac", "-b:a", "256k", str(out)], timeout=900)
|
||
return [(out, segs[0][1], segs[-1][2])], out
|
||
|
||
|
||
def _concat_input(work: Path, stem: str, segs: list[tuple[Path, float, float]], start: float, length: float) -> tuple[list[str], Path]:
|
||
concat = work / f"{stem}.concat.txt"
|
||
concat.write_text("".join(f"file '{p.as_posix()}'\n" for p, _, _ in segs), encoding="utf-8")
|
||
offset = max(0.0, start - segs[0][1])
|
||
# -ss ANTES do -i (gotcha 57): os quadros chegam ao filtro com tempo 0 = `start`.
|
||
return ["-ss", f"{offset:.3f}", "-f", "concat", "-safe", "0", "-i", concat.name, "-t", f"{length:.3f}"], concat
|
||
|
||
|
||
def has_audio_stream(ffprobe: str | None, file: Path) -> bool:
|
||
if not ffprobe:
|
||
return True
|
||
try:
|
||
out = media.run([ffprobe, "-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0",
|
||
str(file)], 30)
|
||
except media.MediaError:
|
||
return True
|
||
return bool(out.strip())
|
||
|
||
|
||
def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segments: list[tuple[Path, float, float]],
|
||
project: dict, base_cfg: dict, credit: str, out_file: Path, repo_root: Path,
|
||
out_range: tuple[float, float] | None = None, timeout: float = 900, chat: list | None = None,
|
||
cover_file: Path | None = None) -> None:
|
||
"""Renderiza o projeto (ou só a saída [a, b] para a prévia real). `segments` = (arquivo, início, fim) da sessão.
|
||
`chat` = mensagens da sessão (para o chat na tela); `cover_file` = capa já renderizada, posta nos 2 primeiros
|
||
quadros quando o projeto pede (`cover.atStart`)."""
|
||
cfg = effective_settings(base_cfg, project)
|
||
total = output_duration(project["cuts"])
|
||
t0, t1 = out_range if out_range else (0.0, total)
|
||
ps = slice_pieces(project["cuts"], t0, t1) if out_range else pieces(project["cuts"])
|
||
if not ps:
|
||
raise media.MediaError("o trecho pedido está fora do corte")
|
||
in0, in1 = ps[0].start, ps[-1].end
|
||
segs = _segments_for(segments, in0, in1)
|
||
if not segs or segs[0][1] > in0 + 0.5 or segs[-1][2] < in1 - 0.5:
|
||
raise media.MediaError("os blocos gravados deste trecho não estão mais disponíveis")
|
||
work = out_file.parent
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
stem = out_file.stem
|
||
segs, uniform = uniform_segments(ffmpeg, ffprobe, segs, work, stem) # emenda de resolução/codec (retomada)
|
||
ass_file = work / f"{stem}.ass"
|
||
ass_text = build_project_ass(project, cfg, credit, t0, t1, chat)
|
||
ass_file.write_text(ass_text, encoding="utf-8")
|
||
input0, concat = _concat_input(work, stem, segs, in0, in1 - in0)
|
||
|
||
extras: list[AudioInput] = []
|
||
for n in project["audio"]["narration"]:
|
||
at = to_output(n["at"], project["cuts"])[0] - t0
|
||
if at + (n["durationS"] or 60) <= 0 or at >= t1 - t0:
|
||
continue
|
||
extras.append(AudioInput(repo_root / n["file"], max(0.0, at), n["volume"], "narration",
|
||
trim_start=max(0.0, -at), duck=n["duck"], length=n["durationS"]))
|
||
for x in project["audio"]["sfx"]:
|
||
at = to_output(x["at"], project["cuts"])[0] - t0
|
||
if 0 <= at < t1 - t0:
|
||
extras.append(AudioInput(repo_root / x["file"], at, x["volume"], "sfx"))
|
||
music = project["audio"]["music"]
|
||
if music:
|
||
extras.append(AudioInput(repo_root / music["file"], 0.0, music["volume"], "music", trim_start=t0,
|
||
duck=0.5 if music["duck"] else 1.0))
|
||
extra_args: list[str] = []
|
||
for x in extras:
|
||
extra_args += (["-stream_loop", "-1"] if x.kind == "music" else []) + ["-i", str(x.file)]
|
||
|
||
cover_input = None
|
||
if cover_file and cover_file.is_file() and project["cover"].get("atStart") and t0 <= 0.001:
|
||
cover_input = len(extras) + 1
|
||
extra_args += ["-loop", "1", "-framerate", str(FPS), "-t", "1", "-i", str(cover_file)]
|
||
# Camadas inseridas: tamanhos pela proporção do vídeo original e PNGs de máscara/borda/sombra, em loop.
|
||
plans, inset_inputs, helper_files = [], [], []
|
||
if any(o["kind"] == "inset" for o in project["overlays"]):
|
||
src_size = media.probe_size(ffprobe, segs[0][0]) if ffprobe else (1280, 720)
|
||
plans = reframe.plan_insets(project, lambda t: to_output(t, project["cuts"])[0], t0, t1,
|
||
layout.frame_size(cfg), layout.canvas_size(cfg)[0], src_size, work, stem)
|
||
next_input = len(extras) + 1 + (1 if cover_input is not None else 0)
|
||
for plan in plans:
|
||
idx = {}
|
||
for key, file in (("mask", plan.mask_file), ("decor", plan.decor_file)):
|
||
if file is None:
|
||
idx[key] = None
|
||
continue
|
||
extra_args += ["-loop", "1", "-framerate", str(FPS), "-t", f"{t1 - t0 + 1:.3f}", "-i", file.name]
|
||
idx[key] = next_input
|
||
next_input += 1
|
||
helper_files.append(file)
|
||
inset_inputs.append(idx)
|
||
graph = build_filter(project, cfg, ps, in0, ass_file.name, extras, has_audio_stream(ffprobe, segs[0][0]), t0,
|
||
project["audio"]["volume"], cover_input, ass_text, plans or None, inset_inputs)
|
||
tmp = work / f"{stem}.tmp.mp4"
|
||
graph_file = work / f"{stem}.graph.txt"
|
||
graph_args = ["-filter_complex", graph]
|
||
if len(graph) > 20000: # muitos keyframes: o grafo vai por arquivo (linha de comando do Windows tem limite)
|
||
graph_file.write_text(graph, encoding="utf-8")
|
||
graph_args = ["-/filter_complex", graph_file.name]
|
||
try:
|
||
media.run([ffmpeg, "-y", "-v", "error", *input0, *extra_args, *graph_args,
|
||
"-map", "[v]", "-map", "[a]", *encoder, "-c:a", "aac", "-b:a", "160k", "-ar", "48000",
|
||
"-t", f"{t1 - t0:.3f}", "-movflags", "+faststart", tmp.name], timeout=timeout, cwd=work)
|
||
tmp.replace(out_file)
|
||
finally:
|
||
for f in (ass_file, concat, tmp, graph_file, *helper_files, *([uniform] if uniform else [])):
|
||
f.unlink(missing_ok=True)
|
||
|
||
|
||
def make_proxy(ffmpeg: str, segments: list[tuple[Path, float, float]], lo: float, hi: float, out_file: Path) -> None:
|
||
"""Vídeo leve (480p, 30 fps, quadro-chave a cada 0,5 s para pular rápido) da janela [lo, hi] para o navegador."""
|
||
segs = _segments_for(segments, lo, hi)
|
||
if not segs:
|
||
raise media.MediaError("nenhum bloco gravado cobre essa janela")
|
||
work = out_file.parent
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
segs, uniform = uniform_segments(ffmpeg, _ffprobe_near(ffmpeg), segs, work, out_file.stem)
|
||
input0, concat = _concat_input(work, out_file.stem, segs, lo, hi - lo)
|
||
tmp = work / f"{out_file.stem}.tmp.mp4"
|
||
try:
|
||
# fps ANTES do scale: com a fonte em 60 qps (1080p60/1440p60) metade dos quadros nem é escalada.
|
||
media.run([ffmpeg, "-y", "-v", "error", *input0, "-vf", f"fps={FPS},scale=-2:480", "-c:v", "libx264",
|
||
"-preset", "veryfast", "-crf", "30", "-g", "15", "-keyint_min", "15", "-pix_fmt", "yuv420p",
|
||
"-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", tmp.name], timeout=600, cwd=work)
|
||
tmp.replace(out_file)
|
||
finally:
|
||
concat.unlink(missing_ok=True)
|
||
tmp.unlink(missing_ok=True)
|
||
if uniform:
|
||
uniform.unlink(missing_ok=True)
|
||
|
||
|
||
def waveform(ffmpeg: str, segments: list[tuple[Path, float, float]], lo: float, hi: float, work: Path) -> list[float]:
|
||
"""Picos de volume (0–1) da janela, `PEAKS_PER_S` por segundo, para desenhar a forma de onda."""
|
||
segs = _segments_for(segments, lo, hi)
|
||
if not segs:
|
||
return []
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
rate = 4000
|
||
input0, concat = _concat_input(work, "waveform", segs, lo, hi - lo)
|
||
try:
|
||
pcm = media.run([ffmpeg, "-v", "error", *input0, "-vn", "-ac", "1", "-ar", str(rate), "-f", "s16le", "-"], 300, cwd=work)
|
||
finally:
|
||
concat.unlink(missing_ok=True)
|
||
samples = array("h")
|
||
samples.frombytes(pcm[: len(pcm) - len(pcm) % 2])
|
||
step = rate // PEAKS_PER_S
|
||
peaks = [max((abs(v) for v in samples[i: i + step]), default=0) / 32768 for i in range(0, len(samples), step)]
|
||
top = max(peaks, default=0) or 1
|
||
return [round(min(1.0, (p / top) ** 0.7), 3) for p in peaks]
|
||
|
||
|
||
def extract_wav(ffmpeg: str, segments: list[tuple[Path, float, float]], a: float, b: float, work: Path) -> bytes:
|
||
"""Áudio mono 16 kHz do trecho [a, b] da sessão, em WAV (para re-transcrever)."""
|
||
segs = _segments_for(segments, a, b)
|
||
if not segs:
|
||
raise media.MediaError("nenhum bloco gravado cobre esse trecho")
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
input0, concat = _concat_input(work, "retranscribe", segs, a, b - a)
|
||
try:
|
||
pcm = media.run([ffmpeg, "-v", "error", *input0, "-vn", "-ac", "1", "-ar", str(media.SAMPLE_RATE), "-f", "s16le", "-"],
|
||
120, cwd=work)
|
||
finally:
|
||
concat.unlink(missing_ok=True)
|
||
return media.to_wav(pcm)
|
||
|
||
|
||
def render_cover(ffmpeg: str, segments: list[tuple[Path, float, float]], project: dict, base_cfg: dict, credit: str,
|
||
out_file: Path) -> Path:
|
||
"""Capa no formato do corte (1080×1920 ou 1920×1080; etapa 7): quadro do instante escolhido no layout do corte +
|
||
texto curto grande no centro."""
|
||
cfg = effective_settings(base_cfg, project)
|
||
cover = project["cover"]
|
||
mode = next((p.mode for p in pieces(project["cuts"]) if p.start <= cover["t"] <= p.end), None)
|
||
if mode and mode != "auto":
|
||
cfg["layout"]["mode"] = mode
|
||
work = out_file.parent
|
||
# Quadro intermediário em PNG: o mjpeg do FFmpeg 7.1 recusa yuv420p marcado como faixa "tv" (blocos do libx264).
|
||
frame = media.grab_frame(ffmpeg, segments, cover["t"], work / f"{out_file.stem}-src.png", width=0)
|
||
cap = {**cfg, "caption": {**cfg["caption"], "enabled": False}}
|
||
ass = build_project_ass({**project, "captions": {**project["captions"], "enabled": False}, "overlays": [],
|
||
"progress": {**project["progress"], "enabled": False}}, cap, credit, 0, 1)
|
||
if cover["text"]:
|
||
cw, ch = layout.canvas_size(cfg)
|
||
line = (f"Dialogue: 4,{_ts(0)},{_ts(1)},Box,,0,0,0,,{{\\pos({cw // 2},{int(ch * 0.5)})\\fs110\\3c{layout.ass_inline_color(COVER_BOX)}}}"
|
||
f"{_wrap(cover['text'].upper(), 110, cw - 120)}")
|
||
ass = ass + line + "\n"
|
||
try:
|
||
media.preview_still(ffmpeg, frame, cap, ass, out_file, reframe.static_reframe(project, cover["t"]))
|
||
finally:
|
||
frame.unlink(missing_ok=True)
|
||
return out_file
|