mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-04 06:55:09 +00:00
refactor(manifests): merge downloaded DASH and ISM segments through segment_pipeline.merge_downloaded
This commit is contained in:
@@ -0,0 +1,54 @@
|
|||||||
|
"""The ISM merge: the rolling path ends the download phase, and a text subtitle merges behind its init as UTF-8."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from tests.core.test_rolling_merge_hls_ism import base, ism_track, make_ctx
|
||||||
|
from tests.core.test_rolling_merge_hls_ism import no_cancel as no_cancel # noqa: F401
|
||||||
|
from tests.core.test_rolling_merge_hls_ism import server as server # noqa: F401
|
||||||
|
from unshackle.core.config import config
|
||||||
|
from unshackle.core.manifests import ISM
|
||||||
|
from unshackle.core.manifests import ism as ism_module
|
||||||
|
from unshackle.core.tracks.segment_store import SegmentStore
|
||||||
|
|
||||||
|
CUES = [b"1\n00:00:00,000 --> 00:00:01,000\n‎one\n\n", b"2\n00:00:02,000 --> 00:00:03,000\n‏two\n\n"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_text_subtitle_merges_behind_its_init_with_the_entities_as_characters(server, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr(config, "merge_segments", False)
|
||||||
|
firsts: list[bytes | None] = []
|
||||||
|
|
||||||
|
def init_segment(track, session_drm, first_segment=None):
|
||||||
|
firsts.append(first_segment)
|
||||||
|
return b"INIT"
|
||||||
|
|
||||||
|
monkeypatch.setattr(ISM, "init_segment", staticmethod(init_segment))
|
||||||
|
for i, cue in enumerate(CUES):
|
||||||
|
server.routes[f"/x.ism/text{i * 20000000}.srt"] = cue
|
||||||
|
manifest = f"""<?xml version="1.0"?>
|
||||||
|
<SmoothStreamingMedia MajorVersion="2" MinorVersion="0" Duration="40000000" TimeScale="10000000">
|
||||||
|
<StreamIndex Type="text" Name="text" Language="en" Url="text{{start_time}}.srt">
|
||||||
|
<QualityLevel Index="0" Bitrate="1000" FourCC="SRT"/>
|
||||||
|
<c t="0" d="20000000" r="{len(CUES)}"/>
|
||||||
|
</StreamIndex>
|
||||||
|
</SmoothStreamingMedia>
|
||||||
|
"""
|
||||||
|
track = ISM.from_text(manifest, f"{base(server)}x.ism/manifest").to_tracks().subtitles[0]
|
||||||
|
ctx = make_ctx(tmp_path, "subtitle.srt")
|
||||||
|
|
||||||
|
ISM.download_track(track, ctx)
|
||||||
|
|
||||||
|
assert firsts == [CUES[0]]
|
||||||
|
assert ctx.save_path.read_bytes() == b"INIT" + b"".join(CUES).replace(b"‎", "\u200e".encode()).replace(
|
||||||
|
b"‏", "\u200f".encode()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_rolling_merge_ends_the_download_phase_before_it_checks_the_count(server, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr(config, "merge_segments", True)
|
||||||
|
calls: list[str] = []
|
||||||
|
monkeypatch.setattr(SegmentStore, "merging", lambda self: calls.append("merging"))
|
||||||
|
monkeypatch.setattr(ism_module, "check_merged", lambda *args: calls.append("check_merged"))
|
||||||
|
|
||||||
|
ISM.download_track(ism_track(server), make_ctx(tmp_path, "audio.mp4"))
|
||||||
|
|
||||||
|
assert calls == ["merging", "check_merged"]
|
||||||
@@ -24,6 +24,7 @@ from unshackle.core.manifests.segment_pipeline import (
|
|||||||
complete_track,
|
complete_track,
|
||||||
fetch_segments,
|
fetch_segments,
|
||||||
license_drm,
|
license_drm,
|
||||||
|
merge_downloaded,
|
||||||
)
|
)
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
from unshackle.core.tracks.segment_store import SegmentStore
|
from unshackle.core.tracks.segment_store import SegmentStore
|
||||||
@@ -427,3 +428,63 @@ def test_complete_track_without_drm_skips_the_decryption(tmp_path, seen):
|
|||||||
assert seen == []
|
assert seen == []
|
||||||
assert track.path == ctx.save_path
|
assert track.path == ctx.save_path
|
||||||
assert ctx.statuses == ["Downloaded"]
|
assert ctx.statuses == ["Downloaded"]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeStore:
|
||||||
|
"""Records when the merge ends the download phase."""
|
||||||
|
|
||||||
|
def __init__(self, calls: list[str]) -> None:
|
||||||
|
self.calls = calls
|
||||||
|
|
||||||
|
def merging(self) -> None:
|
||||||
|
self.calls.append("merging")
|
||||||
|
|
||||||
|
|
||||||
|
def segment_dir(ctx: DownloadContext, parts: list[bytes]) -> list[Path]:
|
||||||
|
ctx.save_dir.mkdir()
|
||||||
|
files = [ctx.save_dir / f"{i}.mp4" for i in range(len(parts))]
|
||||||
|
for path, data in zip(files, parts, strict=True):
|
||||||
|
path.write_bytes(data)
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_downloaded_writes_the_init_then_each_segment_and_removes_it(tmp_path):
|
||||||
|
ctx = make_ctx(tmp_path)
|
||||||
|
files = segment_dir(ctx, PARTS[:3])
|
||||||
|
calls: list[str] = []
|
||||||
|
|
||||||
|
def append(dst, path):
|
||||||
|
calls.append(path.name)
|
||||||
|
dst.write(path.read_bytes())
|
||||||
|
|
||||||
|
merge_downloaded(
|
||||||
|
SimpleNamespace(id="EXAMPLE"), # type: ignore[arg-type]
|
||||||
|
ctx,
|
||||||
|
"DASH",
|
||||||
|
FakeStore(calls), # type: ignore[arg-type]
|
||||||
|
INIT,
|
||||||
|
append,
|
||||||
|
prepare=lambda segment_files: calls.append(f"prepare {len(segment_files)}"),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ctx.save_path.read_bytes() == INIT + b"".join(PARTS[:3])
|
||||||
|
assert calls == ["merging", "prepare 3", "0.mp4", "1.mp4", "2.mp4"]
|
||||||
|
assert not any(path.exists() for path in files)
|
||||||
|
assert ctx.statuses == ["Merging"] # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_downloaded_without_segments_raises(tmp_path):
|
||||||
|
ctx = make_ctx(tmp_path)
|
||||||
|
calls: list[str] = []
|
||||||
|
track = SimpleNamespace(id="EXAMPLE")
|
||||||
|
store = FakeStore(calls)
|
||||||
|
|
||||||
|
with pytest.raises(FileNotFoundError, match="Output directory does not exist"):
|
||||||
|
merge_downloaded(track, ctx, "ISM", store, None, pytest.fail) # type: ignore[arg-type]
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
ctx.save_dir.mkdir()
|
||||||
|
with pytest.raises(FileNotFoundError, match="No segment files found"):
|
||||||
|
merge_downloaded(track, ctx, "ISM", store, None, pytest.fail) # type: ignore[arg-type]
|
||||||
|
assert calls == ["merging"]
|
||||||
|
assert not ctx.save_path.exists()
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import re
|
|||||||
import shutil
|
import shutil
|
||||||
from bisect import bisect_right
|
from bisect import bisect_right
|
||||||
from collections.abc import Callable, Collection
|
from collections.abc import Callable, Collection
|
||||||
from contextlib import suppress
|
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from functools import cache, partial
|
from functools import cache, partial
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -40,6 +39,7 @@ from unshackle.core.manifests.segment_pipeline import (
|
|||||||
complete_track,
|
complete_track,
|
||||||
fetch_segments,
|
fetch_segments,
|
||||||
license_drm,
|
license_drm,
|
||||||
|
merge_downloaded,
|
||||||
)
|
)
|
||||||
from unshackle.core.manifests.trim import trim_overlaps
|
from unshackle.core.manifests.trim import trim_overlaps
|
||||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||||
@@ -769,77 +769,17 @@ class DASH:
|
|||||||
store.merging()
|
store.merging()
|
||||||
check_merged(merger, len(segments), track, ctx, "DASH")
|
check_merged(merger, len(segments), track, ctx, "DASH")
|
||||||
else:
|
else:
|
||||||
if not save_dir.exists():
|
|
||||||
error_msg = f"Output directory does not exist: {save_dir}"
|
|
||||||
log_event(
|
|
||||||
"manifest_dash_download_output_missing",
|
|
||||||
level="ERROR",
|
|
||||||
message=error_msg,
|
|
||||||
context={
|
|
||||||
"track_id": getattr(track, "id", None),
|
|
||||||
"track_type": track.__class__.__name__,
|
|
||||||
"save_dir": str(save_dir),
|
|
||||||
"save_path": str(save_path),
|
|
||||||
"downloader": "requests",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
raise FileNotFoundError(error_msg)
|
|
||||||
|
|
||||||
store.merging()
|
def rebase_periods(segment_files: list[Path]) -> None:
|
||||||
|
|
||||||
segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()]
|
|
||||||
|
|
||||||
log_event(
|
|
||||||
"manifest_dash_download_complete",
|
|
||||||
level="DEBUG",
|
|
||||||
message="DASH download complete, preparing to merge",
|
|
||||||
context={
|
|
||||||
"track_id": getattr(track, "id", None),
|
|
||||||
"track_type": track.__class__.__name__,
|
|
||||||
"save_dir": str(save_dir),
|
|
||||||
"save_dir_exists": save_dir.exists(),
|
|
||||||
"segments_found": len(segments_to_merge),
|
|
||||||
"segment_files": [f.name for f in segments_to_merge[:10]],
|
|
||||||
"downloader": "requests",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
if not segments_to_merge:
|
|
||||||
error_msg = f"No segment files found in output directory: {save_dir}"
|
|
||||||
all_contents = list(save_dir.iterdir()) if save_dir.exists() else []
|
|
||||||
log_event(
|
|
||||||
"manifest_dash_download_no_segments",
|
|
||||||
level="ERROR",
|
|
||||||
message=error_msg,
|
|
||||||
context={
|
|
||||||
"track_id": getattr(track, "id", None),
|
|
||||||
"track_type": track.__class__.__name__,
|
|
||||||
"save_dir": str(save_dir),
|
|
||||||
"directory_contents": [str(p) for p in all_contents],
|
|
||||||
"downloader": "requests",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
raise FileNotFoundError(error_msg)
|
|
||||||
|
|
||||||
if rebase_vtt:
|
|
||||||
firsts = sorted(period_starts)
|
firsts = sorted(period_starts)
|
||||||
groups: list[list[Path]] = [[] for _ in firsts]
|
groups: list[list[Path]] = [[] for _ in firsts]
|
||||||
for segment_file in segments_to_merge:
|
for segment_file in segment_files:
|
||||||
groups[bisect_right(firsts, int(segment_file.stem)) - 1].append(segment_file)
|
groups[bisect_right(firsts, int(segment_file.stem)) - 1].append(segment_file)
|
||||||
last_start, last_duration, _ = period_starts[firsts[-1]]
|
last_start, last_duration, _ = period_starts[firsts[-1]]
|
||||||
bounds = [*(period_starts[i][0] for i in firsts), last_start + last_duration]
|
bounds = [*(period_starts[i][0] for i in firsts), last_start + last_duration]
|
||||||
rebase_webvtt_files(groups, [round(t * 1000) for t in bounds])
|
rebase_webvtt_files(groups, [round(t * 1000) for t in bounds])
|
||||||
|
|
||||||
with open(save_path, "wb") as f:
|
merge_downloaded(track, ctx, "DASH", store, init_data, append, rebase_periods if rebase_vtt else None)
|
||||||
if init_data:
|
|
||||||
f.write(init_data)
|
|
||||||
if len(segments_to_merge) > 1:
|
|
||||||
progress(downloaded="Merging", completed=0, total=len(segments_to_merge))
|
|
||||||
for segment_file in segments_to_merge:
|
|
||||||
append(f, segment_file)
|
|
||||||
with suppress(OSError):
|
|
||||||
segment_file.unlink()
|
|
||||||
progress(advance=1)
|
|
||||||
|
|
||||||
if rebase and rebase.joins and isinstance(track, Audio):
|
if rebase and rebase.joins and isinstance(track, Audio):
|
||||||
try:
|
try:
|
||||||
|
|||||||
+24
-102
@@ -2,13 +2,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
import hashlib
|
import hashlib
|
||||||
import html
|
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
import shutil
|
|
||||||
import struct
|
import struct
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
from contextlib import suppress
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, BinaryIO
|
from typing import Any, BinaryIO
|
||||||
|
|
||||||
@@ -35,12 +32,14 @@ from unshackle.core.manifests.segment_pipeline import (
|
|||||||
complete_track,
|
complete_track,
|
||||||
fetch_segments,
|
fetch_segments,
|
||||||
license_drm,
|
license_drm,
|
||||||
|
merge_downloaded,
|
||||||
|
text_subtitle_bytes,
|
||||||
)
|
)
|
||||||
from unshackle.core.session import RnetSession
|
from unshackle.core.session import RnetSession
|
||||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video
|
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video
|
||||||
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
|
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
|
||||||
from unshackle.core.tracks.track import iter_top_level_boxes
|
from unshackle.core.tracks.track import iter_top_level_boxes
|
||||||
from unshackle.core.utilities import log_event, try_ensure_utf8
|
from unshackle.core.utilities import log_event
|
||||||
from unshackle.core.utils import run_proxy
|
from unshackle.core.utils import run_proxy
|
||||||
from unshackle.core.utils.redact import safe_display_url
|
from unshackle.core.utils.redact import safe_display_url
|
||||||
from unshackle.core.utils.xml import load_xml
|
from unshackle.core.utils.xml import load_xml
|
||||||
@@ -459,22 +458,32 @@ class ISM:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
is_text_subtitle = (
|
||||||
|
not session_drm
|
||||||
|
and isinstance(track, Subtitle)
|
||||||
|
and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML)
|
||||||
|
)
|
||||||
iv_size = first_iv_size(save_path) if store.cursor and session_drm else 8
|
iv_size = first_iv_size(save_path) if store.cursor and session_drm else 8
|
||||||
|
head = not store.cursor
|
||||||
|
|
||||||
def append_ism(dst: BinaryIO, segment_file: Path) -> None:
|
def append_ism(dst: BinaryIO, segment_file: Path) -> None:
|
||||||
"""Write one fragment; segment 0 also synthesises the init box the fragments lack."""
|
"""Write one fragment; the first fragment of the output also synthesises the init box the fragments lack."""
|
||||||
nonlocal iv_size
|
nonlocal iv_size, head
|
||||||
if int(segment_file.stem) == 0:
|
if head:
|
||||||
|
head = False
|
||||||
segment_data = segment_file.read_bytes()
|
segment_data = segment_file.read_bytes()
|
||||||
init_segment = ISM.init_segment(track, session_drm, segment_data)
|
if init_segment := ISM.init_segment(track, session_drm, segment_data):
|
||||||
if init_segment:
|
|
||||||
dst.write(init_segment)
|
dst.write(init_segment)
|
||||||
iv_size = (read_per_sample_iv_size(segment_data) if session_drm else None) or 8
|
if session_drm:
|
||||||
dst.write(piff_senc_to_cenc(segment_data, iv_size) if session_drm else segment_data)
|
iv_size = read_per_sample_iv_size(segment_data) or 8
|
||||||
|
segment_data = piff_senc_to_cenc(segment_data, iv_size)
|
||||||
|
elif is_text_subtitle:
|
||||||
|
segment_data = text_subtitle_bytes(segment_data)
|
||||||
|
dst.write(segment_data)
|
||||||
elif session_drm:
|
elif session_drm:
|
||||||
dst.write(piff_senc_to_cenc(segment_file.read_bytes(), iv_size))
|
dst.write(piff_senc_to_cenc(segment_file.read_bytes(), iv_size))
|
||||||
else:
|
else:
|
||||||
append_segment(dst, segment_file, is_text_subtitle=False)
|
append_segment(dst, segment_file, is_text_subtitle)
|
||||||
|
|
||||||
merger, _ = fetch_segments(
|
merger, _ = fetch_segments(
|
||||||
track,
|
track,
|
||||||
@@ -489,98 +498,11 @@ class ISM:
|
|||||||
append=append_ism,
|
append=append_ism,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not save_dir.exists():
|
|
||||||
error_msg = f"Output directory does not exist: {save_dir}"
|
|
||||||
log_event(
|
|
||||||
"manifest_ism_download_output_missing",
|
|
||||||
level="ERROR",
|
|
||||||
message=error_msg,
|
|
||||||
context={
|
|
||||||
"track_id": getattr(track, "id", None),
|
|
||||||
"track_type": track.__class__.__name__,
|
|
||||||
"save_dir": str(save_dir),
|
|
||||||
"save_path": str(save_path),
|
|
||||||
"downloader": "requests",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
raise FileNotFoundError(error_msg)
|
|
||||||
|
|
||||||
store.merging()
|
|
||||||
|
|
||||||
if merger:
|
if merger:
|
||||||
|
store.merging()
|
||||||
check_merged(merger, len(segments), track, ctx, "ISM")
|
check_merged(merger, len(segments), track, ctx, "ISM")
|
||||||
|
else:
|
||||||
segments_to_merge = [] if merger else [x for x in sorted(save_dir.iterdir()) if x.is_file()]
|
merge_downloaded(track, ctx, "ISM", store, None, append_ism)
|
||||||
|
|
||||||
log_event(
|
|
||||||
"manifest_ism_download_complete",
|
|
||||||
level="DEBUG",
|
|
||||||
message="ISM download complete, preparing to merge",
|
|
||||||
context={
|
|
||||||
"track_id": getattr(track, "id", None),
|
|
||||||
"track_type": track.__class__.__name__,
|
|
||||||
"save_dir": str(save_dir),
|
|
||||||
"save_dir_exists": save_dir.exists(),
|
|
||||||
"segments_found": merger.merged if merger else len(segments_to_merge),
|
|
||||||
"segment_files": [f.name for f in segments_to_merge[:10]],
|
|
||||||
"rolling_merge": merger is not None,
|
|
||||||
"downloader": "requests",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
if not segments_to_merge and not merger:
|
|
||||||
error_msg = f"No segment files found in output directory: {save_dir}"
|
|
||||||
all_contents = list(save_dir.iterdir()) if save_dir.exists() else []
|
|
||||||
log_event(
|
|
||||||
"manifest_ism_download_no_segments",
|
|
||||||
level="ERROR",
|
|
||||||
message=error_msg,
|
|
||||||
context={
|
|
||||||
"track_id": getattr(track, "id", None),
|
|
||||||
"track_type": track.__class__.__name__,
|
|
||||||
"save_dir": str(save_dir),
|
|
||||||
"directory_contents": [str(p) for p in all_contents],
|
|
||||||
"downloader": "requests",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
raise FileNotFoundError(error_msg)
|
|
||||||
|
|
||||||
if not merger:
|
|
||||||
is_text_subtitle = (
|
|
||||||
not session_drm
|
|
||||||
and isinstance(track, Subtitle)
|
|
||||||
and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML)
|
|
||||||
)
|
|
||||||
progress(downloaded="Merging", completed=0, total=len(segments_to_merge))
|
|
||||||
with open(save_path, "wb") as f:
|
|
||||||
first_segment = segments_to_merge[0].read_bytes() if segments_to_merge else None
|
|
||||||
init_segment = ISM.init_segment(track, session_drm, first_segment)
|
|
||||||
if init_segment:
|
|
||||||
f.write(init_segment)
|
|
||||||
iv_size = (read_per_sample_iv_size(first_segment) if session_drm and first_segment else None) or 8
|
|
||||||
for index, segment_file in enumerate(segments_to_merge):
|
|
||||||
if is_text_subtitle:
|
|
||||||
# first segment was already read for the init synthesis, reuse it
|
|
||||||
segment_data = first_segment if index == 0 and first_segment else segment_file.read_bytes()
|
|
||||||
segment_data = try_ensure_utf8(segment_data)
|
|
||||||
segment_data = (
|
|
||||||
segment_data.decode("utf8")
|
|
||||||
.replace("‎", html.unescape("‎"))
|
|
||||||
.replace("‏", html.unescape("‏"))
|
|
||||||
.encode("utf8")
|
|
||||||
)
|
|
||||||
f.write(segment_data)
|
|
||||||
elif session_drm:
|
|
||||||
segment_data = first_segment if index == 0 and first_segment else segment_file.read_bytes()
|
|
||||||
f.write(piff_senc_to_cenc(segment_data, iv_size))
|
|
||||||
elif index == 0 and first_segment:
|
|
||||||
f.write(first_segment)
|
|
||||||
else:
|
|
||||||
with open(segment_file, "rb") as src:
|
|
||||||
shutil.copyfileobj(src, f, 1024 * 1024)
|
|
||||||
with suppress(OSError):
|
|
||||||
segment_file.unlink()
|
|
||||||
progress(advance=1)
|
|
||||||
|
|
||||||
complete_track(track, ctx, session_drm)
|
complete_track(track, ctx, session_drm)
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
"""The segment pipeline: the steps DASH, HLS and ISM share to download a segmented track.
|
"""The segment pipeline: the steps DASH, HLS and ISM share to download a segmented track.
|
||||||
|
|
||||||
Each manifest finds its own segments and supplies its own quirks; the pipeline runs the
|
Each manifest finds its own segments and supplies its own quirks; the pipeline runs the
|
||||||
licence step, the download with its rolling merge, the decrypt hand-off and the cleanup.
|
licence step, the download with its rolling merge, the DASH and ISM merge after the download, the decrypt
|
||||||
|
hand-off and the cleanup.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -11,7 +12,7 @@ import shutil
|
|||||||
import zlib
|
import zlib
|
||||||
from collections.abc import Callable, Iterator
|
from collections.abc import Callable, Iterator
|
||||||
from concurrent.futures import Future
|
from concurrent.futures import Future
|
||||||
from contextlib import ExitStack, closing, contextmanager
|
from contextlib import ExitStack, closing, contextmanager, suppress
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, BinaryIO
|
from typing import Any, BinaryIO
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
@@ -288,6 +289,74 @@ def check_merged(merger: RollingMerge, total: int, track: AnyTrack, ctx: Downloa
|
|||||||
raise FileNotFoundError(error_msg)
|
raise FileNotFoundError(error_msg)
|
||||||
|
|
||||||
|
|
||||||
|
def merge_downloaded(
|
||||||
|
track: AnyTrack,
|
||||||
|
ctx: DownloadContext,
|
||||||
|
label: str,
|
||||||
|
store: SegmentStore,
|
||||||
|
init: bytes | None,
|
||||||
|
append: Callable[[BinaryIO, Path], None],
|
||||||
|
prepare: Callable[[list[Path]], None] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Merge the segment files of ctx.save_dir into ctx.save_path in name order after the download.
|
||||||
|
|
||||||
|
The init heads the output, `prepare` gets the segment files before the first write, and the merge removes each
|
||||||
|
segment file after it appends it. A missing segment directory, or one with no segment file, raises
|
||||||
|
FileNotFoundError.
|
||||||
|
"""
|
||||||
|
save_dir = ctx.save_dir
|
||||||
|
event = f"manifest_{label.lower()}_download"
|
||||||
|
context = {
|
||||||
|
"track_id": getattr(track, "id", None),
|
||||||
|
"track_type": track.__class__.__name__,
|
||||||
|
"save_dir": str(save_dir),
|
||||||
|
"downloader": "requests",
|
||||||
|
}
|
||||||
|
if not save_dir.exists():
|
||||||
|
error_msg = f"Output directory does not exist: {save_dir}"
|
||||||
|
log_event(
|
||||||
|
f"{event}_output_missing",
|
||||||
|
level="ERROR",
|
||||||
|
message=error_msg,
|
||||||
|
context={**context, "save_path": str(ctx.save_path)},
|
||||||
|
)
|
||||||
|
raise FileNotFoundError(error_msg)
|
||||||
|
|
||||||
|
store.merging()
|
||||||
|
segment_files = [x for x in sorted(save_dir.iterdir()) if x.is_file()]
|
||||||
|
log_event(
|
||||||
|
f"{event}_complete",
|
||||||
|
level="DEBUG",
|
||||||
|
message=f"{label} download complete, preparing to merge",
|
||||||
|
context={
|
||||||
|
**context,
|
||||||
|
"segments_found": len(segment_files),
|
||||||
|
"segment_files": [f.name for f in segment_files[:10]],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if not segment_files:
|
||||||
|
error_msg = f"No segment files found in output directory: {save_dir}"
|
||||||
|
log_event(
|
||||||
|
f"{event}_no_segments",
|
||||||
|
level="ERROR",
|
||||||
|
message=error_msg,
|
||||||
|
context={**context, "directory_contents": [str(p) for p in save_dir.iterdir()]},
|
||||||
|
)
|
||||||
|
raise FileNotFoundError(error_msg)
|
||||||
|
|
||||||
|
if prepare:
|
||||||
|
prepare(segment_files)
|
||||||
|
ctx.progress(downloaded="Merging", completed=0, total=len(segment_files))
|
||||||
|
with open(ctx.save_path, "wb") as f:
|
||||||
|
if init:
|
||||||
|
f.write(init)
|
||||||
|
for segment_file in segment_files:
|
||||||
|
append(f, segment_file)
|
||||||
|
with suppress(OSError):
|
||||||
|
segment_file.unlink()
|
||||||
|
ctx.progress(advance=1)
|
||||||
|
|
||||||
|
|
||||||
def check_decrypted(track: AnyTrack, path: Path, drm: DRM_T | None) -> None:
|
def check_decrypted(track: AnyTrack, path: Path, drm: DRM_T | None) -> None:
|
||||||
"""Raise if a fragment of `path` still carries encryption, and mark the track for a repack when its moov does.
|
"""Raise if a fragment of `path` still carries encryption, and mark the track for a repack when its moov does.
|
||||||
|
|
||||||
@@ -355,4 +424,5 @@ __all__ = (
|
|||||||
"fetch_segments",
|
"fetch_segments",
|
||||||
"license_drm",
|
"license_drm",
|
||||||
"licensing",
|
"licensing",
|
||||||
|
"merge_downloaded",
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user