douyinWEB/backend/app/yt_long_clip.py
eric 7bfead371a feat: isolated YouTube long-form 16:9 module (default off)
Companion to Shorts: 3-8min landscape (9:16 centered), upload as watch?v= not Shorts.
Own yt_long_jobs table/settings; read-only Shorts channel OAuth; never writes shorts_*.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 09:35:33 -05:00

146 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Record landscape 16:9 long clips — isolated from Shorts 9:16 recorder.
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 _landscape_vf() -> str:
"""Fit source to 1080p height, center on 1920x1080 (pillarbox for 9:16)."""
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
async def record_landscape_clip(
*,
job_id: str,
stream_urls: list[str] | None = None,
stream_url: str = "",
seconds: int = 300,
) -> dict[str, Any]:
"""Pull live stream for 3–8 minutes into a 16:9 mp4."""
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 300), YT_LONG_MAX_SEC))
out_path = clips_dir() / f"{job_id}.mp4"
vf = _landscape_vf()
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",
"-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 + 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 "录制失败"}