feat: 抖音取样录制对齐 DouyinLiveRecorder 多线探测与 ffmpeg 重连

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 21:33:22 -05:00
parent 7cf6d02ff3
commit e2f03e4082
4 changed files with 315 additions and 103 deletions

View File

@ -57,20 +57,53 @@ def _html_headers(cookie: str = "") -> dict[str, str]:
def _pick_stream_url(room: dict[str, Any]) -> str:
cands = pick_stream_candidates(room)
return cands[0] if cands else ""
def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list[str]:
"""Build ordered playable URLs — aligned with DouyinLiveRecorder stream.get_douyin_stream_url.
Prefer FLV for Douyin (DLR select_source_url), but keep HLS fallbacks because CDN FLV
lines often 404; quality ladder ORIGIN → FULL_HD1 → HD1 → SD1 → SD2.
"""
stream = room.get("stream_url") or {}
if not isinstance(stream, dict):
return []
flv_map = stream.get("flv_pull_url") or {}
hls_map = stream.get("hls_pull_url_map") or {}
for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"):
if key in flv_map and flv_map[key]:
return str(flv_map[key])
for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"):
if key in hls_map and hls_map[key]:
return str(hls_map[key])
if isinstance(flv_map, dict) and flv_map:
return str(next(iter(flv_map.values())))
if isinstance(hls_map, dict) and hls_map:
return str(next(iter(hls_map.values())))
return str(stream.get("flv_pull_url") or stream.get("hls_pull_url") or "")
if not isinstance(flv_map, dict):
flv_map = {}
if not isinstance(hls_map, dict):
hls_map = {}
order = ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2")
flv_list: list[str] = []
hls_list: list[str] = []
for key in order:
u = str(flv_map.get(key) or "").strip()
if u.startswith("http") and u not in flv_list:
flv_list.append(u)
for key in order:
u = str(hls_map.get(key) or "").strip()
if u.startswith("http") and u not in hls_list:
hls_list.append(u)
for u in list(flv_map.values()) if isinstance(flv_map, dict) else []:
s = str(u or "").strip()
if s.startswith("http") and s not in flv_list:
flv_list.append(s)
for u in list(hls_map.values()) if isinstance(hls_map, dict) else []:
s = str(u or "").strip()
if s.startswith("http") and s not in hls_list:
hls_list.append(s)
single_flv = str(stream.get("flv_pull_url") or "").strip()
if single_flv.startswith("http") and single_flv not in flv_list:
flv_list.append(single_flv)
single_hls = str(stream.get("hls_pull_url") or "").strip()
if single_hls.startswith("http") and single_hls not in hls_list:
hls_list.append(single_hls)
if prefer == "hls":
return hls_list + flv_list
return flv_list + hls_list
def _pick_url_list(node: Any) -> str:
@ -125,6 +158,8 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
room_id = str(room.get("id") or room.get("id_str") or extract_room_id(source_url) or "")
web_rid = extract_room_id(source_url)
cover_image = _pick_cover_image(room)
candidates = pick_stream_candidates(room) if is_live else []
stream_url = candidates[0] if candidates else ""
return {
"ok": True,
"is_live": bool(is_live),
@ -134,13 +169,15 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
"title": title,
"room_id": web_rid or room_id,
"source_url": normalize_room_url(source_url),
"stream_url": _pick_stream_url(room) if is_live else "",
"stream_url": stream_url,
"stream_candidates": candidates,
"cover_image": cover_image,
"raw": {
"status": status_code,
"user_count": room.get("user_count") or room.get("user_count_str") or 0,
"has_stream": bool(_pick_stream_url(room)) if is_live else False,
"has_stream": bool(stream_url),
"has_cover_image": bool(cover_image),
"stream_candidate_count": len(candidates),
},
}

View File

