feat: 合成 MP4 时带上独立音频并支持按剧重新下载

This commit is contained in:
Nixevol
2026-10-21 22:06:50 +08:00
parent fe37a84971
commit e31e80384c
6 changed files with 647 additions and 25 deletions
+15
View File
@@ -83,6 +83,21 @@ def resume_all_downloads():
return downloads.resume_all()
@router.post("/remux")
def remux_downloads():
return call(downloads.remux_saved)
@router.post("/{drama_id}/remux")
def remux_one_download(drama_id: str):
return call(lambda: downloads.remux_job(drama_id))
@router.post("/{drama_id}/redownload")
def redownload_one(drama_id: str):
return call(lambda: downloads.redownload(drama_id))
@router.post("/{drama_id}/pause")
def pause_download(drama_id: str):
return downloads.pause(drama_id)
+143 -6
View File
@@ -34,7 +34,7 @@ FOLDER_NOTE = """这部剧的文件说明
这部剧的编号、名称和简介。
MP4
每一集由多个分片合成为一条完整的单集视频,放在这个目录里。一集对应一个文件,可以直接用播放器打开。
每一集由视频分片和音频分片合成为一条完整的单集视频,放在这个目录里。一集对应一个文件,可以直接用播放器打开。
source
这里保存每一集下载下来的分片和播放列表。MP4 目录里的完整单集,就是由这些分片合成的。平时观看用 MP4 目录即可。
@@ -156,6 +156,66 @@ class DownloadManager:
return self._directory
return self.set_directory(chosen)
def remux_saved(self) -> dict:
with self._lock:
directory = self._directory
busy = any(job.get("status") == "downloading" for job in self._jobs.values())
saved = [
(str(job["id"]), str(job.get("folder") or ""), self._episode_snapshot_locked(job))
for job in self._jobs.values()
]
if busy:
raise RuntimeError("有剧正在下载,先暂停后再重新合成")
for drama_id, folder, episodes in saved:
if folder and Path(folder).is_dir():
_seed_master_urls(drama_id, Path(folder), episodes)
return remux_tree(Path(directory))
def remux_job(self, drama_id: str) -> dict:
with self._lock:
job = self._jobs.get(str(drama_id))
if job is None:
raise RuntimeError("没有这部剧的下载记录")
if job.get("status") == "downloading":
raise RuntimeError("这部剧正在下载,先暂停后再重新合成")
folder = str(job.get("folder") or "")
episodes = self._episode_snapshot_locked(job)
if not folder or not Path(folder).is_dir():
raise RuntimeError("这部剧的目录不存在")
_seed_master_urls(str(drama_id), Path(folder), episodes)
return remux_tree(Path(folder))
def redownload(self, drama_id: str) -> dict:
self.start()
with self._lock:
job = self._jobs.get(str(drama_id))
if job is None:
raise RuntimeError("没有这部剧的下载记录")
if job.get("status") == "downloading":
raise RuntimeError("这部剧正在下载")
job["status"] = "queued"
job["command"] = ""
job["completed_at"] = ""
job["error"] = ""
job["fraction"] = 0
for ep in job.get("episodes") or []:
ep["phase"] = "pending" if ep.get("src") else "skipped"
self._save_locked()
self._wake.set()
return self.snapshot()
def _episode_snapshot_locked(self, job: dict) -> list[dict]:
return [
{
"cid": ep.get("cid"),
"idx": ep.get("idx"),
"title": ep.get("title") or "",
"src": ep.get("src") or "",
}
for ep in job.get("episodes") or []
if isinstance(ep, dict)
]
def enqueue(self, token: str, raw_device: dict | None, items: list[dict]) -> dict:
self.start()
device = sessions.bind(token, DeviceProfile.merge(raw_device)) if token else None
@@ -515,17 +575,23 @@ class DownloadManager:
def _write_playlist(self, drama_id: str, folder: Path, row: dict) -> None:
source_dir, _mp4_path = self._episode_paths(folder, row)
master_text, media_text, items = playlists.expand_variant(row["src"])
master_text, media_text, items, audio_text, audio_items = playlists.expand_variant(row["src"])
source_dir.mkdir(parents=True, exist_ok=True)
(source_dir / "video.m3u8").write_text(media_text, encoding="utf-8", newline="\n")
if audio_text and audio_items:
(source_dir / "audio.m3u8").write_text(audio_text, encoding="utf-8", newline="\n")
master_text = _point_audio_at_local(master_text)
(source_dir / "playlist.m3u8").write_text(
_localize(master_text, ["video.m3u8"]),
encoding="utf-8",
newline="\n",
)
(source_dir / "segments.json").write_text(json.dumps(items, ensure_ascii=False), encoding="utf-8")
done = sum(1 for item in items if (source_dir / item["name"]).is_file() and (source_dir / item["name"]).stat().st_size > 0)
self._set_segments(drama_id, row["cid"], len(items), done)
saved_items = list(items) + list(audio_items)
(source_dir / "segments.json").write_text(json.dumps(saved_items, ensure_ascii=False), encoding="utf-8")
if row.get("src"):
(source_dir / "master.url").write_text(str(row["src"]).strip() + "\n", encoding="utf-8")
done = sum(1 for item in saved_items if (source_dir / item["name"]).is_file() and (source_dir / item["name"]).stat().st_size > 0)
self._set_segments(drama_id, row["cid"], len(saved_items), done)
def _set_segments(self, drama_id: str, cid: int, count: int, done: int) -> None:
with self._lock:
@@ -551,7 +617,7 @@ class DownloadManager:
return
source_dir, mp4_path = self._episode_paths(folder, row)
manifest = source_dir / "segments.json"
if mp4_path.is_file() and mp4_path.stat().st_size > 0:
if _keep_finished_episode(str(row.get("phase") or ""), mp4_path):
if manifest.is_file():
items = json.loads(manifest.read_text(encoding="utf-8"))
self._set_segments(drama_id, row["cid"], len(items), len(items))
@@ -685,6 +751,77 @@ class DownloadManager:
)
def _keep_finished_episode(phase: str, mp4_path: Path) -> bool:
return phase == "done" and mp4_path.is_file() and mp4_path.stat().st_size > 0
def _seed_master_urls(drama_id: str, folder: Path, episodes: list[dict]) -> None:
try:
vid = int(drama_id)
except ValueError:
vid = 0
for ep in episodes:
url = str(ep.get("src") or "").strip()
cid = int(ep.get("cid") or 0)
if not url.startswith(("http://", "https://")) and vid and cid:
url = playlists.cached_episode_src(vid, cid)
if not url.startswith(("http://", "https://")):
continue
name = playlists.safe_name(ep.get("title") or "", f"EP.{ep.get('idx') or cid}")
source = folder / "source" / name
if not source.is_dir():
continue
path = source / "master.url"
if path.is_file() and path.read_text(encoding="utf-8").strip():
continue
path.write_text(url + "\n", encoding="utf-8")
def _point_audio_at_local(text: str) -> str:
lines = []
for line in text.splitlines():
if "TYPE=AUDIO" in line.upper() and "URI=" in line:
lines.append(re.sub(r'URI="[^"]*"', 'URI="audio.m3u8"', line, count=1))
else:
lines.append(line)
return "\n".join(lines) + "\n"
def remux_tree(root: Path) -> dict:
if not root.is_dir():
raise RuntimeError("下载目录不存在")
videos = [
path
for path in root.rglob("video.m3u8")
if path.parent.parent.name == "source"
]
if not videos:
raise RuntimeError("这个目录里没有找到已保存的分片。请把下载目录指到包含各部剧文件夹的那一层。")
ok = 0
failed: list[str] = []
for video in videos:
source = video.parent
drama = source.parent.parent
mp4 = drama / "MP4" / f"{source.name}.mp4"
label = f"{drama.name} / {source.name}"
audio_error = ""
try:
playlists.ensure_saved_audio(source)
except RuntimeError as exc:
audio_error = str(exc)
try:
convert_to_mp4(source, mp4)
ok += 1
except RuntimeError as exc:
failed.append(f"{label}: {audio_error or exc}")
except OSError as exc:
failed.append(f"{label}: {exc}")
message = f"已重新合成 {ok} 集"
if failed:
message += f",{len(failed)} 集没有补上声音"
return {"ok": ok, "failed": len(failed), "errors": failed[:50], "message": message}
def _localize(text: str, names: list[str]) -> str:
lines = []
index = 0
+28 -15
View File
@@ -42,22 +42,22 @@ def convert_to_mp4(episode_dir: Path, mp4_path: Path) -> None:
exe = ensure_ffmpeg()
mp4_path.parent.mkdir(parents=True, exist_ok=True)
temporary = mp4_path.with_name(f"{mp4_path.stem}.part.mp4")
command = [
str(exe),
"-y",
"-allowed_extensions",
"ALL",
"-i",
"video.m3u8",
]
audio = episode_dir / "audio.m3u8"
if audio.is_file():
command.extend(["-i", "audio.m3u8", "-map", "0:v:0", "-map", "1:a:0"])
else:
command.extend(["-map", "0:v:0", "-map", "0:a?"])
command.extend(["-c", "copy", "-movflags", "+faststart", "-f", "mp4", str(temporary)])
completed = subprocess.run(
[
str(exe),
"-y",
"-allowed_extensions",
"ALL",
"-i",
"video.m3u8",
"-c",
"copy",
"-movflags",
"+faststart",
"-f",
"mp4",
str(temporary),
],
command,
cwd=episode_dir,
capture_output=True,
check=False,
@@ -66,9 +66,22 @@ def convert_to_mp4(episode_dir: Path, mp4_path: Path) -> None:
temporary.unlink(missing_ok=True)
detail = (completed.stderr or b"").decode("utf-8", "replace")[-400:]
raise RuntimeError("转换成 MP4 失败" + (f":{detail}" if detail else ""))
if not _output_has_audio(exe, temporary):
temporary.unlink(missing_ok=True)
raise RuntimeError("合成结果没有音轨。音频分片没有下载到,或者音频地址已经过期。")
temporary.replace(mp4_path)
def _output_has_audio(exe: Path, media: Path) -> bool:
completed = subprocess.run(
[str(exe), "-hide_banner", "-i", str(media)],
capture_output=True,
check=False,
)
text = (completed.stderr or b"").decode("utf-8", "replace")
return "Audio:" in text
def unused_zip_helper(path: Path) -> None:
if path.suffix == ".zip":
with zipfile.ZipFile(path) as archive:
+252 -4
View File
@@ -73,6 +73,13 @@ def _request_playlist(token: str, device: DeviceProfile, vid: int) -> list[dict]
return collected or episodes
def cached_episode_src(vid: int, cid: int) -> str:
for ep in _read_cache(vid):
if int(ep.get("cid") or 0) == cid:
return str(ep.get("src") or "").strip()
return ""
def _cache_path(vid: int) -> Path:
return CACHE_DIR / f"{vid}.json"
@@ -147,7 +154,19 @@ def load_episodes(token: str, device: DeviceProfile | None, vid: int) -> list[di
return merged
def expand_variant(master_url: str) -> tuple[str, str, list[dict]]:
def audio_rendition_uris(text: str) -> list[str]:
found = []
for line in text.splitlines():
stripped = line.strip()
if "TYPE=AUDIO" not in stripped.upper() or "URI=" not in stripped:
continue
match = re.search(r'URI="([^"]*)"', stripped)
if match and match.group(1):
found.append(match.group(1))
return found
def expand_variant(master_url: str) -> tuple[str, str, list[dict], str, list[dict]]:
master_text = http.read_text(master_url)
variant_rel = next(
(line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")),
@@ -164,10 +183,35 @@ def expand_variant(master_url: str) -> tuple[str, str, list[dict]]:
localized, items = localize_media(media_text, variant_url)
if not items:
raise RuntimeError("播放列表没有分片")
return master_text, localized, items
audio_text = ""
audio_items: list[dict] = []
for rel in audio_rendition_uris(master_text):
audio_url = urljoin(master_url, rel)
fetched = http.read_text(audio_url)
audio_text, audio_items = localize_media(fetched, audio_url, name_prefix="audio-")
if audio_items:
break
return master_text, localized, items, audio_text, audio_items
def localize_media(text: str, base: str) -> tuple[str, list[dict]]:
def guess_audio_playlist_urls(segment_url: str) -> list[str]:
"""由视频分片地址推测同一视频目录下的音频列表。"""
if not segment_url.startswith(("http://", "https://")):
return []
path, sep, query = segment_url.partition("?")
parts = path.rstrip("/").split("/")
if len(parts) < 3:
return []
suffix = f"?{query}" if sep and query else ""
root = "/".join(parts[:-2])
parent = "/".join(parts[:-1])
return [
f"{root}/audio/audio.m3u8{suffix}",
f"{parent}/audio.m3u8{suffix}",
]
def localize_media(text: str, base: str, name_prefix: str = "") -> tuple[str, list[dict]]:
urls = _resource_urls(text, base)
names: list[str] = []
items: list[dict] = []
@@ -176,7 +220,7 @@ def localize_media(text: str, base: str) -> tuple[str, list[dict]]:
for index, url in enumerate(urls, start=1):
name = known.get(url)
if name is None:
name = _resource_name(url, index, used)
name = name_prefix + _resource_name(url, index, used)
known[url] = name
items.append({"name": name, "url": url})
names.append(name)
@@ -232,6 +276,210 @@ def _apply_local_names(text: str, names: list[str]) -> str:
return "\n".join(lines) + "\n"
def _playlist_local_files(playlist: Path) -> list[Path]:
text = playlist.read_text(encoding="utf-8")
base = playlist.parent
found: list[Path] = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
continue
if stripped.startswith("#"):
for match in re.findall(r'URI="([^"]*)"', stripped):
if match and not match.startswith(("http://", "https://")):
found.append(base / match)
continue
if not stripped.startswith(("http://", "https://")):
found.append(base / stripped)
return found
def _playlist_complete(playlist: Path) -> bool:
if not playlist.is_file():
return False
files = _playlist_local_files(playlist)
if not files:
return False
return all(path.is_file() and path.stat().st_size > 0 for path in files)
def _segment_urls(source: Path) -> list[str]:
manifest = source / "segments.json"
if not manifest.is_file():
return []
try:
items = json.loads(manifest.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return []
urls = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
url = str(item.get("url") or "")
if url.startswith(("http://", "https://")):
urls.append(url)
return urls
def _cdn_master_base(segment_url: str) -> tuple[str, str]:
path, sep, query = segment_url.partition("?")
parts = path.rstrip("/").split("/")
if len(parts) < 3:
return "", ""
return "/".join(parts[:-2]) + "/", query if sep else ""
def _master_audio_urls(source: Path) -> list[str]:
master_file = source / "master.url"
if not master_file.is_file():
return []
try:
master_url = master_file.read_text(encoding="utf-8").strip()
except OSError:
return []
if not master_url.startswith(("http://", "https://")):
return []
try:
master_text = http.read_text(master_url)
except RuntimeError:
return []
return [urljoin(master_url, rel) for rel in audio_rendition_uris(master_text)]
def audio_download_candidates(source: Path) -> list[str]:
"""从已保存的播放列表和分片地址里找出还能尝试的音频列表。"""
found: list[str] = []
playlist = source / "playlist.m3u8"
relatives: list[str] = []
if playlist.is_file():
try:
relatives = audio_rendition_uris(playlist.read_text(encoding="utf-8"))
except OSError:
relatives = []
segment_urls = _segment_urls(source)
base = ""
query = ""
for url in segment_urls:
base, query = _cdn_master_base(url)
if base:
break
for rel in relatives:
if rel.startswith(("http://", "https://")):
found.append(rel)
continue
if rel in {"audio.m3u8", "video.m3u8"} or not base:
continue
joined = urljoin(base, rel)
if query and "?" not in joined:
joined = f"{joined}?{query}"
found.append(joined)
for url in segment_urls:
found.extend(guess_audio_playlist_urls(url))
break
unique: list[str] = []
seen: set[str] = set()
for url in found:
if url not in seen:
seen.add(url)
unique.append(url)
return unique
def store_audio_playlist(source: Path, playlist_url: str) -> None:
text = http.read_text(playlist_url)
localized, items = localize_media(text, playlist_url, name_prefix="audio-")
if not items:
raise RuntimeError("音频列表没有分片")
source.mkdir(parents=True, exist_ok=True)
created: list[Path] = []
try:
for item in items:
target = source / item["name"]
if target.is_file() and target.stat().st_size > 0:
continue
http.download_file(item["url"], target)
created.append(target)
missing = [item["name"] for item in items if not (source / item["name"]).is_file() or (source / item["name"]).stat().st_size <= 0]
if missing:
raise RuntimeError("音频分片没有下全")
(source / "audio.m3u8").write_text(localized, encoding="utf-8", newline="\n")
except Exception:
for path in created:
path.unlink(missing_ok=True)
partial = source / "audio.m3u8"
if partial.is_file() and not _playlist_complete(partial):
partial.unlink(missing_ok=True)
raise
def _complete_audio_from_manifest(source: Path) -> bool:
audio = source / "audio.m3u8"
if not audio.is_file():
return False
needed = _playlist_local_files(audio)
if not needed:
return False
manifest = dict(_manifest_items(source))
for path in needed:
if path.is_file() and path.stat().st_size > 0:
continue
url = manifest.get(path.name)
if not url:
return False
http.download_file(url, path)
return _playlist_complete(audio)
def _manifest_items(source: Path) -> list[tuple[str, str]]:
manifest = source / "segments.json"
if not manifest.is_file():
return []
try:
items = json.loads(manifest.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return []
pairs = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
name = str(item.get("name") or "")
url = str(item.get("url") or "")
if name and url.startswith(("http://", "https://")):
pairs.append((name, url))
return pairs
def ensure_saved_audio(source: Path) -> bool:
"""准备好 audio.m3u8。没有音频引用时返回 False;地址失效时抛出错误。"""
audio = source / "audio.m3u8"
if _playlist_complete(audio):
return True
try:
if _complete_audio_from_manifest(source):
return True
except RuntimeError:
pass
if audio.is_file():
audio.unlink(missing_ok=True)
candidates: list[str] = []
seen: set[str] = set()
for url in _master_audio_urls(source) + audio_download_candidates(source):
if url not in seen:
seen.add(url)
candidates.append(url)
if not candidates:
return False
errors: list[str] = []
for url in candidates:
try:
store_audio_playlist(source, url)
return True
except RuntimeError as exc:
errors.append(str(exc))
detail = errors[-1] if errors else "下载失败"
raise RuntimeError(f"音频地址已失效,没法补上下载:{detail}")
def episode_src(token: str, device: DeviceProfile | None, vid: int, cid: int) -> str:
for ep in load_episodes(token, device, vid):
if int(ep.get("cid") or 0) == cid and ep.get("src"):