"""Qualidade de gravação (`capture.quality`), escolha do stream no Streamlink, resolução gravada de fato, busca exata de quadro em .ts (H.264 e HEVC) e render que atravessa blocos de resolução/codec diferentes.""" import json import shutil import subprocess from pathlib import Path import pytest from app import capture, editor, editor_render, layout, media from app.db import loads from app.scoring import Word from .test_sources_and_api import KEY, env, seed_session # noqa: F401 - fixture reaproveitada FFMPEG = shutil.which("ffmpeg") FFPROBE = shutil.which("ffprobe") needs_ffmpeg = pytest.mark.skipif(not (FFMPEG and FFPROBE), reason="FFmpeg não instalado") def auth(): return {"X-Service-Key": KEY} # ---------------------------------------------------------------- configuração (camadas e validação) def test_capture_defaults_to_best_and_layers_field_by_field(): assert layout.merge()["capture"] == {"quality": "best"} assert layout.merge({"capture": {"quality": "720p"}})["capture"]["quality"] == "720p" # canal 720p, sessão 1080p: a sessão vence assert layout.merge({"capture": {"quality": "720p"}}, {"capture": {"quality": "1080p"}})["capture"]["quality"] == "1080p" # configuração antiga (sem o grupo) segue o padrão assert layout.merge({"layout": {"mode": "blur"}})["capture"]["quality"] == "best" @pytest.mark.parametrize("quality", ["best", "1440p", "1080p", "720p", "480p"]) def test_capture_validate_accepts_each_quality(quality): assert layout.validate({"capture": {"quality": quality}}) == {"capture": {"quality": quality}} @pytest.mark.parametrize("bad", [{"capture": {"quality": "4k"}}, {"capture": {"quality": "720p60"}}, {"capture": "best"}, {"capture": {"quality": None}}]) def test_capture_validate_rejects_unknown(bad): with pytest.raises(layout.LayoutError): layout.validate(bad) def test_capture_options_match_the_contract(): assert [o["id"] for o in capture.OPTIONS] == list(capture.QUALITIES) == list(layout.CAPTURE_QUALITIES) for option in capture.OPTIONS: assert option["label"] and option["hint"] and option["gbPerHour"] > 0 assert option["maxHeight"] == capture.CEILING_HEIGHT.get(option["id"]) # ---------------------------------------------------------------- argumentos do Streamlink @pytest.mark.parametrize("platform", ["twitch", "kick", "youtube"]) @pytest.mark.parametrize("quality", ["best", "1440p", "1080p", "720p", "480p"]) def test_stream_choice_per_option_and_platform(platform, quality): choice = capture.stream_choice(quality, platform) opts = list(choice.options) hevc = platform == "twitch" and quality in ("best", "1440p") assert ("--twitch-supported-codecs" in opts) == hevc if hevc: assert opts[opts.index("--twitch-supported-codecs") + 1] == "h264,h265" # sem av1: sem libdav1d no FFmpeg if quality == "best": assert choice.streams == "best" and "--stream-sorting-excludes" not in opts else: assert opts[opts.index("--stream-sorting-excludes") + 1] == f">{quality}60" assert choice.streams == "best,worst-unfiltered" # reserva: nunca falha por causa do teto url = "https://www.twitch.tv/x" assert choice.args(url)[-2:] == [url, choice.streams] def test_unknown_quality_falls_back_to_best(): assert capture.stream_choice("4k", "kick") == capture.stream_choice("best", "kick") # Nomes medidos com `streamlink --json` (17/11/2026). O 2K da Twitch não estava no ar: lista do mesmo formato. TWITCH = ["audio_only", "160p30", "360p30", "480p30", "720p60", "1080p60"] TWITCH_PORTRAIT = TWITCH + ["284p30_portrait", "640p30_portrait", "852p30_portrait", "1280p60_portrait", "1920p60_portrait"] TWITCH_936 = ["audio_only", "160p30", "360p30", "480p30", "720p60", "936p60"] TWITCH_30 = ["audio_only", "160p30", "360p30", "480p30", "720p30", "1080p"] TWITCH_2K = ["audio_only", "160p30", "360p30", "480p30", "720p60", "1080p60", "1440p60"] KICK = ["160p", "360p", "480p", "720p60", "1080p60"] YOUTUBE = ["144p", "240p", "360p", "480p", "720p", "1080p"] YOUTUBE_60 = ["144p", "240p", "360p", "480p", "720p60", "1080p60"] def _pick(names: list[str], choice: capture.StreamChoice) -> str | None: """Mesma escolha da CLI (1º nome da lista que existir), com o `Plugin.streams` de verdade do Streamlink.""" from streamlink import Streamlink from streamlink.plugin import Plugin from streamlink.stream.http import HTTPStream class Fake(Plugin): def _get_streams(self): return {n: HTTPStream(self.session, f"https://e.invalid/{n}") for n in names} opts = list(choice.options) excludes = opts[opts.index("--stream-sorting-excludes") + 1].split(",") if "--stream-sorting-excludes" in opts else None streams = Fake(Streamlink(), "https://e.invalid/").streams(sorting_excludes=excludes) name = next((n for n in choice.streams.split(",") if n in streams), None) return streams[name].url.rsplit("/", 1)[1] if name else None @pytest.mark.parametrize("names,platform,expected", [ (TWITCH, "twitch", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p30"}), (TWITCH_PORTRAIT, "twitch", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p30"}), (TWITCH_936, "twitch", {"best": "936p60", "1440p": "936p60", "1080p": "936p60", "720p": "720p60", "480p": "480p30"}), (TWITCH_30, "twitch", {"best": "1080p", "1440p": "1080p", "1080p": "1080p", "720p": "720p30", "480p": "480p30"}), (TWITCH_2K, "twitch", {"best": "1440p60", "1440p": "1440p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p30"}), (KICK, "kick", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p"}), (YOUTUBE, "youtube", {"best": "1080p", "1440p": "1080p", "1080p": "1080p", "720p": "720p", "480p": "480p"}), (YOUTUBE_60, "youtube", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p"}), ]) def test_preference_picks_largest_under_the_ceiling(names, platform, expected): """Medido nas lives reais com os mesmos argumentos (skipnho, kagura0mea, hpduketv, hotrodd, westcol): mesmo resultado. Variantes verticais (`*_portrait`) e `audio_only` nunca são escolhidas.""" assert {q: _pick(names, capture.stream_choice(q, platform)) for q in capture.QUALITIES} == expected def test_ceiling_with_nothing_below_takes_the_closest_above(): assert _pick(["audio_only", "1080p60"], capture.stream_choice("480p", "twitch")) == "1080p60" assert _pick(["720p60", "1080p60"], capture.stream_choice("480p", "kick")) == "720p60" # ---------------------------------------------------------------- resolução gravada de fato def _make_ts(path: Path, size: str, seconds: float, codec: str = "libx264", rate: int = 60, lum: str | None = None) -> Path: """Bloco .ts sintético com GOP de 2 s (como a Twitch). `lum` = expressão do brilho no tempo (geq).""" src = f"color=c=gray:s={size}:r={rate}:d={seconds}" + (f",geq=lum='{lum}':cb=128:cr=128" if lum else "") codec_args = ["-c:v", codec, "-g", str(2 * rate), "-bf", "0"] if codec == "libx265": codec_args += ["-x265-params", f"keyint={2 * rate}:min-keyint={2 * rate}:open-gop=0:bframes=0:log-level=error"] subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", src, "-f", "lavfi", "-i", f"sine=frequency=440:sample_rate=48000:duration={seconds}", *codec_args, "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", "-f", "mpegts", str(path)], check=True, capture_output=True) return path @needs_ffmpeg def test_probe_block_reads_resolution_fps_codec(tmp_path): info = capture.probe_block(FFPROBE, _make_ts(tmp_path / "a.ts", "320x180", 2)) assert (info["width"], info["height"], info["fps"], info["codec"]) == (320, 180, 60, "h264") assert info["kbps"] and info["gbPerHour"] > 0 def test_record_run_keeps_runs_and_flags_mixed_resolution(): p1 = {"width": 1920, "height": 1080, "fps": 60, "codec": "h264", "kbps": 8000, "gbPerHour": 3.6} first = capture.record_run(None, "best", 0, p1, "t1") assert first["width"] == 1920 and first["quality"] == "best" and first["mixed"] is False and len(first["runs"]) == 1 same = capture.record_run(first, "best", 40, p1, "t2") assert same["mixed"] is False and [r["fromIdx"] for r in same["runs"]] == [0, 40] p2 = {**p1, "width": 1280, "height": 720} mixed = capture.record_run(same, "720p", 80, p2, "t3") assert mixed["height"] == 720 and mixed["fromIdx"] == 80 and mixed["mixed"] is True assert capture.label(mixed) == "1280×720 · 60 qps" @needs_ffmpeg def test_capture_records_real_resolution_on_first_block(env, tmp_path, monkeypatch): # noqa: F811 from dataclasses import replace from app.sources import parse_source from app.worker import Capture client, engine = env sid = seed_session(engine, duration=60) engine.db.run("DELETE FROM segments WHERE session_id = ?", sid) engine.settings = replace(engine.settings, ffprobe=FFPROBE) work = tmp_path / "cap" work.mkdir() _make_ts(work / "seg_00000.ts", "640x360", 2) (work / "segments.csv").write_text("seg_00000.ts,0.000000,2.000000\n", encoding="utf-8") cap = Capture(engine, sid, parse_source("https://www.twitch.tv/alanzoka"), work) cap.quality = "1440p" import app.worker as worker_module monkeypatch.setattr(worker_module, "rel", lambda path: path.as_posix()) # bloco fora do repositório (tmp) assert cap._collect(work / "segments.csv", 0) == 1 info = loads(engine.db.get("SELECT capture_json FROM sessions WHERE id = ?", sid)["capture_json"], None) assert (info["quality"], info["width"], info["height"], info["fps"], info["fromIdx"]) == ("1440p", 640, 360, 60, 0) view = client.get(f"/v1/sessions/{sid}", headers=auth()).json() assert view["capture"]["width"] == 640 and view["capture"]["mixed"] is False def test_session_without_capture_info_reports_none(env): # noqa: F811 client, engine = env sid = seed_session(engine, duration=60) assert client.get(f"/v1/sessions/{sid}", headers=auth()).json()["capture"] is None def test_engine_quality_follows_channel_then_session(env): # noqa: F811 client, engine = env client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth()) sid = seed_session(engine, duration=60) engine.db.run("UPDATE sessions SET channel_id = 'twitch-alanzoka' WHERE id = ?", sid) assert engine.capture_quality(sid) == "best" # padrão novo r = client.put("/v1/channels/twitch-alanzoka/settings", json={"capture": {"quality": "720p"}}, headers=auth()) assert r.status_code == 200 and r.json()["effective"]["capture"]["quality"] == "720p" assert engine.capture_quality(sid) == "720p" r = client.put(f"/v1/sessions/{sid}/settings", json={"capture": {"quality": "1080p"}}, headers=auth()) assert r.json()["effective"]["capture"]["quality"] == "1080p" assert engine.capture_quality(sid) == "1080p" assert client.put(f"/v1/sessions/{sid}/settings", json={"capture": {"quality": "8k"}}, headers=auth()).status_code == 400 def test_settings_route_lists_capture_qualities(env): # noqa: F811 client, engine = env sid = seed_session(engine, duration=60) body = client.get(f"/v1/sessions/{sid}/settings", headers=auth()).json() assert [o["id"] for o in body["captureQualities"]] == list(capture.QUALITIES) assert body["defaults"]["capture"] == {"quality": "best"} # ---------------------------------------------------------------- busca exata de quadro em .ts @needs_ffmpeg @pytest.mark.parametrize("codec", ["libx264", "libx265"]) def test_grab_frame_is_exact_in_ts(tmp_path, codec): """Antes: `-ss` antes do `-i` num .ts dava o PRÓXIMO quadro-chave no H.264 e um quadro CINZA no HEVC.""" if codec == "libx265" and "libx265" not in subprocess.run([FFMPEG, "-hide_banner", "-encoders"], capture_output=True, text=True).stdout: pytest.skip("FFmpeg sem libx265") ts = _make_ts(tmp_path / "b.ts", "160x96", 12, codec=codec, rate=30, lum="min(235,16+T*18)") for t in (3.0, 7.5, 9.3): out = media.grab_frame(FFMPEG, [(ts, 0.0, 12.0)], t, tmp_path / f"f{t}.png", width=0) raw = subprocess.run([FFMPEG, "-v", "error", "-i", str(out), "-f", "rawvideo", "-pix_fmt", "gray", "-"], capture_output=True, check=True).stdout mean = sum(raw) / len(raw) expected = t * 18 * 255 / 219 # Y de faixa limitada (16 + 18·t) → cinza de faixa cheia assert abs(mean - expected) < 6, (t, mean, expected) # 6 ≈ 0,3 s; o próximo quadro-chave daria até 42 def test_seek_args_prerolls_and_selects_absolute_time(): assert media.seek_args(10.0) == (["-ss", "6.000", "-copyts", "-start_at_zero"], "select='gte(t,10.000)'") assert media.seek_args(1.5) == (["-ss", "0.000", "-copyts", "-start_at_zero"], "select='gte(t,1.500)'") # ---------------------------------------------------------------- render que atravessa a troca de resolução @needs_ffmpeg @pytest.mark.parametrize("second", [("640x360", "libx264"), ("960x540", "libx265")]) def test_render_across_resolution_change_keeps_whole_video(tmp_path, second): """Retomada em outra qualidade (ou fonte que muda de resolução). Antes o vídeo parava na emenda (corte de 35 s com 20 s de vídeo; 15 s na troca H.264 → HEVC).""" size, codec = second if codec == "libx265" and "libx265" not in subprocess.run([FFMPEG, "-hide_banner", "-encoders"], capture_output=True, text=True).stdout: pytest.skip("FFmpeg sem libx265") a = _make_ts(tmp_path / "seg_00000.ts", "320x180", 4) b = _make_ts(tmp_path / "seg_00001.ts", size, 4, codec=codec) segs = [(a, 0.0, 4.0), (b, 4.0, 8.0)] same, created = editor_render.uniform_segments(FFMPEG, FFPROBE, [(a, 0.0, 4.0), (a, 4.0, 8.0)], tmp_path, "x") assert created is None and same == [(a, 0.0, 4.0), (a, 4.0, 8.0)] # blocos iguais: caminho de sempre clip = {"session_id": 1, "start_s": 1.0, "end_s": 7.0, "peak_s": 4.0, "title": "Emenda"} project = editor.validate_project(editor.default_project(clip, [Word(1.2, 1.5, "oi")], 8.0), session_id=1, session_duration=8.0, repo_root=tmp_path, tts_dir=tmp_path, assets_dir=tmp_path) project["cover"]["enabled"] = False out = tmp_path / "clip.mp4" editor_render.render_project(FFMPEG, FFPROBE, ["-c:v", "libx264", "-preset", "ultrafast"], segs, project, layout.merge(), "canal", out, tmp_path) streams = json.loads(subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v", "-show_entries", "stream=duration,width,height", "-of", "json", str(out)], capture_output=True, text=True, check=True).stdout)["streams"][0] assert (streams["width"], streams["height"]) == (1080, 1920) assert float(streams["duration"]) == pytest.approx(6.0, abs=0.15) assert not list(tmp_path.glob("*.uniform.mkv")) # intermediário apagado