fix: 修复抖音短录 ffmpeg reconnect 参数导致 Invalid argument

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 21:41:32 -05:00
parent 45c2437a0e
commit f76c5a326f

View File

@ -189,61 +189,63 @@ async def record_clip(
out_path.unlink()
except OSError:
pass
# ffmpeg flags aligned with DouyinLiveRecorder start_record (sans -re for short clips)
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",
"-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),
"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() -> dict[str, Any]:
def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]:
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=sec + 90)
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:
@ -258,7 +260,7 @@ async def record_clip(
"path": str(out_path),
"bytes": out_path.stat().st_size,
"seconds": sec,
"stream_url": url,
"stream_url": used_url,
"candidate_index": idx,
}
@ -268,10 +270,21 @@ async def record_clip(
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 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
# still try next line for transient open errors
continue
return {"ok": False, "error": last_err or "录制失败"}