Upload files to "/"
This commit is contained in:
+283
@@ -0,0 +1,283 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from guessit import guessit
|
||||||
|
from pymediainfo import MediaInfo
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
load_dotenv(BASE_DIR / "config.env")
|
||||||
|
MIN_MEDIA_DURATION = float(os.getenv("MIN_MEDIA_DURATION", "30"))
|
||||||
|
|
||||||
|
VIDEO_EXTENSIONS = {
|
||||||
|
".mkv", ".mp4", ".m4v", ".avi", ".mov", ".webm",
|
||||||
|
".mpg", ".mpeg", ".ts", ".m2ts", ".wmv",
|
||||||
|
}
|
||||||
|
|
||||||
|
NOISE_TOKENS = {
|
||||||
|
"480p", "576p", "720p", "1080p", "1080i", "1440p", "2160p", "4k", "8k",
|
||||||
|
"bluray", "blu-ray", "bdrip", "brrip", "web", "webdl", "web-dl", "webrip", "web-rip",
|
||||||
|
"hdtv", "dvdrip", "remux", "x264", "x265", "h264", "h265", "hevc", "avc", "av1",
|
||||||
|
"aac", "aac2", "ac3", "eac3", "ddp", "ddp5", "ddp51", "truehd", "atmos", "dts", "dtshd",
|
||||||
|
"proper", "repack", "internal", "hdr", "hdr10", "hdr10plus", "dolbyvision", "dv",
|
||||||
|
}
|
||||||
|
|
||||||
|
KNOWN_PREFIXES = ("wanshow", "wan show")
|
||||||
|
|
||||||
|
ACRONYMS = {
|
||||||
|
"ai": "AI", "amd": "AMD", "arc": "Arc", "cpu": "CPU", "cpus": "CPUs",
|
||||||
|
"ddr4": "DDR4", "ddr5": "DDR5", "gpu": "GPU", "gpus": "GPUs", "hdr": "HDR",
|
||||||
|
"intel": "Intel", "linux": "Linux", "mac": "Mac", "nvidia": "NVIDIA", "oled": "OLED",
|
||||||
|
"pc": "PC", "pcs": "PCs", "ram": "RAM", "ssd": "SSD", "usb": "USB", "vr": "VR",
|
||||||
|
"wan": "WAN", "wifi": "WiFi",
|
||||||
|
}
|
||||||
|
|
||||||
|
SMALL_WORDS = {
|
||||||
|
"a", "an", "and", "as", "at", "but", "by", "for", "from", "in", "into", "of", "on",
|
||||||
|
"or", "the", "to", "vs", "with",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_number(value):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
value = value[0]
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def looks_like_random_id(token):
|
||||||
|
token = str(token).strip()
|
||||||
|
if len(token) < 8 or len(token) > 20 or " " in token:
|
||||||
|
return False
|
||||||
|
letters = [c for c in token if c.isalpha()]
|
||||||
|
has_upper = any(c.isupper() for c in letters)
|
||||||
|
has_lower = any(c.islower() for c in letters)
|
||||||
|
has_digit = any(c.isdigit() for c in token)
|
||||||
|
has_separator = "-" in token or "_" in token
|
||||||
|
return has_digit and ((has_upper and has_lower) or has_separator)
|
||||||
|
|
||||||
|
|
||||||
|
def smart_title_case(text):
|
||||||
|
words = text.split()
|
||||||
|
output = []
|
||||||
|
for index, word in enumerate(words):
|
||||||
|
stripped = word.strip()
|
||||||
|
if not stripped:
|
||||||
|
continue
|
||||||
|
lower = stripped.lower()
|
||||||
|
if lower in ACRONYMS:
|
||||||
|
output.append(ACRONYMS[lower])
|
||||||
|
continue
|
||||||
|
if index > 0 and lower in SMALL_WORDS:
|
||||||
|
output.append(lower)
|
||||||
|
continue
|
||||||
|
if any(c.isupper() for c in stripped[1:]) and any(c.islower() for c in stripped):
|
||||||
|
output.append(stripped)
|
||||||
|
continue
|
||||||
|
if any(c.isdigit() for c in stripped):
|
||||||
|
output.append(stripped if stripped.isupper() else stripped[:1].upper() + stripped[1:])
|
||||||
|
continue
|
||||||
|
output.append(stripped[:1].upper() + stripped[1:].lower())
|
||||||
|
return " ".join(output)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_known_prefixes(text):
|
||||||
|
cleaned = text.strip()
|
||||||
|
lowered = cleaned.lower()
|
||||||
|
for prefix in KNOWN_PREFIXES:
|
||||||
|
if lowered == prefix:
|
||||||
|
return ""
|
||||||
|
for sep in (" ", "-", "_"):
|
||||||
|
if lowered.startswith(prefix + sep):
|
||||||
|
return cleaned[len(prefix) + 1:].strip()
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def remove_trailing_random_id(text):
|
||||||
|
parts = text.split()
|
||||||
|
if parts and looks_like_random_id(parts[-1]):
|
||||||
|
parts.pop()
|
||||||
|
return " ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_noise_tokens(text):
|
||||||
|
output = []
|
||||||
|
for token in text.split():
|
||||||
|
normalized = token.lower().strip("[](){}.,")
|
||||||
|
if normalized in NOISE_TOKENS:
|
||||||
|
continue
|
||||||
|
output.append(token)
|
||||||
|
return " ".join(output)
|
||||||
|
|
||||||
|
|
||||||
|
def clean_title(value):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = unicodedata.normalize("NFKC", str(value)).strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
suffix = Path(text).suffix.lower()
|
||||||
|
if suffix in VIDEO_EXTENSIONS:
|
||||||
|
text = Path(text).stem
|
||||||
|
text = re.sub(r"[._]+", " ", text)
|
||||||
|
text = re.sub(r"\s*-\s*", " ", text)
|
||||||
|
text = remove_known_prefixes(text)
|
||||||
|
text = remove_trailing_random_id(text)
|
||||||
|
text = remove_noise_tokens(text)
|
||||||
|
text = re.sub(r"\[[^\]]+\]", " ", text)
|
||||||
|
text = re.sub(r"\{[^}]+\}", " ", text)
|
||||||
|
text = re.sub(r"\s+", " ", text).strip(" -_.")
|
||||||
|
return smart_title_case(text) if text else None
|
||||||
|
|
||||||
|
|
||||||
|
MOVIE_FOLDER_PATTERN = re.compile(r"^(?P<title>.+?)\s*\((?P<year>\d{4})\)\s*$")
|
||||||
|
|
||||||
|
|
||||||
|
def clean_parent_movie_folder(path):
|
||||||
|
parent_name = Path(path).parent.name.strip()
|
||||||
|
match = MOVIE_FOLDER_PATTERN.match(parent_name)
|
||||||
|
if not match:
|
||||||
|
return None, None
|
||||||
|
return clean_title(match.group("title")), normalize_number(match.group("year"))
|
||||||
|
|
||||||
|
|
||||||
|
def list_media_files(root):
|
||||||
|
root = Path(root).resolve()
|
||||||
|
files = []
|
||||||
|
if not root.is_dir():
|
||||||
|
return files
|
||||||
|
for path in root.rglob("*"):
|
||||||
|
try:
|
||||||
|
if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS:
|
||||||
|
files.append(path)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
files.sort(key=lambda p: str(p).lower())
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
def extract_resolution(media_info):
|
||||||
|
for track in media_info.tracks:
|
||||||
|
if track.track_type != "Video":
|
||||||
|
continue
|
||||||
|
width = getattr(track, "width", None)
|
||||||
|
height = getattr(track, "height", None)
|
||||||
|
if width and height:
|
||||||
|
try:
|
||||||
|
return f"{int(width)}x{int(height)}"
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def extract_duration_seconds(media_info):
|
||||||
|
for wanted in ("General", "Video"):
|
||||||
|
for track in media_info.tracks:
|
||||||
|
if track.track_type != wanted:
|
||||||
|
continue
|
||||||
|
duration = getattr(track, "duration", None)
|
||||||
|
if duration is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
duration_ms = float(duration)
|
||||||
|
if duration_ms >= 0:
|
||||||
|
return duration_ms / 1000.0
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def is_short_media(duration_seconds, minimum_duration=None):
|
||||||
|
if minimum_duration is None:
|
||||||
|
minimum_duration = MIN_MEDIA_DURATION
|
||||||
|
if duration_seconds is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return float(duration_seconds) < float(minimum_duration)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_media_file(path):
|
||||||
|
path = Path(path).resolve()
|
||||||
|
guessed = guessit(path.name)
|
||||||
|
media_info = MediaInfo.parse(str(path))
|
||||||
|
|
||||||
|
resolution = extract_resolution(media_info)
|
||||||
|
duration_seconds = extract_duration_seconds(media_info)
|
||||||
|
short_media = is_short_media(duration_seconds)
|
||||||
|
|
||||||
|
guessed_type = guessed.get("type")
|
||||||
|
season = normalize_number(guessed.get("season"))
|
||||||
|
episode = normalize_number(guessed.get("episode"))
|
||||||
|
guessed_year = normalize_number(guessed.get("year"))
|
||||||
|
guessed_title = clean_title(guessed.get("title"))
|
||||||
|
episode_title = clean_title(guessed.get("episode_title"))
|
||||||
|
filename_title = clean_title(path.stem)
|
||||||
|
parent_title, parent_year = clean_parent_movie_folder(path)
|
||||||
|
|
||||||
|
media_type = "episode" if guessed_type == "episode" or season is not None or episode is not None else "movie"
|
||||||
|
series_title = guessed_title if media_type == "episode" else None
|
||||||
|
|
||||||
|
if media_type == "movie":
|
||||||
|
title = parent_title or guessed_title or filename_title or path.stem
|
||||||
|
year = parent_year or guessed_year
|
||||||
|
else:
|
||||||
|
title = series_title or guessed_title or filename_title or path.stem
|
||||||
|
year = guessed_year
|
||||||
|
|
||||||
|
return {
|
||||||
|
"original_path": str(path),
|
||||||
|
"type": media_type,
|
||||||
|
"title": title,
|
||||||
|
"series_title": series_title,
|
||||||
|
"episode_title": episode_title,
|
||||||
|
"season": season,
|
||||||
|
"episode": episode,
|
||||||
|
"year": year,
|
||||||
|
"resolution": resolution,
|
||||||
|
"duration_seconds": duration_seconds,
|
||||||
|
"is_short_media": short_media,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_full_mediainfo(path):
|
||||||
|
path = Path(path).resolve()
|
||||||
|
if not path.is_file():
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
media_info = MediaInfo.parse(str(path))
|
||||||
|
guessed = guessit(path.name)
|
||||||
|
normalized = inspect_media_file(path)
|
||||||
|
try:
|
||||||
|
media_info_data = media_info.to_data()
|
||||||
|
except Exception:
|
||||||
|
media_info_data = {"tracks": [track.to_data() for track in media_info.tracks]}
|
||||||
|
return {
|
||||||
|
"file": path.name,
|
||||||
|
"guessit": dict(guessed),
|
||||||
|
"normalized": normalized,
|
||||||
|
"mediainfo": media_info_data,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def scan_media(root):
|
||||||
|
results = []
|
||||||
|
for path in list_media_files(root):
|
||||||
|
try:
|
||||||
|
item = inspect_media_file(path)
|
||||||
|
if item.get("is_short_media"):
|
||||||
|
duration = item.get("duration_seconds") or 0
|
||||||
|
print(f"[MEDIAINFO] Skipping short media ({duration:.1f}s): {path}")
|
||||||
|
continue
|
||||||
|
results.append(item)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[MEDIAINFO] {path}: {exc}")
|
||||||
|
return results
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import socket
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
load_dotenv(BASE_DIR / "config.env")
|
||||||
|
DB_PATH = Path(
|
||||||
|
os.getenv("DB_PATH", str(BASE_DIR / "media_library.db"))
|
||||||
|
).expanduser().resolve()
|
||||||
|
|
||||||
|
POLL_SECONDS = max(
|
||||||
|
0.5,
|
||||||
|
float(os.getenv("MUSIC_IMPORT_JOB_POLL_SECONDS", "1")),
|
||||||
|
)
|
||||||
|
|
||||||
|
RESOLVER_WAIT_SECONDS = max(
|
||||||
|
1.0,
|
||||||
|
float(os.getenv("MUSIC_IMPORT_RESOLVER_WAIT_SECONDS", "2")),
|
||||||
|
)
|
||||||
|
|
||||||
|
_RESOLVER_URL = (
|
||||||
|
os.getenv("KRONIC_MUSIC_API_URL")
|
||||||
|
or os.getenv("KRONIC_RESOLVER_URL")
|
||||||
|
or "http://127.0.0.1:3030"
|
||||||
|
).rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def _resolver_address():
|
||||||
|
parsed = urlparse(_RESOLVER_URL)
|
||||||
|
host = parsed.hostname or "127.0.0.1"
|
||||||
|
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||||
|
return host, port
|
||||||
|
|
||||||
|
|
||||||
|
def _resolver_ready():
|
||||||
|
host, port = _resolver_address()
|
||||||
|
try:
|
||||||
|
with socket.create_connection((host, port), timeout=1.0):
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _resolver_unavailable_error(error):
|
||||||
|
text = str(error or "").lower()
|
||||||
|
needles = (
|
||||||
|
"connection refused",
|
||||||
|
"resolver unavailable",
|
||||||
|
"urlopen error",
|
||||||
|
"failed to establish a new connection",
|
||||||
|
"connection reset",
|
||||||
|
"connection aborted",
|
||||||
|
"timed out",
|
||||||
|
)
|
||||||
|
return any(needle in text for needle in needles)
|
||||||
|
|
||||||
|
_THREAD = None
|
||||||
|
_STOP = threading.Event()
|
||||||
|
|
||||||
|
|
||||||
|
def _db():
|
||||||
|
db = sqlite3.connect(DB_PATH, timeout=30)
|
||||||
|
db.row_factory = sqlite3.Row
|
||||||
|
return db
|
||||||
|
|
||||||
|
|
||||||
|
def init_music_import_jobs():
|
||||||
|
with _db() as db:
|
||||||
|
db.executescript("""
|
||||||
|
CREATE TABLE IF NOT EXISTS music_import_jobs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER,
|
||||||
|
query TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
message TEXT NOT NULL DEFAULT '',
|
||||||
|
resolved INTEGER NOT NULL DEFAULT 0,
|
||||||
|
inserted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
updated INTEGER NOT NULL DEFAULT 0,
|
||||||
|
repaired INTEGER NOT NULL DEFAULT 0,
|
||||||
|
errors INTEGER NOT NULL DEFAULT 0,
|
||||||
|
result_import_id INTEGER,
|
||||||
|
error TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
started_at INTEGER,
|
||||||
|
finished_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_music_import_jobs_status
|
||||||
|
ON music_import_jobs(status,created_at);
|
||||||
|
""")
|
||||||
|
# Imports are idempotent/upsert-based; interrupted work is safe to retry.
|
||||||
|
db.execute(
|
||||||
|
"""UPDATE music_import_jobs
|
||||||
|
SET status='queued',
|
||||||
|
message='requeued after service restart',
|
||||||
|
started_at=NULL
|
||||||
|
WHERE status='running'"""
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def enqueue_music_import(query: str, user_id: int | None = None):
|
||||||
|
query = str(query or "").strip()
|
||||||
|
if not query:
|
||||||
|
raise ValueError("Spotify URL or music query is required")
|
||||||
|
|
||||||
|
now = int(time.time())
|
||||||
|
with _db() as db:
|
||||||
|
existing = db.execute(
|
||||||
|
"""SELECT * FROM music_import_jobs
|
||||||
|
WHERE query=? AND status IN ('queued','running')
|
||||||
|
ORDER BY id DESC LIMIT 1""",
|
||||||
|
(query,),
|
||||||
|
).fetchone()
|
||||||
|
if existing:
|
||||||
|
return dict(existing)
|
||||||
|
|
||||||
|
cur = db.execute(
|
||||||
|
"""INSERT INTO music_import_jobs(
|
||||||
|
user_id,query,status,message,created_at
|
||||||
|
) VALUES(?,?,'queued','queued',?)""",
|
||||||
|
(user_id, query, now),
|
||||||
|
)
|
||||||
|
job_id = int(cur.lastrowid)
|
||||||
|
db.commit()
|
||||||
|
return get_music_import_job(job_id)
|
||||||
|
|
||||||
|
|
||||||
|
def get_music_import_job(job_id: int):
|
||||||
|
with _db() as db:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT * FROM music_import_jobs WHERE id=?",
|
||||||
|
(int(job_id),),
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def list_music_import_jobs(limit=20):
|
||||||
|
limit = max(1, min(int(limit or 20), 100))
|
||||||
|
with _db() as db:
|
||||||
|
rows = db.execute(
|
||||||
|
"""SELECT * FROM music_import_jobs
|
||||||
|
ORDER BY
|
||||||
|
CASE status WHEN 'running' THEN 0 WHEN 'queued' THEN 1 ELSE 2 END,
|
||||||
|
id DESC
|
||||||
|
LIMIT ?""",
|
||||||
|
(limit,),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(row) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def clear_music_import_jobs():
|
||||||
|
with _db() as db:
|
||||||
|
cur = db.execute(
|
||||||
|
"""DELETE FROM music_import_jobs
|
||||||
|
WHERE status IN ('complete','failed')"""
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return int(cur.rowcount or 0)
|
||||||
|
|
||||||
|
|
||||||
|
def _claim():
|
||||||
|
with _db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
row = db.execute(
|
||||||
|
"""SELECT * FROM music_import_jobs
|
||||||
|
WHERE status='queued'
|
||||||
|
ORDER BY id LIMIT 1"""
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
db.commit()
|
||||||
|
return None
|
||||||
|
|
||||||
|
cur = db.execute(
|
||||||
|
"""UPDATE music_import_jobs
|
||||||
|
SET status='running',
|
||||||
|
message='resolving Spotify metadata and YouTube matches…',
|
||||||
|
started_at=?,
|
||||||
|
error=''
|
||||||
|
WHERE id=? AND status='queued'""",
|
||||||
|
(int(time.time()), int(row["id"])),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
if cur.rowcount != 1:
|
||||||
|
return None
|
||||||
|
return get_music_import_job(int(row["id"]))
|
||||||
|
|
||||||
|
|
||||||
|
def _update(job_id, **values):
|
||||||
|
if not values:
|
||||||
|
return
|
||||||
|
sets = []
|
||||||
|
args = []
|
||||||
|
for key, value in values.items():
|
||||||
|
sets.append(f"{key}=?")
|
||||||
|
args.append(value)
|
||||||
|
args.append(int(job_id))
|
||||||
|
with _db() as db:
|
||||||
|
db.execute(
|
||||||
|
f"UPDATE music_import_jobs SET {', '.join(sets)} WHERE id=?",
|
||||||
|
args,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _run(job):
|
||||||
|
from music import import_music, repair_spotify_import_metadata
|
||||||
|
|
||||||
|
job_id = int(job["id"])
|
||||||
|
try:
|
||||||
|
result = import_music(
|
||||||
|
job["query"],
|
||||||
|
user_id=job.get("user_id"),
|
||||||
|
)
|
||||||
|
_update(
|
||||||
|
job_id,
|
||||||
|
message="repairing Spotify artwork and track metadata…",
|
||||||
|
resolved=int(result.get("resolved") or 0),
|
||||||
|
inserted=int(result.get("inserted") or 0),
|
||||||
|
updated=int(result.get("updated") or 0),
|
||||||
|
errors=len(result.get("errors") or []),
|
||||||
|
result_import_id=result.get("import_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
repair = repair_spotify_import_metadata(
|
||||||
|
int(result["import_id"])
|
||||||
|
)
|
||||||
|
|
||||||
|
_update(
|
||||||
|
job_id,
|
||||||
|
status="complete",
|
||||||
|
message="complete",
|
||||||
|
repaired=int(repair.get("repaired") or 0),
|
||||||
|
errors=(
|
||||||
|
len(result.get("errors") or [])
|
||||||
|
+ len(repair.get("errors") or [])
|
||||||
|
),
|
||||||
|
finished_at=int(time.time()),
|
||||||
|
)
|
||||||
|
except Exception as error:
|
||||||
|
if _resolver_unavailable_error(error):
|
||||||
|
_update(
|
||||||
|
job_id,
|
||||||
|
status="queued",
|
||||||
|
message="waiting for Kronic resolver…",
|
||||||
|
error="",
|
||||||
|
started_at=None,
|
||||||
|
finished_at=None,
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"[MUSIC] import waiting for resolver",
|
||||||
|
{"job_id": job_id, "error": str(error)},
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
_update(
|
||||||
|
job_id,
|
||||||
|
status="failed",
|
||||||
|
message="failed",
|
||||||
|
error=str(error)[:4000],
|
||||||
|
finished_at=int(time.time()),
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"[MUSIC] background import failed",
|
||||||
|
{"job_id": job_id, "error": str(error)},
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _loop():
|
||||||
|
while not _STOP.is_set():
|
||||||
|
# stream_server intentionally starts the embedded resolver in a
|
||||||
|
# background thread. Do not claim Spotify jobs until its TCP listener
|
||||||
|
# is actually available, otherwise a queued import can fail during
|
||||||
|
# the first seconds of service startup.
|
||||||
|
if not _resolver_ready():
|
||||||
|
_STOP.wait(RESOLVER_WAIT_SECONDS)
|
||||||
|
continue
|
||||||
|
|
||||||
|
job = _claim()
|
||||||
|
if not job:
|
||||||
|
_STOP.wait(POLL_SECONDS)
|
||||||
|
continue
|
||||||
|
|
||||||
|
_run(job)
|
||||||
|
|
||||||
|
# A transient resolver outage can requeue the job. Avoid a tight loop
|
||||||
|
# while the resolver is still coming back.
|
||||||
|
if not _resolver_ready():
|
||||||
|
_STOP.wait(RESOLVER_WAIT_SECONDS)
|
||||||
|
|
||||||
|
|
||||||
|
def start_music_import_worker():
|
||||||
|
global _THREAD
|
||||||
|
if _THREAD and _THREAD.is_alive():
|
||||||
|
return
|
||||||
|
_STOP.clear()
|
||||||
|
_THREAD = threading.Thread(
|
||||||
|
target=_loop,
|
||||||
|
daemon=True,
|
||||||
|
name="spotify-import-worker",
|
||||||
|
)
|
||||||
|
_THREAD.start()
|
||||||
@@ -0,0 +1,841 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
load_dotenv(BASE_DIR / "config.env")
|
||||||
|
|
||||||
|
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg")
|
||||||
|
FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe")
|
||||||
|
|
||||||
|
BROWSER_CACHE_DIR = Path(
|
||||||
|
os.getenv(
|
||||||
|
"BROWSER_CACHE_DIR",
|
||||||
|
str(BASE_DIR / "browser-cache"),
|
||||||
|
)
|
||||||
|
).expanduser().resolve()
|
||||||
|
|
||||||
|
BROWSER_CACHE_MAX_GB = max(
|
||||||
|
0.0,
|
||||||
|
float(os.getenv("BROWSER_CACHE_MAX_GB", "100")),
|
||||||
|
)
|
||||||
|
|
||||||
|
BROWSER_AUDIO_CHANNELS = max(
|
||||||
|
1,
|
||||||
|
min(
|
||||||
|
6,
|
||||||
|
int(os.getenv("BROWSER_AUDIO_CHANNELS", "2")),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
BROWSER_AUDIO_BITRATE = os.getenv(
|
||||||
|
"BROWSER_AUDIO_BITRATE",
|
||||||
|
"192k",
|
||||||
|
)
|
||||||
|
|
||||||
|
BROWSER_X264_PRESET = os.getenv(
|
||||||
|
"BROWSER_X264_PRESET",
|
||||||
|
"veryfast",
|
||||||
|
)
|
||||||
|
|
||||||
|
BROWSER_X264_CRF = str(
|
||||||
|
int(os.getenv("BROWSER_X264_CRF", "21"))
|
||||||
|
)
|
||||||
|
|
||||||
|
QUALITY_BITRATES = {
|
||||||
|
720: os.getenv("QUALITY_720P_BITRATE", "3500k"),
|
||||||
|
480: os.getenv("QUALITY_480P_BITRATE", "1800k"),
|
||||||
|
360: os.getenv("QUALITY_360P_BITRATE", "900k"),
|
||||||
|
}
|
||||||
|
|
||||||
|
_probe_lock = threading.Lock()
|
||||||
|
_probe_cache: dict[str, tuple[tuple[int, int], dict[str, Any]]] = {}
|
||||||
|
|
||||||
|
_cache_locks_guard = threading.Lock()
|
||||||
|
_cache_locks: dict[str, threading.Lock] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _fingerprint(path: Path) -> tuple[int, int]:
|
||||||
|
stat = path.stat()
|
||||||
|
return (
|
||||||
|
int(stat.st_size),
|
||||||
|
int(stat.st_mtime_ns),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_lock(key: str) -> threading.Lock:
|
||||||
|
with _cache_locks_guard:
|
||||||
|
lock = _cache_locks.get(key)
|
||||||
|
if lock is None:
|
||||||
|
lock = threading.Lock()
|
||||||
|
_cache_locks[key] = lock
|
||||||
|
return lock
|
||||||
|
|
||||||
|
|
||||||
|
def probe_media(path: str | Path) -> dict[str, Any]:
|
||||||
|
path = Path(path).resolve()
|
||||||
|
fingerprint = _fingerprint(path)
|
||||||
|
cache_key = str(path)
|
||||||
|
|
||||||
|
with _probe_lock:
|
||||||
|
cached = _probe_cache.get(cache_key)
|
||||||
|
if cached and cached[0] == fingerprint:
|
||||||
|
return dict(cached[1])
|
||||||
|
|
||||||
|
command = [
|
||||||
|
FFPROBE_BIN, "-v", "error",
|
||||||
|
"-show_streams", "-show_format", "-of", "json", str(path),
|
||||||
|
]
|
||||||
|
result = subprocess.run(
|
||||||
|
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||||
|
text=True, timeout=30, check=True,
|
||||||
|
)
|
||||||
|
raw = json.loads(result.stdout or "{}")
|
||||||
|
streams = raw.get("streams") or []
|
||||||
|
videos = [x for x in streams if x.get("codec_type") == "video"]
|
||||||
|
audios = [x for x in streams if x.get("codec_type") == "audio"]
|
||||||
|
video = videos[0] if videos else {}
|
||||||
|
audio = audios[0] if audios else {}
|
||||||
|
format_data = raw.get("format") or {}
|
||||||
|
|
||||||
|
audio_tracks = []
|
||||||
|
for ordinal, stream in enumerate(audios):
|
||||||
|
tags = stream.get("tags") or {}
|
||||||
|
disposition = stream.get("disposition") or {}
|
||||||
|
channels = _safe_int(stream.get("channels"))
|
||||||
|
layout = str(stream.get("channel_layout") or "").strip()
|
||||||
|
language = str(tags.get("language") or "").strip().lower()
|
||||||
|
title = str(tags.get("title") or "").strip()
|
||||||
|
codec = str(stream.get("codec_name") or "").lower()
|
||||||
|
audio_tracks.append({
|
||||||
|
"ordinal": ordinal,
|
||||||
|
"stream_index": _safe_int(stream.get("index")),
|
||||||
|
"codec": codec,
|
||||||
|
"codec_long_name": str(stream.get("codec_long_name") or ""),
|
||||||
|
"language": language,
|
||||||
|
"title": title,
|
||||||
|
"channels": channels,
|
||||||
|
"channel_layout": layout,
|
||||||
|
"bit_rate": _safe_int(stream.get("bit_rate")),
|
||||||
|
"sample_rate": _safe_int(stream.get("sample_rate")),
|
||||||
|
"default": bool(disposition.get("default")),
|
||||||
|
})
|
||||||
|
|
||||||
|
info = {
|
||||||
|
"path": str(path),
|
||||||
|
"suffix": path.suffix.lower(),
|
||||||
|
"size": fingerprint[0],
|
||||||
|
"mtime_ns": fingerprint[1],
|
||||||
|
"container": str(format_data.get("format_name") or "").lower(),
|
||||||
|
"duration": _safe_float(format_data.get("duration")),
|
||||||
|
"video_codec": str(video.get("codec_name") or "").lower(),
|
||||||
|
"video_profile": str(video.get("profile") or ""),
|
||||||
|
"pixel_format": str(video.get("pix_fmt") or "").lower(),
|
||||||
|
"width": _safe_int(video.get("width")),
|
||||||
|
"height": _safe_int(video.get("height")),
|
||||||
|
"video_bitrate": _safe_int(video.get("bit_rate")),
|
||||||
|
"fps": _frame_rate(video.get("avg_frame_rate") or video.get("r_frame_rate")),
|
||||||
|
"audio_codec": str(audio.get("codec_name") or "").lower(),
|
||||||
|
"audio_channels": _safe_int(audio.get("channels")),
|
||||||
|
"audio_sample_rate": _safe_int(audio.get("sample_rate")),
|
||||||
|
"audio_tracks": audio_tracks,
|
||||||
|
}
|
||||||
|
with _probe_lock:
|
||||||
|
_probe_cache[cache_key] = (fingerprint, dict(info))
|
||||||
|
return info
|
||||||
|
|
||||||
|
|
||||||
|
def quality_options(info: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
height = int(info.get("height") or 0)
|
||||||
|
native = f"{height}p" if height else "Original"
|
||||||
|
options = [{"value": "original", "label": f"Original {native}" if height else "Original", "height": height or None}]
|
||||||
|
for target in (720, 480, 360):
|
||||||
|
if height > target:
|
||||||
|
options.append({"value": str(target), "label": f"{target}p", "height": target, "bitrate": QUALITY_BITRATES[target]})
|
||||||
|
return options
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_float(value: Any) -> float | None:
|
||||||
|
try:
|
||||||
|
return float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_int(value: Any) -> int | None:
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _frame_rate(value: Any) -> float | None:
|
||||||
|
text = str(value or "").strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if "/" in text:
|
||||||
|
numerator, denominator = text.split("/", 1)
|
||||||
|
try:
|
||||||
|
denominator_value = float(denominator)
|
||||||
|
if denominator_value == 0:
|
||||||
|
return None
|
||||||
|
return float(numerator) / denominator_value
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
return _safe_float(text)
|
||||||
|
|
||||||
|
|
||||||
|
def _truthy(value: Any) -> bool:
|
||||||
|
return str(value or "").strip().lower() in {
|
||||||
|
"1",
|
||||||
|
"true",
|
||||||
|
"yes",
|
||||||
|
"on",
|
||||||
|
"probably",
|
||||||
|
"maybe",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _browser_name(value: Any) -> str:
|
||||||
|
value = str(value or "").strip().lower()
|
||||||
|
if value in {
|
||||||
|
"firefox",
|
||||||
|
"chrome",
|
||||||
|
"edge",
|
||||||
|
"safari",
|
||||||
|
"unknown",
|
||||||
|
}:
|
||||||
|
return value
|
||||||
|
return "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def plan_playback(
|
||||||
|
path: str | Path,
|
||||||
|
*,
|
||||||
|
capabilities: dict[str, Any] | None = None,
|
||||||
|
browser: str = "unknown",
|
||||||
|
force_compat: bool = False,
|
||||||
|
quality: str = "original",
|
||||||
|
audio_stream_index: int | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
info = probe_media(path)
|
||||||
|
capabilities = capabilities or {}
|
||||||
|
browser = _browser_name(browser)
|
||||||
|
quality = str(quality or "original").lower().strip()
|
||||||
|
requested_height = None if quality == "original" else _safe_int(quality)
|
||||||
|
if requested_height not in {None, 720, 480, 360}:
|
||||||
|
requested_height = None
|
||||||
|
quality = "original"
|
||||||
|
|
||||||
|
tracks = info.get("audio_tracks") or []
|
||||||
|
selected_audio = None
|
||||||
|
if audio_stream_index is not None:
|
||||||
|
selected_audio = next((t for t in tracks if t.get("stream_index") == int(audio_stream_index)), None)
|
||||||
|
if selected_audio is None and tracks:
|
||||||
|
selected_audio = next((t for t in tracks if t.get("default")), tracks[0])
|
||||||
|
selected_audio_index = selected_audio.get("stream_index") if selected_audio else None
|
||||||
|
selected_audio_codec = (selected_audio or {}).get("codec") or info.get("audio_codec") or ""
|
||||||
|
|
||||||
|
def finalize(plan: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
plan["selected_audio_stream_index"] = selected_audio_index
|
||||||
|
plan["selected_audio"] = selected_audio
|
||||||
|
plan["selected_quality"] = quality
|
||||||
|
plan.setdefault("quality_options", quality_options(info))
|
||||||
|
return plan
|
||||||
|
|
||||||
|
suffix = info["suffix"]
|
||||||
|
vcodec = info["video_codec"]
|
||||||
|
acodec = selected_audio_codec
|
||||||
|
|
||||||
|
supports_h264 = _truthy(
|
||||||
|
capabilities.get("h264", True)
|
||||||
|
)
|
||||||
|
supports_av1 = _truthy(
|
||||||
|
capabilities.get("av1", False)
|
||||||
|
)
|
||||||
|
supports_hevc = _truthy(
|
||||||
|
capabilities.get("hevc", False)
|
||||||
|
)
|
||||||
|
supports_webm_vp9 = _truthy(
|
||||||
|
capabilities.get("webm_vp9", False)
|
||||||
|
)
|
||||||
|
supports_webm_av1 = _truthy(
|
||||||
|
capabilities.get("webm_av1", False)
|
||||||
|
)
|
||||||
|
|
||||||
|
is_mp4 = suffix in {
|
||||||
|
".mp4",
|
||||||
|
".m4v",
|
||||||
|
".mov",
|
||||||
|
}
|
||||||
|
is_webm = suffix == ".webm"
|
||||||
|
|
||||||
|
if requested_height is not None and int(info.get("height") or 0) > requested_height:
|
||||||
|
plan = _plan(
|
||||||
|
"transcode_stream", info, browser,
|
||||||
|
f"Manual {requested_height}p lower-bandwidth transcode selected.",
|
||||||
|
seek_mode="server",
|
||||||
|
)
|
||||||
|
plan["requested_height"] = requested_height
|
||||||
|
plan["video_bitrate"] = QUALITY_BITRATES[requested_height]
|
||||||
|
return finalize(plan)
|
||||||
|
|
||||||
|
# A retry requested by the frontend must use the most conservative path.
|
||||||
|
# Do not select remux_cache again or the retry simply repeats the same
|
||||||
|
# startup failure.
|
||||||
|
if force_compat:
|
||||||
|
return finalize(_plan(
|
||||||
|
"transcode_stream",
|
||||||
|
info,
|
||||||
|
browser,
|
||||||
|
"Forced compatibility retry: H.264/AAC live transcode.",
|
||||||
|
seek_mode="server",
|
||||||
|
))
|
||||||
|
|
||||||
|
video_direct = False
|
||||||
|
|
||||||
|
if vcodec in {
|
||||||
|
"h264",
|
||||||
|
"avc1",
|
||||||
|
}:
|
||||||
|
video_direct = supports_h264
|
||||||
|
elif vcodec == "av1":
|
||||||
|
video_direct = supports_av1
|
||||||
|
elif vcodec in {
|
||||||
|
"hevc",
|
||||||
|
"h265",
|
||||||
|
}:
|
||||||
|
video_direct = supports_hevc
|
||||||
|
elif vcodec in {
|
||||||
|
"vp9",
|
||||||
|
"vp09",
|
||||||
|
}:
|
||||||
|
video_direct = supports_webm_vp9
|
||||||
|
|
||||||
|
if vcodec == "av1" and is_webm:
|
||||||
|
video_direct = supports_webm_av1
|
||||||
|
|
||||||
|
audio_mp4_direct = acodec in {
|
||||||
|
"",
|
||||||
|
"aac",
|
||||||
|
"mp3",
|
||||||
|
}
|
||||||
|
|
||||||
|
audio_webm_direct = acodec in {
|
||||||
|
"",
|
||||||
|
"opus",
|
||||||
|
"vorbis",
|
||||||
|
}
|
||||||
|
|
||||||
|
default_track = next((t for t in tracks if t.get("default")), tracks[0] if tracks else None)
|
||||||
|
default_audio_index = default_track.get("stream_index") if default_track else None
|
||||||
|
alternate_audio_selected = (
|
||||||
|
audio_stream_index is not None
|
||||||
|
and selected_audio_index is not None
|
||||||
|
and selected_audio_index != default_audio_index
|
||||||
|
)
|
||||||
|
|
||||||
|
# The most stable path is an ordinary seekable source that the browser
|
||||||
|
# already supports. Never run FFmpeg simply because it exists.
|
||||||
|
if (
|
||||||
|
is_mp4
|
||||||
|
and video_direct
|
||||||
|
and audio_mp4_direct
|
||||||
|
and not alternate_audio_selected
|
||||||
|
):
|
||||||
|
return finalize(_plan(
|
||||||
|
"direct",
|
||||||
|
info,
|
||||||
|
browser,
|
||||||
|
"Source is already browser-compatible MP4.",
|
||||||
|
seek_mode="client",
|
||||||
|
))
|
||||||
|
|
||||||
|
if (
|
||||||
|
is_webm
|
||||||
|
and video_direct
|
||||||
|
and audio_webm_direct
|
||||||
|
and not alternate_audio_selected
|
||||||
|
):
|
||||||
|
return finalize(_plan(
|
||||||
|
"direct",
|
||||||
|
info,
|
||||||
|
browser,
|
||||||
|
"Source is already browser-compatible WebM.",
|
||||||
|
seek_mode="client",
|
||||||
|
))
|
||||||
|
|
||||||
|
# H.264 is already the desired compatibility video codec. Repackage it
|
||||||
|
# once into a normal +faststart MP4 instead of feeding Firefox an endless
|
||||||
|
# fragmented MP4 pipe on every playback.
|
||||||
|
if vcodec in {
|
||||||
|
"h264",
|
||||||
|
"avc1",
|
||||||
|
} and supports_h264:
|
||||||
|
return finalize(_plan(
|
||||||
|
"remux_stream",
|
||||||
|
info,
|
||||||
|
browser,
|
||||||
|
(
|
||||||
|
"H.264 video can be copied immediately while the selected "
|
||||||
|
"audio track is normalized for browser playback."
|
||||||
|
),
|
||||||
|
seek_mode="server",
|
||||||
|
))
|
||||||
|
|
||||||
|
# Unsupported video codecs must be transcoded while playing. Waiting for
|
||||||
|
# a full movie-length H.264 cache before first playback would be a poor UX.
|
||||||
|
return finalize(_plan(
|
||||||
|
"transcode_stream",
|
||||||
|
info,
|
||||||
|
browser,
|
||||||
|
(
|
||||||
|
f"{vcodec or 'unknown'} video is not directly usable by this "
|
||||||
|
"browser; stream a normalized H.264/AAC fragmented MP4."
|
||||||
|
),
|
||||||
|
seek_mode="server",
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def _plan(
|
||||||
|
mode: str,
|
||||||
|
info: dict[str, Any],
|
||||||
|
browser: str,
|
||||||
|
reason: str,
|
||||||
|
*,
|
||||||
|
seek_mode: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"mode": mode,
|
||||||
|
"seek_mode": seek_mode,
|
||||||
|
"browser": browser,
|
||||||
|
"reason": reason,
|
||||||
|
"source": info,
|
||||||
|
"quality_options": quality_options(info),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cache_path_for(
|
||||||
|
source_path: str | Path,
|
||||||
|
*,
|
||||||
|
media_id: int | str,
|
||||||
|
) -> Path:
|
||||||
|
source_path = Path(source_path).resolve()
|
||||||
|
size, mtime_ns = _fingerprint(source_path)
|
||||||
|
|
||||||
|
digest = hashlib.sha1(
|
||||||
|
(
|
||||||
|
f"{source_path}\0"
|
||||||
|
f"{size}\0"
|
||||||
|
f"{mtime_ns}\0"
|
||||||
|
"compat-mp4-v2"
|
||||||
|
).encode("utf-8")
|
||||||
|
).hexdigest()[:20]
|
||||||
|
|
||||||
|
return (
|
||||||
|
BROWSER_CACHE_DIR
|
||||||
|
/ f"{media_id}-{digest}.mp4"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def compatibility_cache_status(
|
||||||
|
source_path: str | Path,
|
||||||
|
*,
|
||||||
|
media_id: int | str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
path = cache_path_for(
|
||||||
|
source_path,
|
||||||
|
media_id=media_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"cached": path.is_file()
|
||||||
|
and path.stat().st_size > 0,
|
||||||
|
"path": str(path),
|
||||||
|
"size_bytes": (
|
||||||
|
path.stat().st_size
|
||||||
|
if path.is_file()
|
||||||
|
else 0
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_remux_cache(
|
||||||
|
source_path: str | Path,
|
||||||
|
*,
|
||||||
|
media_id: int | str,
|
||||||
|
) -> Path:
|
||||||
|
source_path = Path(source_path).resolve()
|
||||||
|
BROWSER_CACHE_DIR.mkdir(
|
||||||
|
parents=True,
|
||||||
|
exist_ok=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
destination = cache_path_for(
|
||||||
|
source_path,
|
||||||
|
media_id=media_id,
|
||||||
|
)
|
||||||
|
lock = _cache_lock(str(destination))
|
||||||
|
|
||||||
|
with lock:
|
||||||
|
if (
|
||||||
|
destination.is_file()
|
||||||
|
and destination.stat().st_size > 0
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
os.utime(destination, None)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return destination
|
||||||
|
|
||||||
|
info = probe_media(source_path)
|
||||||
|
temporary = destination.with_suffix(
|
||||||
|
".part.mp4"
|
||||||
|
)
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
command = [
|
||||||
|
FFMPEG_BIN,
|
||||||
|
"-nostdin",
|
||||||
|
"-hide_banner",
|
||||||
|
"-loglevel",
|
||||||
|
"warning",
|
||||||
|
"-fflags",
|
||||||
|
"+genpts+discardcorrupt",
|
||||||
|
"-i",
|
||||||
|
str(source_path),
|
||||||
|
"-map",
|
||||||
|
"0:v:0",
|
||||||
|
"-map",
|
||||||
|
"0:a:0?",
|
||||||
|
"-sn",
|
||||||
|
"-dn",
|
||||||
|
"-c:v",
|
||||||
|
"copy",
|
||||||
|
]
|
||||||
|
|
||||||
|
if info.get("audio_codec") in {
|
||||||
|
"",
|
||||||
|
"aac",
|
||||||
|
"mp3",
|
||||||
|
}:
|
||||||
|
command.extend(
|
||||||
|
[
|
||||||
|
"-c:a",
|
||||||
|
"copy",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
command.extend(
|
||||||
|
[
|
||||||
|
"-c:a",
|
||||||
|
"aac",
|
||||||
|
"-b:a",
|
||||||
|
BROWSER_AUDIO_BITRATE,
|
||||||
|
"-ar",
|
||||||
|
"48000",
|
||||||
|
"-ac",
|
||||||
|
str(BROWSER_AUDIO_CHANNELS),
|
||||||
|
"-af",
|
||||||
|
"aresample=async=1:first_pts=0",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
command.extend(
|
||||||
|
[
|
||||||
|
"-avoid_negative_ts",
|
||||||
|
"make_zero",
|
||||||
|
"-map_metadata",
|
||||||
|
"-1",
|
||||||
|
"-map_chapters",
|
||||||
|
"-1",
|
||||||
|
"-movflags",
|
||||||
|
"+faststart",
|
||||||
|
"-f",
|
||||||
|
"mp4",
|
||||||
|
"-y",
|
||||||
|
str(temporary),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (
|
||||||
|
result.returncode != 0
|
||||||
|
or not temporary.is_file()
|
||||||
|
or temporary.stat().st_size <= 0
|
||||||
|
):
|
||||||
|
temporary.unlink(
|
||||||
|
missing_ok=True
|
||||||
|
)
|
||||||
|
raise RuntimeError(
|
||||||
|
"FFmpeg compatibility remux failed: "
|
||||||
|
+ (
|
||||||
|
result.stderr[-4000:]
|
||||||
|
if result.stderr
|
||||||
|
else f"return code {result.returncode}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
temporary.replace(destination)
|
||||||
|
prune_browser_cache()
|
||||||
|
|
||||||
|
return destination
|
||||||
|
|
||||||
|
|
||||||
|
def remux_stream_command(
|
||||||
|
source_path: str | Path,
|
||||||
|
*,
|
||||||
|
start_seconds: float = 0.0,
|
||||||
|
audio_stream_index: int | None = None,
|
||||||
|
) -> list[str]:
|
||||||
|
"""
|
||||||
|
Start immediately for H.264 sources that only need container/audio cleanup.
|
||||||
|
|
||||||
|
Video is copied. Audio is normalized to AAC. Output is fragmented MP4 so
|
||||||
|
the browser can begin playback before the entire movie has been remuxed.
|
||||||
|
"""
|
||||||
|
source_path = Path(source_path).resolve()
|
||||||
|
|
||||||
|
command = [
|
||||||
|
FFMPEG_BIN,
|
||||||
|
"-nostdin",
|
||||||
|
"-hide_banner",
|
||||||
|
"-loglevel",
|
||||||
|
"warning",
|
||||||
|
"-fflags",
|
||||||
|
"+genpts+discardcorrupt",
|
||||||
|
]
|
||||||
|
|
||||||
|
if start_seconds > 0:
|
||||||
|
command.extend([
|
||||||
|
"-ss",
|
||||||
|
f"{start_seconds:.3f}",
|
||||||
|
])
|
||||||
|
|
||||||
|
command.extend([
|
||||||
|
"-i",
|
||||||
|
str(source_path),
|
||||||
|
"-map",
|
||||||
|
"0:v:0",
|
||||||
|
"-map",
|
||||||
|
(f"0:{audio_stream_index}?" if audio_stream_index is not None else "0:a:0?"),
|
||||||
|
"-sn",
|
||||||
|
"-dn",
|
||||||
|
"-c:v",
|
||||||
|
"copy",
|
||||||
|
"-c:a",
|
||||||
|
"aac",
|
||||||
|
"-b:a",
|
||||||
|
BROWSER_AUDIO_BITRATE,
|
||||||
|
"-ar",
|
||||||
|
"48000",
|
||||||
|
"-ac",
|
||||||
|
str(BROWSER_AUDIO_CHANNELS),
|
||||||
|
"-af",
|
||||||
|
"aresample=async=1:first_pts=0",
|
||||||
|
"-avoid_negative_ts",
|
||||||
|
"make_zero",
|
||||||
|
"-map_metadata",
|
||||||
|
"-1",
|
||||||
|
"-map_chapters",
|
||||||
|
"-1",
|
||||||
|
"-movflags",
|
||||||
|
(
|
||||||
|
"+frag_keyframe"
|
||||||
|
"+empty_moov"
|
||||||
|
"+default_base_moof"
|
||||||
|
"+omit_tfhd_offset"
|
||||||
|
),
|
||||||
|
"-frag_duration",
|
||||||
|
"2000000",
|
||||||
|
"-min_frag_duration",
|
||||||
|
"1000000",
|
||||||
|
"-video_track_timescale",
|
||||||
|
"90000",
|
||||||
|
"-max_interleave_delta",
|
||||||
|
"0",
|
||||||
|
"-flush_packets",
|
||||||
|
"1",
|
||||||
|
"-f",
|
||||||
|
"mp4",
|
||||||
|
"pipe:1",
|
||||||
|
])
|
||||||
|
|
||||||
|
return command
|
||||||
|
|
||||||
|
|
||||||
|
def transcode_stream_command(
|
||||||
|
source_path: str | Path,
|
||||||
|
*,
|
||||||
|
start_seconds: float = 0.0,
|
||||||
|
audio_stream_index: int | None = None,
|
||||||
|
target_height: int | None = None,
|
||||||
|
video_bitrate: str | None = None,
|
||||||
|
) -> list[str]:
|
||||||
|
source_path = Path(source_path).resolve()
|
||||||
|
|
||||||
|
command = [
|
||||||
|
FFMPEG_BIN,
|
||||||
|
"-nostdin",
|
||||||
|
"-hide_banner",
|
||||||
|
"-loglevel",
|
||||||
|
"warning",
|
||||||
|
"-fflags",
|
||||||
|
"+genpts+discardcorrupt",
|
||||||
|
]
|
||||||
|
|
||||||
|
if start_seconds > 0:
|
||||||
|
command.extend(
|
||||||
|
[
|
||||||
|
"-ss",
|
||||||
|
f"{start_seconds:.3f}",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
command.extend(
|
||||||
|
[
|
||||||
|
"-i",
|
||||||
|
str(source_path),
|
||||||
|
"-map",
|
||||||
|
"0:v:0",
|
||||||
|
"-map",
|
||||||
|
(f"0:{audio_stream_index}?" if audio_stream_index is not None else "0:a:0?"),
|
||||||
|
"-sn",
|
||||||
|
"-dn",
|
||||||
|
"-c:v",
|
||||||
|
"libx264",
|
||||||
|
"-preset",
|
||||||
|
BROWSER_X264_PRESET,
|
||||||
|
"-crf",
|
||||||
|
BROWSER_X264_CRF,
|
||||||
|
"-profile:v",
|
||||||
|
"high",
|
||||||
|
"-level:v",
|
||||||
|
"4.1",
|
||||||
|
"-pix_fmt",
|
||||||
|
"yuv420p",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
if target_height:
|
||||||
|
command.extend(["-vf", f"scale=-2:{int(target_height)}"])
|
||||||
|
if video_bitrate:
|
||||||
|
command.extend([
|
||||||
|
"-b:v", str(video_bitrate),
|
||||||
|
"-maxrate", str(video_bitrate),
|
||||||
|
"-bufsize", str(video_bitrate),
|
||||||
|
])
|
||||||
|
|
||||||
|
command.extend(
|
||||||
|
[
|
||||||
|
"-c:a",
|
||||||
|
"aac",
|
||||||
|
"-b:a",
|
||||||
|
BROWSER_AUDIO_BITRATE,
|
||||||
|
"-ar",
|
||||||
|
"48000",
|
||||||
|
"-ac",
|
||||||
|
str(BROWSER_AUDIO_CHANNELS),
|
||||||
|
"-af",
|
||||||
|
"aresample=async=1:first_pts=0",
|
||||||
|
"-avoid_negative_ts",
|
||||||
|
"make_zero",
|
||||||
|
"-map_metadata",
|
||||||
|
"-1",
|
||||||
|
"-map_chapters",
|
||||||
|
"-1",
|
||||||
|
"-movflags",
|
||||||
|
(
|
||||||
|
"+frag_keyframe"
|
||||||
|
"+empty_moov"
|
||||||
|
"+default_base_moof"
|
||||||
|
"+omit_tfhd_offset"
|
||||||
|
),
|
||||||
|
"-frag_duration",
|
||||||
|
"2000000",
|
||||||
|
"-min_frag_duration",
|
||||||
|
"1000000",
|
||||||
|
"-video_track_timescale",
|
||||||
|
"90000",
|
||||||
|
"-f",
|
||||||
|
"mp4",
|
||||||
|
"pipe:1",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
return command
|
||||||
|
|
||||||
|
|
||||||
|
def prune_browser_cache() -> None:
|
||||||
|
if (
|
||||||
|
BROWSER_CACHE_MAX_GB
|
||||||
|
<= 0
|
||||||
|
or not BROWSER_CACHE_DIR.is_dir()
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
maximum = int(
|
||||||
|
BROWSER_CACHE_MAX_GB
|
||||||
|
* 1024
|
||||||
|
* 1024
|
||||||
|
* 1024
|
||||||
|
)
|
||||||
|
|
||||||
|
files = [
|
||||||
|
path
|
||||||
|
for path in BROWSER_CACHE_DIR.glob("*.mp4")
|
||||||
|
if path.is_file()
|
||||||
|
]
|
||||||
|
|
||||||
|
entries = []
|
||||||
|
total = 0
|
||||||
|
|
||||||
|
for path in files:
|
||||||
|
try:
|
||||||
|
stat = path.stat()
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
total += stat.st_size
|
||||||
|
entries.append(
|
||||||
|
(
|
||||||
|
stat.st_mtime,
|
||||||
|
stat.st_size,
|
||||||
|
path,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if total <= maximum:
|
||||||
|
return
|
||||||
|
|
||||||
|
entries.sort(
|
||||||
|
key=lambda item: item[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
for _mtime, size, path in entries:
|
||||||
|
if total <= maximum:
|
||||||
|
break
|
||||||
|
|
||||||
|
try:
|
||||||
|
path.unlink()
|
||||||
|
total -= size
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import atexit
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.error import URLError
|
||||||
|
from urllib.request import urlopen
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
load_dotenv(BASE_DIR / "config.env")
|
||||||
|
|
||||||
|
KRONIC_DIR = Path(
|
||||||
|
os.getenv(
|
||||||
|
"KRONIC_DIR",
|
||||||
|
str(BASE_DIR / "kronic"),
|
||||||
|
)
|
||||||
|
).expanduser().resolve()
|
||||||
|
|
||||||
|
RESOLVER_HOST = os.getenv(
|
||||||
|
"KRONIC_RESOLVER_HOST",
|
||||||
|
"127.0.0.1",
|
||||||
|
).strip() or "127.0.0.1"
|
||||||
|
|
||||||
|
RESOLVER_PORT = int(
|
||||||
|
os.getenv(
|
||||||
|
"KRONIC_RESOLVER_PORT",
|
||||||
|
"3030",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
RESOLVER_START_TIMEOUT = float(
|
||||||
|
os.getenv(
|
||||||
|
"KRONIC_RESOLVER_START_TIMEOUT",
|
||||||
|
"30",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
RESOLVER_URL = (
|
||||||
|
f"http://{RESOLVER_HOST}:{RESOLVER_PORT}"
|
||||||
|
)
|
||||||
|
|
||||||
|
_PROCESS: subprocess.Popen | None = None
|
||||||
|
_LOCK = threading.Lock()
|
||||||
|
_OWNS_PROCESS = False
|
||||||
|
|
||||||
|
|
||||||
|
def _health_url() -> str:
|
||||||
|
return f"{RESOLVER_URL}/health"
|
||||||
|
|
||||||
|
|
||||||
|
def resolver_is_ready(
|
||||||
|
timeout: float = 1.0,
|
||||||
|
) -> bool:
|
||||||
|
try:
|
||||||
|
with urlopen(
|
||||||
|
_health_url(),
|
||||||
|
timeout=timeout,
|
||||||
|
) as response:
|
||||||
|
if response.status < 200 or response.status >= 300:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# The Kronic resolver currently returns JSON, but health only
|
||||||
|
# needs a successful HTTP response.
|
||||||
|
try:
|
||||||
|
json.loads(
|
||||||
|
response.read().decode(
|
||||||
|
"utf-8",
|
||||||
|
"replace",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _required_paths() -> list[Path]:
|
||||||
|
return [
|
||||||
|
KRONIC_DIR / "resolver" / "__init__.py",
|
||||||
|
KRONIC_DIR / "resolver" / "app.py",
|
||||||
|
KRONIC_DIR / "resolver" / "app_spotdl.py",
|
||||||
|
KRONIC_DIR / "resolver" / "spotdl_router.py",
|
||||||
|
KRONIC_DIR / "resolver" / "models.py",
|
||||||
|
KRONIC_DIR / "resolver" / "net.py",
|
||||||
|
KRONIC_DIR / "resolver" / "ytdlp_service.py",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_resolver_tree() -> None:
|
||||||
|
missing = [
|
||||||
|
path
|
||||||
|
for path in _required_paths()
|
||||||
|
if not path.is_file()
|
||||||
|
]
|
||||||
|
|
||||||
|
if missing:
|
||||||
|
formatted = "\n".join(
|
||||||
|
f" - {path}"
|
||||||
|
for path in missing
|
||||||
|
)
|
||||||
|
raise RuntimeError(
|
||||||
|
"Kronic resolver files are missing:\n"
|
||||||
|
f"{formatted}\n"
|
||||||
|
"Expected the resolver beneath "
|
||||||
|
f"{KRONIC_DIR}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def start_resolver() -> bool:
|
||||||
|
"""
|
||||||
|
Start kronic.resolver.app_spotdl:app as a child of the media server.
|
||||||
|
|
||||||
|
Returns True when this process started the resolver.
|
||||||
|
Returns False when a compatible resolver was already listening.
|
||||||
|
"""
|
||||||
|
global _PROCESS, _OWNS_PROCESS
|
||||||
|
|
||||||
|
with _LOCK:
|
||||||
|
if _PROCESS is not None and _PROCESS.poll() is None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# If something is already listening and healthy, use it rather than
|
||||||
|
# starting a duplicate listener.
|
||||||
|
if resolver_is_ready():
|
||||||
|
print(
|
||||||
|
f"[RESOLVER] Existing resolver detected at {RESOLVER_URL}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
_OWNS_PROCESS = False
|
||||||
|
return False
|
||||||
|
|
||||||
|
validate_resolver_tree()
|
||||||
|
|
||||||
|
command = [
|
||||||
|
sys.executable,
|
||||||
|
"-m",
|
||||||
|
"uvicorn",
|
||||||
|
"kronic.resolver.app_spotdl:app",
|
||||||
|
"--host",
|
||||||
|
RESOLVER_HOST,
|
||||||
|
"--port",
|
||||||
|
str(RESOLVER_PORT),
|
||||||
|
"--log-level",
|
||||||
|
os.getenv(
|
||||||
|
"KRONIC_RESOLVER_LOG_LEVEL",
|
||||||
|
"warning",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
env = os.environ.copy()
|
||||||
|
env.setdefault(
|
||||||
|
"PYTHONUNBUFFERED",
|
||||||
|
"1",
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"[RESOLVER] Starting embedded Kronic resolver:",
|
||||||
|
" ".join(command),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
_PROCESS = subprocess.Popen(
|
||||||
|
command,
|
||||||
|
cwd=str(BASE_DIR),
|
||||||
|
env=env,
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
_OWNS_PROCESS = True
|
||||||
|
|
||||||
|
deadline = (
|
||||||
|
time.monotonic()
|
||||||
|
+ RESOLVER_START_TIMEOUT
|
||||||
|
)
|
||||||
|
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
process = _PROCESS
|
||||||
|
|
||||||
|
if process is None:
|
||||||
|
break
|
||||||
|
|
||||||
|
return_code = process.poll()
|
||||||
|
if return_code is not None:
|
||||||
|
_PROCESS = None
|
||||||
|
_OWNS_PROCESS = False
|
||||||
|
raise RuntimeError(
|
||||||
|
"Embedded Kronic resolver exited during startup "
|
||||||
|
f"with return code {return_code}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if resolver_is_ready(
|
||||||
|
timeout=1.0
|
||||||
|
):
|
||||||
|
print(
|
||||||
|
f"[RESOLVER] Ready at {RESOLVER_URL}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
|
||||||
|
time.sleep(0.25)
|
||||||
|
|
||||||
|
stop_resolver()
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
"Embedded Kronic resolver did not become ready within "
|
||||||
|
f"{RESOLVER_START_TIMEOUT:.1f} seconds"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def stop_resolver() -> None:
|
||||||
|
global _PROCESS, _OWNS_PROCESS
|
||||||
|
|
||||||
|
with _LOCK:
|
||||||
|
process = _PROCESS
|
||||||
|
owns_process = _OWNS_PROCESS
|
||||||
|
|
||||||
|
_PROCESS = None
|
||||||
|
_OWNS_PROCESS = False
|
||||||
|
|
||||||
|
if process is None or not owns_process:
|
||||||
|
return
|
||||||
|
|
||||||
|
if process.poll() is not None:
|
||||||
|
return
|
||||||
|
|
||||||
|
print(
|
||||||
|
"[RESOLVER] Stopping embedded Kronic resolver...",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
process.terminate()
|
||||||
|
process.wait(timeout=8)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
process.kill()
|
||||||
|
process.wait(timeout=3)
|
||||||
|
except Exception as error:
|
||||||
|
print(
|
||||||
|
f"[RESOLVER] Stop error: {error}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolver_status() -> dict:
|
||||||
|
process = _PROCESS
|
||||||
|
|
||||||
|
return {
|
||||||
|
"url": RESOLVER_URL,
|
||||||
|
"ready": resolver_is_ready(),
|
||||||
|
"managed": bool(
|
||||||
|
process is not None
|
||||||
|
and _OWNS_PROCESS
|
||||||
|
),
|
||||||
|
"pid": (
|
||||||
|
process.pid
|
||||||
|
if process is not None
|
||||||
|
and process.poll() is None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"kronic_dir": str(KRONIC_DIR),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
atexit.register(
|
||||||
|
stop_resolver
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user