@ -1,23 +1,124 @@
# -*- coding: utf-8 -*-
"""Record a short Douyin live clip with ffmpeg (default 15s, vertical-friendly)."""
"""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 pathlib import Path
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\r\n"
"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 = "",
@ -25,94 +126,152 @@ async def resolve_stream_url(
cookie: str = "",
prefer_fresh: bool = False,
) -> str:
"""Resolve a playable Douyin live URL.
Douyin CDN links expire / 404 quickly. When recording, prefer_fresh=True so we
always re-check the live page instead of trusting a queued stream_url.
"""
src = (source_url or "").strip()
cached = (stream_url or "").strip()
if prefer_fresh and src:
result = await check_room(src, cookie=cookie)
if result.get("ok") and result.get("is_live"):
fresh = str(result.get("stream_url") or "").strip()
if fresh:
return fresh
"""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 ""
if cached:
return cached
if not src:
return ""
result = await check_room(src, cookie=cookie)
if not result.get("ok") or not result.get("is_live"):
return ""
return str(result.get("stream_url") or "").strip()
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_url: str = "",
stream_urls: list[str] | None = None,
seconds: int = 15,
) -> dict[str, Any]:
"""Pull stream for `seconds` and write mp4 under clips_dir."""
url = (stream_url or "").strip()
if not url:
"""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 (letterbox/crop center).
# Prefer crop-to-fill for vertical phones; fallback scale+pad.
# Scale to 1080x1920 Shorts canvas (crop center).
vf = (
"scale=1080:1920:force_original_aspect_ratio=increase,"
"crop=1080:1920,setsar=1"
)
cmd = [
settings.ffmpeg_bin,
"-hide_banner",
"-loglevel",
"error",
"-y",
"-headers",
_headers_arg(),
"-rw_timeout",
"20000000",
"-i",
url,
"-t",
str(sec),
"-vf",
vf,
"-c:v",
"libx264",
"-preset",
"veryfast",
"-crf",
"23",
"-c:a",
"aac",
"-b:a",
"128k",
"-movflags",
"+faststart",
str(out_path),
]
def _run() -> dict[str, Any]:
try:
proc = subprocess.run(cmd, 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}
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
# ffmpeg flags aligned with DouyinLiveRecorder start_record (sans -re for short clips)
cmd = [
settings.ffmpeg_bin,
"-y",
"-hide_banner",
"-loglevel",
"error",
"-user_agent",
_user_agent(),
"-headers",
_headers_arg(),
"-protocol_whitelist",
"file,http,https,tcp,tls,crypto,rtmp,httpproxy,ipv4",
"-thread_queue_size",
"1024",
"-analyzeduration",
"20000000",
"-probesize",
"20000000",
"-fflags",
"+discardcorrupt",
"-rw_timeout",
"30000000",
"-reconnect",
"1",
"-reconnect_streamed",
"-reconnect_at_eof",
"-reconnect_delay_max",
"15",
"-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",
"1",
str(out_path),
]
return await asyncio.to_thread(_run)
def _run() -> dict[str, Any]:
try:
proc = subprocess.run(cmd, 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": 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")):
if len(urls) == 1:
break
# still try next line for transient open errors
continue
return {"ok": False, "error": last_err or "录制失败"}

View File

@ -15,7 +15,7 @@ import time
from typing import Any, Optional
from . import db
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_clip import record_clip, resolve_stream_candidates
from .shorts_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_socks import resolve_upload_socks_proxy
from .shorts_yt_quota import (
@ -1057,11 +1057,14 @@ class ShortsPipeline:
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"])
cookie = str(cfg.get("dy_cookie") or "")
stream = await resolve_stream_url(
candidates = await resolve_stream_candidates(
source_url=str(job.get("source_url") or ""),
stream_url=str(job.get("stream_url") or ""),
cookie=cookie,
prefer_fresh=True,
max_candidates=8,
)
stream = candidates[0] if candidates else ""
if not stream:
err = str(job.get("error") or "")
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
@ -1087,7 +1090,8 @@ class ShortsPipeline:
)
return
sec = int(cfg.get("shorts_clip_sec") or 15)
outcome = await record_clip(job_id=jid, stream_url=stream, seconds=sec)
outcome = await record_clip(job_id=jid, stream_urls=candidates, seconds=sec)
stream = str(outcome.get("stream_url") or stream)
if not outcome.get("ok"):
err = str(outcome.get("error") or "录制失败")
db.update_shorts_job(

View File

@ -11,7 +11,7 @@ from typing import Any, Optional
from . import db
from . import tiktok_db
from . import tiktok_session
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_clip import record_clip, resolve_stream_candidates
from .tiktok_schedule import pick_upload_at, schedule_board
from .tiktok_upload import upload_tiktok_mp4
from .timeutil import push_date_from_ts
@ -387,16 +387,17 @@ class TikTokPipeline:
cookie = str(cfg.get("dy_cookie") or "")
source = str(job.get("source_url") or "")
async def _fresh_stream() -> str:
return await resolve_stream_url(
async def _fresh_candidates() -> list[str]:
return await resolve_stream_candidates(
source_url=source,
stream_url="",
cookie=cookie,
prefer_fresh=True,
max_candidates=8,
)
stream = await _fresh_stream()
if not stream:
candidates = await _fresh_candidates()
if not candidates:
err = str(job.get("error") or "")
# 取样入队时在播,真正开录时可能已下播或取流抖动:给一次重排队
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
@ -416,22 +417,33 @@ class TikTokPipeline:
)
return
# TikTok 素材最少录 1 分钟
# TikTok 素材最少录 1 分钟;多 CDN 线路按 DouyinLiveRecorder 方式试探
sec = max(60, int(cfg.get("tiktok_clip_sec") or 60))
outcome = await record_clip(job_id=f"tiktok_{jid[:8]}", stream_url=stream, seconds=sec)
outcome = await record_clip(
job_id=f"tiktok_{jid[:8]}",
stream_urls=candidates,
seconds=sec,
)
stream = str(outcome.get("stream_url") or (candidates[0] if candidates else ""))
if not outcome.get("ok"):
err = str(outcome.get("error") or "录制失败")
low = err.lower()
# CDN 链接 404 / 打开失败:立刻换新流再试一次
if any(x in low for x in ("404", "error opening", "server returned")) and "stream_ffmpeg_retry" not in str(
# 整批线路失败:重新拉房源再试一次(等价 DLR 换源)
if any(x in low for x in ("404", "error opening", "server returned", "probe 404")) and "stream_ffmpeg_retry" not in str(
job.get("error") or ""
):
stream2 = await _fresh_stream()
if stream2 and stream2 != stream:
outcome2 = await record_clip(job_id=f"tiktok_{jid[:8]}r", stream_url=stream2, seconds=sec)
cands2 = await _fresh_candidates()
# Prefer URLs not already tried
fresh_only = [u for u in cands2 if u not in candidates] or cands2
if fresh_only:
outcome2 = await record_clip(
job_id=f"tiktok_{jid[:8]}r",
stream_urls=fresh_only,
seconds=sec,
)
if outcome2.get("ok"):
outcome = outcome2
stream = stream2
stream = str(outcome2.get("stream_url") or fresh_only[0])
err = ""
else:
err = str(outcome2.get("error") or err)