546 lines
12 KiB
Python
546 lines
12 KiB
Python
|
|
"""
|
|
Kronic YouTube compatibility router.
|
|
|
|
Uses the stripped resolver only for search + fresh yt-dlp format resolution.
|
|
FFmpeg reads the signed GoogleVideo URLs directly. This intentionally bypasses
|
|
Insidious HLS generation AND the resolver media proxy.
|
|
|
|
Existing Kronic frontend routes remain:
|
|
GET /api/video/search?q=...
|
|
GET /api/video/{video_id}
|
|
GET /api/audio/{video_id}
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import os
|
|
from typing import Any
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
|
|
|
router = APIRouter()
|
|
|
|
RESOLVER_URL = os.getenv(
|
|
"KRONIC_RESOLVER_URL",
|
|
"http://172.22.1.25:3030",
|
|
).rstrip("/")
|
|
|
|
PUBLIC_BASE_URL = os.getenv(
|
|
"PUBLIC_BASE_URL",
|
|
"",
|
|
).rstrip("/")
|
|
|
|
MAX_VIDEO_HEIGHT = int(
|
|
os.getenv(
|
|
"KRONIC_VIDEO_MAX_HEIGHT",
|
|
"720",
|
|
)
|
|
)
|
|
|
|
|
|
def public_url(request: Request, path: str) -> str:
|
|
if PUBLIC_BASE_URL:
|
|
return PUBLIC_BASE_URL + path
|
|
return str(request.base_url).rstrip("/") + path
|
|
|
|
|
|
async def resolver_client(request: Request) -> httpx.AsyncClient:
|
|
client = getattr(
|
|
request.app.state,
|
|
"kronic_resolver_client",
|
|
None,
|
|
)
|
|
|
|
if client is None:
|
|
client = httpx.AsyncClient(
|
|
timeout=httpx.Timeout(
|
|
connect=10.0,
|
|
read=60.0,
|
|
write=30.0,
|
|
pool=30.0,
|
|
)
|
|
)
|
|
request.app.state.kronic_resolver_client = client
|
|
|
|
return client
|
|
|
|
|
|
async def resolver_get(
|
|
request: Request,
|
|
path: str,
|
|
*,
|
|
params: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
client = await resolver_client(request)
|
|
|
|
try:
|
|
reply = await client.get(
|
|
RESOLVER_URL + path,
|
|
params=params,
|
|
)
|
|
reply.raise_for_status()
|
|
return reply.json()
|
|
except httpx.HTTPStatusError as error:
|
|
raise HTTPException(
|
|
status_code=502,
|
|
detail=(
|
|
f"resolver HTTP {error.response.status_code}: "
|
|
f"{error.response.text[:1000]}"
|
|
),
|
|
) from error
|
|
except httpx.HTTPError as error:
|
|
raise HTTPException(
|
|
status_code=502,
|
|
detail=f"resolver unavailable: {error}",
|
|
) from error
|
|
|
|
|
|
def codec_family(codec: str | None) -> str:
|
|
codec = (codec or "").lower()
|
|
|
|
if codec.startswith(("avc1", "avc3")) or "h264" in codec:
|
|
return "h264"
|
|
if codec.startswith("av01"):
|
|
return "av1"
|
|
if codec.startswith(("vp09", "vp9")):
|
|
return "vp9"
|
|
|
|
return codec
|
|
|
|
|
|
def choose_video_format(
|
|
formats: list[dict[str, Any]],
|
|
) -> dict[str, Any]:
|
|
candidates = [
|
|
f for f in formats
|
|
if f.get("vcodec")
|
|
and not f.get("acodec")
|
|
and (f.get("height") or 0) > 0
|
|
]
|
|
|
|
if not candidates:
|
|
candidates = [
|
|
f for f in formats
|
|
if f.get("vcodec")
|
|
and (f.get("height") or 0) > 0
|
|
]
|
|
|
|
if not candidates:
|
|
raise HTTPException(
|
|
status_code=502,
|
|
detail="No video format returned by resolver",
|
|
)
|
|
|
|
at_or_below = [
|
|
f for f in candidates
|
|
if (f.get("height") or 0) <= MAX_VIDEO_HEIGHT
|
|
]
|
|
pool = at_or_below or candidates
|
|
|
|
def score(f: dict[str, Any]):
|
|
codec_rank = {
|
|
"h264": 3,
|
|
"av1": 2,
|
|
"vp9": 1,
|
|
}.get(codec_family(f.get("vcodec")), 0)
|
|
|
|
return (
|
|
f.get("height") or 0,
|
|
codec_rank,
|
|
f.get("fps") or 0,
|
|
f.get("bitrate") or 0,
|
|
)
|
|
|
|
return max(pool, key=score)
|
|
|
|
|
|
def choose_audio_format(
|
|
formats: list[dict[str, Any]],
|
|
) -> dict[str, Any]:
|
|
candidates = [
|
|
f for f in formats
|
|
if f.get("acodec") and not f.get("vcodec")
|
|
]
|
|
|
|
if not candidates:
|
|
raise HTTPException(
|
|
status_code=502,
|
|
detail="No audio-only format returned by resolver",
|
|
)
|
|
|
|
def score(f: dict[str, Any]):
|
|
codec = (f.get("acodec") or "").lower()
|
|
|
|
# Prefer AAC so MP4 can be muxed with audio copy.
|
|
if "mp4a" in codec or codec.startswith("aac"):
|
|
codec_rank = 3
|
|
elif "opus" in codec:
|
|
codec_rank = 2
|
|
else:
|
|
codec_rank = 1
|
|
|
|
return (
|
|
codec_rank,
|
|
f.get("bitrate") or 0,
|
|
f.get("audio_channels") or 0,
|
|
)
|
|
|
|
return max(candidates, key=score)
|
|
|
|
|
|
async def resolve_media(
|
|
request: Request,
|
|
video_id: str,
|
|
*,
|
|
refresh: bool = False,
|
|
):
|
|
info = await resolver_get(
|
|
request,
|
|
f"/api/video/{video_id}",
|
|
params={"refresh": str(refresh).lower()},
|
|
)
|
|
|
|
formats = info.get("formats") or []
|
|
|
|
return (
|
|
info,
|
|
choose_video_format(formats),
|
|
choose_audio_format(formats),
|
|
)
|
|
|
|
|
|
def ffmpeg_headers(headers: dict[str, str] | None) -> str | None:
|
|
if not headers:
|
|
return None
|
|
|
|
allowed = {
|
|
"user-agent",
|
|
"referer",
|
|
"origin",
|
|
"accept",
|
|
"accept-language",
|
|
}
|
|
|
|
lines = []
|
|
|
|
for key, value in headers.items():
|
|
if key.lower() in allowed and value:
|
|
lines.append(f"{key}: {value}")
|
|
|
|
if not lines:
|
|
return None
|
|
|
|
return "\r\n".join(lines) + "\r\n"
|
|
|
|
|
|
def add_input(
|
|
command: list[str],
|
|
fmt: dict[str, Any],
|
|
) -> None:
|
|
headers = ffmpeg_headers(
|
|
fmt.get("http_headers")
|
|
)
|
|
|
|
if headers:
|
|
command.extend([
|
|
"-headers",
|
|
headers,
|
|
])
|
|
|
|
command.extend([
|
|
"-i",
|
|
fmt["direct_url"],
|
|
])
|
|
|
|
|
|
async def start_mux(
|
|
*,
|
|
video_id: str,
|
|
video: dict[str, Any],
|
|
audio: dict[str, Any],
|
|
) -> StreamingResponse:
|
|
command = [
|
|
"ffmpeg",
|
|
"-nostdin",
|
|
"-hide_banner",
|
|
"-loglevel",
|
|
"warning",
|
|
]
|
|
|
|
add_input(command, video)
|
|
add_input(command, audio)
|
|
|
|
command.extend([
|
|
"-map",
|
|
"0:v:0",
|
|
"-map",
|
|
"1:a:0",
|
|
])
|
|
|
|
if codec_family(video.get("vcodec")) == "h264":
|
|
command.extend([
|
|
"-c:v",
|
|
"copy",
|
|
])
|
|
else:
|
|
command.extend([
|
|
"-c:v",
|
|
"libx264",
|
|
"-preset",
|
|
"veryfast",
|
|
"-crf",
|
|
"23",
|
|
"-pix_fmt",
|
|
"yuv420p",
|
|
])
|
|
|
|
audio_codec = (audio.get("acodec") or "").lower()
|
|
|
|
if "mp4a" in audio_codec or audio_codec.startswith("aac"):
|
|
command.extend([
|
|
"-c:a",
|
|
"copy",
|
|
])
|
|
else:
|
|
command.extend([
|
|
"-c:a",
|
|
"aac",
|
|
"-b:a",
|
|
"160k",
|
|
])
|
|
|
|
command.extend([
|
|
"-movflags",
|
|
"frag_keyframe+empty_moov+default_base_moof",
|
|
"-f",
|
|
"mp4",
|
|
"pipe:1",
|
|
])
|
|
|
|
print(
|
|
"Kronic YouTube mux:",
|
|
{
|
|
"video_id": video_id,
|
|
"video_format": video.get("id"),
|
|
"height": video.get("height"),
|
|
"fps": video.get("fps"),
|
|
"vcodec": video.get("vcodec"),
|
|
"audio_format": audio.get("id"),
|
|
"acodec": audio.get("acodec"),
|
|
},
|
|
flush=True,
|
|
)
|
|
|
|
process = await asyncio.create_subprocess_exec(
|
|
*command,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE,
|
|
)
|
|
|
|
assert process.stdout is not None
|
|
assert process.stderr is not None
|
|
|
|
async def stream():
|
|
sent = False
|
|
|
|
try:
|
|
while True:
|
|
chunk = await process.stdout.read(
|
|
256 * 1024
|
|
)
|
|
|
|
if not chunk:
|
|
break
|
|
|
|
sent = True
|
|
yield chunk
|
|
|
|
rc = await process.wait()
|
|
|
|
if rc != 0 or not sent:
|
|
error = (
|
|
await process.stderr.read()
|
|
).decode(
|
|
"utf-8",
|
|
"replace",
|
|
)
|
|
|
|
print(
|
|
"Kronic YouTube ffmpeg failed:",
|
|
{
|
|
"video_id": video_id,
|
|
"returncode": rc,
|
|
"stderr": error[-5000:],
|
|
},
|
|
flush=True,
|
|
)
|
|
|
|
finally:
|
|
if process.returncode is None:
|
|
process.kill()
|
|
await process.wait()
|
|
|
|
return StreamingResponse(
|
|
stream(),
|
|
media_type="video/mp4",
|
|
headers={
|
|
"Cache-Control": "no-store",
|
|
"X-Kronic-Source": "youtube-resolver",
|
|
},
|
|
)
|
|
|
|
|
|
@router.get("/api/video/search")
|
|
async def video_search(
|
|
request: Request,
|
|
q: str,
|
|
limit: int = 20,
|
|
) -> JSONResponse:
|
|
data = await resolver_get(
|
|
request,
|
|
"/api/search",
|
|
params={
|
|
"q": q,
|
|
"limit": limit,
|
|
},
|
|
)
|
|
|
|
items = []
|
|
|
|
for item in data.get("items") or []:
|
|
video_id = item["id"]
|
|
|
|
items.append({
|
|
"id": video_id,
|
|
"title": item.get("title") or video_id,
|
|
"artist": item.get("channel"),
|
|
"duration": item.get("duration"),
|
|
"thumbnail": item.get("thumbnail"),
|
|
"videoUrl": public_url(
|
|
request,
|
|
f"/api/video/{video_id}",
|
|
),
|
|
"audioUrl": public_url(
|
|
request,
|
|
f"/api/audio/{video_id}",
|
|
),
|
|
"watchUrl": (
|
|
f"https://www.youtube.com/watch?v={video_id}"
|
|
),
|
|
# Keep current Kronic frontend compatibility.
|
|
"source": "invidious",
|
|
})
|
|
|
|
return JSONResponse({"items": items})
|
|
|
|
|
|
@router.options("/api/video/{video_id}")
|
|
async def video_options(video_id: str) -> Response:
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.get("/api/video/{video_id}")
|
|
async def video_stream(
|
|
request: Request,
|
|
video_id: str,
|
|
) -> StreamingResponse:
|
|
_info, video, audio = await resolve_media(
|
|
request,
|
|
video_id,
|
|
)
|
|
|
|
return await start_mux(
|
|
video_id=video_id,
|
|
video=video,
|
|
audio=audio,
|
|
)
|
|
|
|
|
|
@router.options("/api/audio/{video_id}")
|
|
async def audio_options(video_id: str) -> Response:
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.get("/api/audio/{video_id}")
|
|
async def audio_stream(
|
|
request: Request,
|
|
video_id: str,
|
|
) -> StreamingResponse:
|
|
_info, _video, audio = await resolve_media(
|
|
request,
|
|
video_id,
|
|
)
|
|
|
|
command = [
|
|
"ffmpeg",
|
|
"-nostdin",
|
|
"-hide_banner",
|
|
"-loglevel",
|
|
"warning",
|
|
]
|
|
|
|
add_input(command, audio)
|
|
|
|
audio_codec = (audio.get("acodec") or "").lower()
|
|
|
|
if "mp4a" in audio_codec or audio_codec.startswith("aac"):
|
|
command.extend([
|
|
"-vn",
|
|
"-c:a",
|
|
"copy",
|
|
])
|
|
else:
|
|
command.extend([
|
|
"-vn",
|
|
"-c:a",
|
|
"aac",
|
|
"-b:a",
|
|
"160k",
|
|
])
|
|
|
|
command.extend([
|
|
"-movflags",
|
|
"frag_keyframe+empty_moov+default_base_moof",
|
|
"-f",
|
|
"mp4",
|
|
"pipe:1",
|
|
])
|
|
|
|
process = await asyncio.create_subprocess_exec(
|
|
*command,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE,
|
|
)
|
|
|
|
assert process.stdout is not None
|
|
assert process.stderr is not None
|
|
|
|
async def stream():
|
|
try:
|
|
while True:
|
|
chunk = await process.stdout.read(
|
|
256 * 1024
|
|
)
|
|
|
|
if not chunk:
|
|
break
|
|
|
|
yield chunk
|
|
finally:
|
|
if process.returncode is None:
|
|
process.kill()
|
|
await process.wait()
|
|
|
|
return StreamingResponse(
|
|
stream(),
|
|
media_type="audio/mp4",
|
|
headers={
|
|
"Cache-Control": "no-store",
|
|
"X-Kronic-Source": "youtube-resolver",
|
|
},
|
|
)
|