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: 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 {} stream = room.get("stream_url") or {}
if not isinstance(stream, dict):
return []
flv_map = stream.get("flv_pull_url") or {} flv_map = stream.get("flv_pull_url") or {}
hls_map = stream.get("hls_pull_url_map") or {} hls_map = stream.get("hls_pull_url_map") or {}
for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"): if not isinstance(flv_map, dict):
if key in flv_map and flv_map[key]: flv_map = {}
return str(flv_map[key]) if not isinstance(hls_map, dict):
for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"): hls_map = {}
if key in hls_map and hls_map[key]: order = ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2")
return str(hls_map[key]) flv_list: list[str] = []
if isinstance(flv_map, dict) and flv_map: hls_list: list[str] = []
return str(next(iter(flv_map.values()))) for key in order:
if isinstance(hls_map, dict) and hls_map: u = str(flv_map.get(key) or "").strip()
return str(next(iter(hls_map.values()))) if u.startswith("http") and u not in flv_list:
return str(stream.get("flv_pull_url") or stream.get("hls_pull_url") or "") 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: 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 "") 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) web_rid = extract_room_id(source_url)
cover_image = _pick_cover_image(room) cover_image = _pick_cover_image(room)
candidates = pick_stream_candidates(room) if is_live else []
stream_url = candidates[0] if candidates else ""
return { return {
"ok": True, "ok": True,
"is_live": bool(is_live), "is_live": bool(is_live),
@ -134,13 +169,15 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
"title": title, "title": title,
"room_id": web_rid or room_id, "room_id": web_rid or room_id,
"source_url": normalize_room_url(source_url), "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, "cover_image": cover_image,
"raw": { "raw": {
"status": status_code, "status": status_code,
"user_count": room.get("user_count") or room.get("user_count_str") or 0, "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), "has_cover_image": bool(cover_image),
"stream_candidate_count": len(candidates),
}, },
} }

View File

@ -1,23 +1,124 @@
# -*- coding: utf-8 -*- # -*- 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 from __future__ import annotations
import asyncio import asyncio
import subprocess import subprocess
from pathlib import Path
from typing import Any from typing import Any
import httpx
from .config import settings from .config import settings
from .douyin import check_room from .douyin import check_room
def _headers_arg() -> str: def _headers_arg() -> str:
return ( 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" "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( async def resolve_stream_url(
*, *,
source_url: str = "", source_url: str = "",
@ -25,61 +126,98 @@ async def resolve_stream_url(
cookie: str = "", cookie: str = "",
prefer_fresh: bool = False, prefer_fresh: bool = False,
) -> str: ) -> str:
"""Resolve a playable Douyin live URL. """Resolve a playable Douyin live URL (first candidate after optional probe)."""
cands = await resolve_stream_candidates(
Douyin CDN links expire / 404 quickly. When recording, prefer_fresh=True so we source_url=source_url,
always re-check the live page instead of trusting a queued stream_url. stream_url=stream_url,
""" cookie=cookie,
src = (source_url or "").strip() prefer_fresh=prefer_fresh,
cached = (stream_url or "").strip() )
if prefer_fresh and src: if not cands:
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
return "" return ""
if cached: unknown: list[str] = []
return cached for u in cands:
if not src: alive = await probe_stream_url(u)
return "" if alive is True:
result = await check_room(src, cookie=cookie) return u
if not result.get("ok") or not result.get("is_live"): if alive is None:
return "" unknown.append(u)
return str(result.get("stream_url") or "").strip() if unknown:
return unknown[0]
return cands[0]
async def record_clip( async def record_clip(
*, *,
job_id: str, job_id: str,
stream_url: str, stream_url: str = "",
stream_urls: list[str] | None = None,
seconds: int = 15, seconds: int = 15,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Pull stream for `seconds` and write mp4 under clips_dir.""" """Pull stream for `seconds` and write mp4 under clips_dir.
url = (stream_url or "").strip()
if not url: 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": "无可用流地址"} return {"ok": False, "error": "无可用流地址"}
sec = max(10, min(int(seconds or 15), 180)) sec = max(10, min(int(seconds or 15), 180))
out_dir = settings.clips_dir out_dir = settings.clips_dir
out_dir.mkdir(parents=True, exist_ok=True) out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{job_id}.mp4" out_path = out_dir / f"{job_id}.mp4"
# Scale to 1080x1920 Shorts canvas (letterbox/crop center). # Scale to 1080x1920 Shorts canvas (crop center).
# Prefer crop-to-fill for vertical phones; fallback scale+pad.
vf = ( vf = (
"scale=1080:1920:force_original_aspect_ratio=increase," "scale=1080:1920:force_original_aspect_ratio=increase,"
"crop=1080:1920,setsar=1" "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
# ffmpeg flags aligned with DouyinLiveRecorder start_record (sans -re for short clips)
cmd = [ cmd = [
settings.ffmpeg_bin, settings.ffmpeg_bin,
"-y",
"-hide_banner", "-hide_banner",
"-loglevel", "-loglevel",
"error", "error",
"-y", "-user_agent",
_user_agent(),
"-headers", "-headers",
_headers_arg(), _headers_arg(),
"-rw_timeout", "-protocol_whitelist",
"file,http,https,tcp,tls,crypto,rtmp,httpproxy,ipv4",
"-thread_queue_size",
"1024",
"-analyzeduration",
"20000000", "20000000",
"-probesize",
"20000000",
"-fflags",
"+discardcorrupt",
"-rw_timeout",
"30000000",
"-reconnect",
"1",
"-reconnect_streamed",
"-reconnect_at_eof",
"-reconnect_delay_max",
"15",
"-i", "-i",
url, url,
"-t", "-t",
@ -98,6 +236,8 @@ async def record_clip(
"128k", "128k",
"-movflags", "-movflags",
"+faststart", "+faststart",
"-avoid_negative_ts",
"1",
str(out_path), str(out_path),
] ]
@ -113,6 +253,25 @@ async def record_clip(
return {"ok": False, "error": err} return {"ok": False, "error": err}
if not out_path.is_file() or out_path.stat().st_size < 50_000: if not out_path.is_file() or out_path.stat().st_size < 50_000:
return {"ok": False, "error": "成片过小或不存在"} return {"ok": False, "error": "成片过小或不存在"}
return {"ok": True, "path": str(out_path), "bytes": out_path.stat().st_size, "seconds": sec} return {
"ok": True,
"path": str(out_path),
"bytes": out_path.stat().st_size,
"seconds": sec,
"stream_url": url,
"candidate_index": idx,
}
return await asyncio.to_thread(_run) 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 typing import Any, Optional
from . import db 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_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_socks import resolve_upload_socks_proxy from .shorts_socks import resolve_upload_socks_proxy
from .shorts_yt_quota import ( 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: async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
jid = str(job["id"]) jid = str(job["id"])
cookie = str(cfg.get("dy_cookie") or "") 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 ""), source_url=str(job.get("source_url") or ""),
stream_url=str(job.get("stream_url") or ""), stream_url=str(job.get("stream_url") or ""),
cookie=cookie, cookie=cookie,
prefer_fresh=True,
max_candidates=8,
) )
stream = candidates[0] if candidates else ""
if not stream: if not stream:
err = str(job.get("error") or "") err = str(job.get("error") or "")
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900: if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
@ -1087,7 +1090,8 @@ class ShortsPipeline:
) )
return return
sec = int(cfg.get("shorts_clip_sec") or 15) 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"): if not outcome.get("ok"):
err = str(outcome.get("error") or "录制失败") err = str(outcome.get("error") or "录制失败")
db.update_shorts_job( db.update_shorts_job(

View File

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