# -*- coding: utf-8 -*- """Record YouTube long-form clips (default 9:16). 16:9 landscape is opt-in and off. Reuses only side-effect-free stream helpers from shorts_clip. Writes under clips_dir/yt_long/ so filenames never collide with Shorts. """ from __future__ import annotations import asyncio import subprocess from pathlib import Path from typing import Any from .config import settings from .shorts_clip import _headers_arg, probe_stream_url from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC def _portrait_vf() -> str: """Vertical 9:16 at 720x1280 — matches Shorts CPU profile for 4c VPS.""" return ( "scale=720:1280:force_original_aspect_ratio=increase," "crop=720:1280,setsar=1" ) def _landscape_vf() -> str: """Legacy 16:9 pillarbox — disabled unless yt_long_landscape_16x9=True.""" return ( "scale=-2:1080:force_original_aspect_ratio=decrease," "pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black,setsar=1" ) def clips_dir() -> Path: d = settings.clips_dir / "yt_long" d.mkdir(parents=True, exist_ok=True) return d def _vf_for_settings(cfg: dict[str, Any] | None = None) -> str: from . import db settings_map = cfg if cfg is not None else db.get_settings_map() if bool(settings_map.get("yt_long_landscape_16x9", False)): return _landscape_vf() return _portrait_vf() async def record_long_clip( *, job_id: str, stream_urls: list[str] | None = None, stream_url: str = "", seconds: int = 600, cfg: dict[str, Any] | None = None, ) -> dict[str, Any]: """Pull live stream for 8–15 minutes into a 9:16 mp4 (16:9 only if explicitly enabled).""" urls: list[str] = [] for u in list(stream_urls or []) + [stream_url]: s = str(u or "").strip() if s.startswith("http") and s not in urls: urls.append(s) if not urls: return {"ok": False, "error": "无可用流地址"} sec = max(YT_LONG_MIN_SEC, min(int(seconds or 600), YT_LONG_MAX_SEC)) out_path = clips_dir() / f"{job_id}.mp4" vf = _vf_for_settings(cfg) last_err = "" for url in urls: if len(urls) > 1: alive = await probe_stream_url(url) if alive is False: last_err = f"probe 404: {url[:80]}" continue if out_path.is_file(): try: out_path.unlink() except OSError: pass is_hls = ".m3u8" in url.lower() or "/playlist" in url.lower() cmd = [ settings.ffmpeg_bin, "-y", "-hide_banner", "-loglevel", "error", "-headers", _headers_arg(), "-rw_timeout", "20000000", ] if not is_hls: cmd.extend( [ "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_at_eof", "1", "-reconnect_delay_max", "8", ] ) cmd.extend( [ "-i", url, "-t", str(sec), "-vf", vf, "-c:v", "libx264", "-threads", "2", "-preset", "ultrafast", "-crf", "26", "-c:a", "aac", "-b:a", "96k", "-movflags", "+faststart", "-avoid_negative_ts", "make_zero", str(out_path), ] ) def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]: try: from .procutil import run_outside_api_cgroup proc = run_outside_api_cgroup( cmd_local, capture_output=True, text=True, timeout=sec + 180, ) except subprocess.TimeoutExpired: return {"ok": False, "error": "ffmpeg 超时", "stream_url": used_url} except Exception as exc: return {"ok": False, "error": str(exc)[:400], "stream_url": used_url} if proc.returncode != 0: err = (proc.stderr or proc.stdout or "ffmpeg failed")[:500] return {"ok": False, "error": err, "stream_url": used_url} if not out_path.is_file() or out_path.stat().st_size < 50_000: return {"ok": False, "error": "成片过小或不存在", "stream_url": used_url} return { "ok": True, "path": str(out_path), "seconds": sec, "stream_url": used_url, } outcome = await asyncio.to_thread(_run) if outcome.get("ok"): return outcome last_err = str(outcome.get("error") or last_err) return {"ok": False, "error": last_err or "录制失败"} # Back-compat alias (name kept so older imports do not break) async def record_landscape_clip(**kwargs: Any) -> dict[str, Any]: return await record_long_clip(**kwargs)