# -*- coding: utf-8 -*- """Record a short Douyin live clip with ffmpeg (default 15s, vertical-friendly). Stream picking / ffmpeg flags follow DouyinLiveRecorder patterns: https://github.com/ihmily/DouyinLiveRecorder """ from __future__ import annotations import asyncio import subprocess from typing import Any import httpx from .config import settings from .douyin import check_room def _headers_arg() -> str: return ( "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1\r\n" "Referer: https://live.douyin.com/\r\n" ) def _user_agent() -> str: return ( "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1" ) async def probe_stream_url(url: str, *, timeout: float = 8.0) -> bool | None: """Probe CDN line. True=alive, False=dead(404/403), None=unknown (try ffmpeg anyway).""" u = (url or "").strip() if not u.startswith("http"): return False headers = { "User-Agent": _user_agent(), "Referer": "https://live.douyin.com/", } try: async with httpx.AsyncClient( timeout=httpx.Timeout(timeout, connect=5.0), verify=False, trust_env=False, follow_redirects=True, ) as client: try: resp = await client.head(u, headers=headers) if resp.status_code == 200: return True if resp.status_code in (403, 405, 501): resp = await client.get(u, headers={**headers, "Range": "bytes=0-1"}) if resp.status_code in (200, 206): return True if resp.status_code in (404, 410, 403): return False return None if resp.status_code in (404, 410): return False return None except Exception: try: resp = await client.get(u, headers={**headers, "Range": "bytes=0-1"}) if resp.status_code in (200, 206): return True if resp.status_code in (404, 410, 403): return False except Exception: pass return None except Exception: return None async def resolve_stream_candidates( *, source_url: str = "", stream_url: str = "", cookie: str = "", prefer_fresh: bool = False, max_candidates: int = 6, ) -> list[str]: """Resolve ordered playable Douyin URLs (FLV ladder + HLS fallbacks).""" src = (source_url or "").strip() cached = (stream_url or "").strip() out: list[str] = [] def _extend(urls: list[str]) -> None: for u in urls: s = str(u or "").strip() if s.startswith("http") and s not in out: out.append(s) if prefer_fresh and src: result = await check_room(src, cookie=cookie) if result.get("ok") and result.get("is_live"): cands = result.get("stream_candidates") or [] if isinstance(cands, list): _extend([str(x) for x in cands]) fresh = str(result.get("stream_url") or "").strip() if fresh: _extend([fresh]) return out[: max(1, max_candidates)] if cached: _extend([cached]) if src: result = await check_room(src, cookie=cookie) if result.get("ok") and result.get("is_live"): cands = result.get("stream_candidates") or [] if isinstance(cands, list): _extend([str(x) for x in cands]) fresh = str(result.get("stream_url") or "").strip() if fresh: _extend([fresh]) return out[: max(1, max_candidates)] async def resolve_stream_url( *, source_url: str = "", stream_url: str = "", cookie: str = "", prefer_fresh: bool = False, ) -> str: """Resolve a playable Douyin live URL (first candidate after optional probe).""" cands = await resolve_stream_candidates( source_url=source_url, stream_url=stream_url, cookie=cookie, prefer_fresh=prefer_fresh, ) if not cands: return "" unknown: list[str] = [] for u in cands: alive = await probe_stream_url(u) if alive is True: return u if alive is None: unknown.append(u) if unknown: return unknown[0] return cands[0] async def record_clip( *, job_id: str, stream_url: str = "", stream_urls: list[str] | None = None, seconds: int = 15, ) -> dict[str, Any]: """Pull stream for `seconds` and write mp4 under clips_dir. Tries multiple CDN lines (FLV then HLS) like DouyinLiveRecorder quality fallback. """ 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(10, min(int(seconds or 15), 180)) out_dir = settings.clips_dir out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / f"{job_id}.mp4" # Scale to 1080x1920 Shorts canvas (crop center). vf = ( "scale=1080:1920:force_original_aspect_ratio=increase," "crop=1080:1920,setsar=1" ) last_err = "" for idx, url in enumerate(urls): # Skip known-dead lines when alternatives exist 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() # Keep input options conservative: bad reconnect flags caused EINVAL on Douyin CDN. # Short clips don't need long-lived reconnect like DouyinLiveRecorder full captures. cmd = [ settings.ffmpeg_bin, "-y", "-hide_banner", "-loglevel", "error", "-headers", _headers_arg(), "-rw_timeout", "20000000", ] if not is_hls: # HTTP FLV reconnect (must pass explicit 1 — bare flags break avformat_open_input) 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", "-preset", "veryfast", "-crf", "23", "-c:a", "aac", "-b:a", "128k", "-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: proc = subprocess.run(cmd_local, capture_output=True, text=True, timeout=sec + 90) except subprocess.TimeoutExpired: return {"ok": False, "error": "ffmpeg 录制超时"} except Exception as exc: return {"ok": False, "error": f"ffmpeg 启动失败: {exc}"} if proc.returncode != 0: err = (proc.stderr or proc.stdout or "ffmpeg failed")[-400:] return {"ok": False, "error": err} if not out_path.is_file() or out_path.stat().st_size < 50_000: return {"ok": False, "error": "成片过小或不存在"} return { "ok": True, "path": str(out_path), "bytes": out_path.stat().st_size, "seconds": sec, "stream_url": used_url, "candidate_index": idx, } outcome = await asyncio.to_thread(_run) if outcome.get("ok"): return outcome last_err = str(outcome.get("error") or last_err or "录制失败") # Only cascade on CDN / open failures; keep other errors low = last_err.lower() if not any( x in low for x in ( "404", "403", "error opening", "server returned", "input/output", "timed out", "timeout", "invalid argument", ) ): if len(urls) == 1: break continue return {"ok": False, "error": last_err or "录制失败"}