forked from kenzuya/unshackle
feat(dl): add --sample and --include-sample
--sample downloads only a time window of a title (default 120-180 s) and cuts the mux to it. --include-sample cuts a 60 s sample from a finished file. Both write to a Sample folder with a SAMPLE tag on the filename
This commit is contained in:
@@ -418,6 +418,15 @@ def perform_download(
|
||||
if params.get("export"):
|
||||
params["export"] = bool(params["export"])
|
||||
|
||||
sample_raw = params.get("sample")
|
||||
if sample_raw is not None:
|
||||
from unshackle.core.utils.click_types import SAMPLE_RANGE
|
||||
|
||||
try:
|
||||
params["sample"] = SAMPLE_RANGE.convert(sample_raw, None, None)
|
||||
except click.BadParameter as exc:
|
||||
raise Exception(f"Invalid sample parameter: {exc}")
|
||||
|
||||
slow_raw = params.get("slow")
|
||||
if slow_raw is not None and not isinstance(slow_raw, tuple):
|
||||
if isinstance(slow_raw, bool):
|
||||
@@ -633,6 +642,8 @@ def perform_download(
|
||||
no_folder=params.get("no_folder", False),
|
||||
no_source=params.get("no_source", False),
|
||||
no_mux=params.get("no_mux", False),
|
||||
sample=params.get("sample"),
|
||||
include_sample=params.get("include_sample", False),
|
||||
workers=params.get("workers"),
|
||||
adaptive_workers=params.get("adaptive_workers", False),
|
||||
download_processes=params.get("download_processes", 1),
|
||||
|
||||
@@ -92,6 +92,8 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
||||
"no_folder": False,
|
||||
"no_source": False,
|
||||
"no_mux": False,
|
||||
"sample": None,
|
||||
"include_sample": False,
|
||||
"workers": None,
|
||||
"adaptive_workers": False,
|
||||
"download_processes": 1,
|
||||
@@ -1831,6 +1833,16 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
except APIError as e:
|
||||
return e.message
|
||||
|
||||
if data.get("sample") is not None:
|
||||
from unshackle.core.utils.click_types import SAMPLE_RANGE
|
||||
|
||||
try:
|
||||
SAMPLE_RANGE.convert(data["sample"], None, None)
|
||||
except click.BadParameter:
|
||||
return "sample must be true or a 'START-END' window in seconds, such as '60-120'."
|
||||
if data.get("sample") and data.get("include_sample"):
|
||||
return "sample and include_sample cannot be used together."
|
||||
|
||||
# The serve user would create and write any directory a client names; keep it under downloads.
|
||||
if data.get("output_dir"):
|
||||
root = config.directories.downloads.resolve()
|
||||
|
||||
@@ -1005,6 +1005,14 @@ async def download(request: web.Request) -> web.Response:
|
||||
no_mux:
|
||||
type: boolean
|
||||
description: Do not mux tracks into a container file (default - false)
|
||||
include_sample:
|
||||
type: boolean
|
||||
description: Also cut a 60 second sample from each muxed file into a Sample folder next to it (default - false)
|
||||
sample:
|
||||
oneOf:
|
||||
- type: boolean
|
||||
- type: string
|
||||
description: Download a short sample and write it to a Sample folder. `true` for 60 seconds from 2 minutes in, or a `"START-END"` string in seconds (e.g., `"0-60"`) (default - null)
|
||||
workers:
|
||||
type: integer
|
||||
description: Max workers/threads per track download (default - None)
|
||||
|
||||
@@ -193,6 +193,7 @@ class Config:
|
||||
# mask local base dirs (install root/venv/home) in logged paths; False shows full paths
|
||||
self.redact_paths: bool = kwargs.get("redact_paths", True)
|
||||
self.continue_downloads: bool = kwargs.get("continue_downloads", False)
|
||||
self.sample: Optional[tuple[int, int]] = None
|
||||
self.post_scripts: list = kwargs.get("post_scripts") or []
|
||||
|
||||
self.language_tags: dict = kwargs.get("language_tags") or {}
|
||||
|
||||
@@ -3,6 +3,8 @@ from typing import TypeVar, Union
|
||||
|
||||
DOWNLOAD_CANCELLED = Event()
|
||||
DOWNLOAD_LICENCE_ONLY = Event()
|
||||
|
||||
DEFAULT_SAMPLE = (120, 180)
|
||||
DOWNLOAD_ALL_DRM = Event()
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,11 @@ from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
|
||||
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, assert_fragments_decrypted
|
||||
from unshackle.core.tracks.track import (
|
||||
DRM_PREFERENCE_TYPES,
|
||||
assert_fragments_decrypted,
|
||||
parse_sidx,
|
||||
)
|
||||
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils.redact import safe_display_url
|
||||
from unshackle.core.utils.xml import load_xml
|
||||
@@ -458,6 +462,7 @@ class DASH:
|
||||
track_url=track.url,
|
||||
session=session,
|
||||
probe_kid=period_idx == 0,
|
||||
window=config.sample,
|
||||
)
|
||||
|
||||
if period_idx == 0:
|
||||
@@ -471,12 +476,20 @@ class DASH:
|
||||
seen_segments.add(seg)
|
||||
segments.append(seg)
|
||||
segment_durations.extend(p_durations)
|
||||
# ponytail: a sample comes from the first content period only; map the window across
|
||||
# periods if a manifest with a short first period needs it
|
||||
if config.sample and segments:
|
||||
break
|
||||
|
||||
if not segments:
|
||||
log.error("Could not find a way to get segments from this MPD manifest.")
|
||||
log.debug(track.url)
|
||||
sys.exit(1)
|
||||
|
||||
if config.sample and not segment_durations and not isinstance(track, Subtitle):
|
||||
log.error("--sample cannot cut this track: the manifest gives it as one file with no segment index.")
|
||||
sys.exit(1)
|
||||
|
||||
# TODO: Should we floor/ceil/round, or is int() ok?
|
||||
track.data["dash"]["timescale"] = int(segment_timescale)
|
||||
track.data["dash"]["segment_durations"] = segment_durations
|
||||
@@ -533,7 +546,7 @@ class DASH:
|
||||
# When every segment is a byte range of one parent resource and init is its [0, len)
|
||||
# prefix, the whole resource is itself a valid MP4, so one direct download to save_path
|
||||
# replaces the per-segment files, init write and merge pass.
|
||||
collapse_single_url = DASH.collapsible_single_url(
|
||||
collapse_single_url = not config.sample and DASH.collapsible_single_url(
|
||||
isinstance(track, Subtitle),
|
||||
segments,
|
||||
len(init_data) if init_data is not None else None,
|
||||
@@ -753,6 +766,26 @@ class DASH:
|
||||
|
||||
progress(downloaded="Downloaded")
|
||||
|
||||
@staticmethod
|
||||
def find_segment_element(name: str, adaptation_set: Element, representation: Element) -> Optional[Element]:
|
||||
"""Find a segment description element on the representation, or else on its adaptation set."""
|
||||
element = representation.find(name)
|
||||
return element if element is not None else adaptation_set.find(name)
|
||||
|
||||
@staticmethod
|
||||
def has_segment_timing(track: AnyTrack) -> bool:
|
||||
"""Return False when the manifest gives the track as one file with no index, so a sample cannot cut it."""
|
||||
dash = track.data.get("dash") or {}
|
||||
representation, adaptation_set = dash.get("representation"), dash.get("adaptation_set")
|
||||
if representation is None or adaptation_set is None:
|
||||
return True
|
||||
segment_base = DASH.find_segment_element("SegmentBase", adaptation_set, representation)
|
||||
return (
|
||||
DASH.merge_segment_templates(adaptation_set, representation) is not None
|
||||
or DASH.find_segment_element("SegmentList", adaptation_set, representation) is not None
|
||||
or (segment_base is not None and bool(segment_base.get("indexRange")))
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def collapsible_single_url(
|
||||
is_subtitle: bool,
|
||||
@@ -844,6 +877,7 @@ class DASH:
|
||||
track_url: str,
|
||||
session: Union[Session, RnetSession],
|
||||
probe_kid: bool = True,
|
||||
window: Optional[tuple[int, int]] = None,
|
||||
) -> tuple[
|
||||
Optional[bytes],
|
||||
list[tuple[str, Optional[str]]],
|
||||
@@ -877,13 +911,9 @@ class DASH:
|
||||
|
||||
segment_template = DASH.merge_segment_templates(adaptation_set, representation)
|
||||
|
||||
segment_list = representation.find("SegmentList")
|
||||
if segment_list is None:
|
||||
segment_list = adaptation_set.find("SegmentList")
|
||||
segment_list = DASH.find_segment_element("SegmentList", adaptation_set, representation)
|
||||
|
||||
segment_base = representation.find("SegmentBase")
|
||||
if segment_base is None:
|
||||
segment_base = adaptation_set.find("SegmentBase")
|
||||
segment_base = DASH.find_segment_element("SegmentBase", adaptation_set, representation)
|
||||
|
||||
segments: list[tuple[str, Optional[str]]] = []
|
||||
segment_timescale: float = 0
|
||||
@@ -930,6 +960,10 @@ class DASH:
|
||||
segment_durations.append(current_time)
|
||||
current_time += int(s.get("d"))
|
||||
|
||||
keep = track.sample_slice(segment_durations, segment_timescale, window) if window else slice(None)
|
||||
start_number += keep.start or 0
|
||||
segment_durations = segment_durations[keep]
|
||||
|
||||
if not end_number:
|
||||
end_number = start_number + len(segment_durations) - 1
|
||||
|
||||
@@ -956,7 +990,11 @@ class DASH:
|
||||
segment_count = math.ceil(period_duration / (segment_duration / segment_timescale))
|
||||
end_number = start_number + segment_count - 1
|
||||
|
||||
for s in range(start_number, end_number + 1):
|
||||
numbers = range(start_number, end_number + 1)
|
||||
if window:
|
||||
starts = [n * segment_duration for n in range(len(numbers))]
|
||||
numbers = numbers[track.sample_slice(starts, segment_timescale, window)]
|
||||
for s in numbers:
|
||||
segments.append(
|
||||
(
|
||||
DASH.replace_fields(
|
||||
@@ -994,6 +1032,10 @@ class DASH:
|
||||
track_kid = track.get_key_id(init_data)
|
||||
|
||||
segment_urls = segment_list.findall("SegmentURL")
|
||||
list_duration = float(segment_list.get("duration") or 0)
|
||||
if window and list_duration:
|
||||
starts = [n * list_duration for n in range(len(segment_urls))]
|
||||
segment_urls = segment_urls[track.sample_slice(starts, segment_timescale, window)]
|
||||
for segment_url in segment_urls:
|
||||
media_url = segment_url.get("media")
|
||||
if not media_url:
|
||||
@@ -1022,7 +1064,20 @@ class DASH:
|
||||
if total_size:
|
||||
media_range = f"{len(init_data)}-{total_size}"
|
||||
|
||||
segments.append((rep_base_url, media_range))
|
||||
subsegments: list[tuple[int, int, int]] = []
|
||||
index_range = segment_base.get("indexRange")
|
||||
if window and index_range and not isinstance(track, Subtitle):
|
||||
res = session.get(url=rep_base_url, headers={"Range": f"bytes={index_range}"})
|
||||
res.raise_for_status()
|
||||
segment_timescale, subsegments = parse_sidx(res.content, int(index_range.split("-")[0]))
|
||||
|
||||
if subsegments:
|
||||
segment_durations = [time for time, _, _ in subsegments]
|
||||
keep = track.sample_slice(segment_durations, segment_timescale, window)
|
||||
segment_durations = segment_durations[keep]
|
||||
segments.extend((rep_base_url, f"{first}-{last}") for _, first, last in subsegments[keep])
|
||||
else:
|
||||
segments.append((rep_base_url, media_range))
|
||||
elif rep_base_url:
|
||||
segments.append((rep_base_url, None))
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import ExitStack, closing
|
||||
from itertools import accumulate
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, Union
|
||||
from urllib.parse import urljoin, urlparse
|
||||
@@ -685,6 +686,12 @@ class HLS:
|
||||
)
|
||||
hls_data["unwanted_segments"] = [s.absolute_uri for s in unwanted_segments]
|
||||
|
||||
if config.sample:
|
||||
content = [segment for segment in master.segments if segment not in unwanted_segments]
|
||||
starts = list(accumulate((segment.duration or 0 for segment in content[:-1]), initial=0.0))
|
||||
del content[track.sample_slice(starts, window=config.sample)]
|
||||
unwanted_segments += content
|
||||
|
||||
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
|
||||
if track.drm:
|
||||
session_drm = track.get_drm_for_cdm(cdm)
|
||||
@@ -796,17 +803,17 @@ class HLS:
|
||||
|
||||
range_offset = 0
|
||||
for segment in master.segments:
|
||||
if segment.byterange:
|
||||
byte_range = HLS.calculate_byte_range(segment.byterange, range_offset)
|
||||
range_offset = int(byte_range.split("-")[1]) + 1
|
||||
else:
|
||||
byte_range = None
|
||||
|
||||
if segment in unwanted_segments:
|
||||
continue
|
||||
|
||||
segment_durations.append(int(segment.duration))
|
||||
|
||||
if segment.byterange:
|
||||
byte_range = HLS.calculate_byte_range(segment.byterange, range_offset)
|
||||
range_offset = int(byte_range.split("-")[0])
|
||||
else:
|
||||
byte_range = None
|
||||
|
||||
urls.append(
|
||||
{
|
||||
"url": urljoin(segment.base_uri, segment.uri),
|
||||
|
||||
@@ -259,6 +259,7 @@ class ISM:
|
||||
)
|
||||
|
||||
track_urls: list[str] = []
|
||||
track_times: list[int] = []
|
||||
fragment_time = 0
|
||||
fragments = stream_index.findall("c")
|
||||
# MS-SSTR UrlPattern; regex over str.format so {Bitrate}/{start_time}
|
||||
@@ -276,6 +277,7 @@ class ISM:
|
||||
first_time = int(fragments[0].get("t") or 0)
|
||||
if first_time != 0:
|
||||
track_urls.append(re.sub(r"\{start[ _]time\}", "0", url_template))
|
||||
track_times.append(first_time)
|
||||
|
||||
for idx, frag in enumerate(fragments):
|
||||
fragment_time = int(frag.get("t", fragment_time))
|
||||
@@ -292,6 +294,7 @@ class ISM:
|
||||
duration_frag = (next_time - fragment_time) // repeat
|
||||
for _ in range(repeat):
|
||||
track_urls.append(re.sub(r"\{start[ _]time\}", str(fragment_time), url_template))
|
||||
track_times.append(fragment_time)
|
||||
fragment_time += duration_frag
|
||||
|
||||
track_id = hashlib.md5(
|
||||
@@ -312,6 +315,8 @@ class ISM:
|
||||
"stream_index": stream_index,
|
||||
"quality_level": ql,
|
||||
"segments": track_urls,
|
||||
"segment_times": track_times,
|
||||
"timescale": int(stream_index.get("TimeScale") or self.manifest.get("TimeScale") or 10000000),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,6 +419,9 @@ class ISM:
|
||||
session.proxies.update({"all": proxy})
|
||||
|
||||
segments: list[str] = track.data["ism"]["segments"]
|
||||
segment_times: list[int] = track.data["ism"].get("segment_times") or []
|
||||
if segment_times:
|
||||
segments = segments[track.sample_slice(segment_times, track.data["ism"]["timescale"], config.sample)]
|
||||
|
||||
session_drm = None
|
||||
if track.drm:
|
||||
|
||||
@@ -15,6 +15,7 @@ import click
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DEFAULT_SAMPLE
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.service_repo import DirtyServiceRepo, head, is_repo_spec, refresh_repo, resolve_service_repo
|
||||
from unshackle.core.utilities import import_module_by_path
|
||||
@@ -360,16 +361,17 @@ class Services(click.Group):
|
||||
super().format_help(ctx, formatter)
|
||||
|
||||
def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
|
||||
"""Preprocess ``--slow`` so it can take an optional range value before Click parses the arguments."""
|
||||
"""Preprocess ``--slow`` and ``--sample`` so each can take an optional range value before Click parses."""
|
||||
defaults = {"--slow": "60-120", "--sample": "{}-{}".format(*DEFAULT_SAMPLE)}
|
||||
processed = []
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--slow":
|
||||
if args[i] in defaults:
|
||||
if i + 1 < len(args) and re.match(r"^\d+-\d+$", args[i + 1]):
|
||||
processed.append(f"--slow={args[i + 1]}")
|
||||
processed.append(f"{args[i]}={args[i + 1]}")
|
||||
i += 2
|
||||
else:
|
||||
processed.append("--slow=60-120")
|
||||
processed.append(f"{args[i]}={defaults[args[i]]}")
|
||||
i += 1
|
||||
else:
|
||||
processed.append(args[i])
|
||||
|
||||
@@ -9,7 +9,7 @@ from enum import Enum
|
||||
from functools import partial
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable, Optional, Union
|
||||
from typing import Any, Callable, Iterable, Optional, Sequence, Union
|
||||
|
||||
import pycaption
|
||||
import requests
|
||||
@@ -1001,6 +1001,32 @@ class Subtitle(Track):
|
||||
|
||||
return captions, language
|
||||
|
||||
def sample_slice(
|
||||
self, starts: Sequence[float], timescale: float = 1, window: Optional[tuple[int, int]] = None
|
||||
) -> slice:
|
||||
"""Keep every segment: ``trim`` cuts a subtitle by its cue times after the download."""
|
||||
return slice(None)
|
||||
|
||||
def trim(self, start: float, end: float) -> bool:
|
||||
"""Keep the cues between ``start`` and ``end`` seconds and move them to start at zero.
|
||||
|
||||
Returns False and leaves the file whole when pysubs2 cannot read or write its format.
|
||||
"""
|
||||
import pysubs2
|
||||
|
||||
low, high = round(start * 1000), round(end * 1000)
|
||||
try:
|
||||
subs = pysubs2.load(str(self.path), encoding="utf-8")
|
||||
subs.events = [event for event in subs.events if event.end > low and event.start < high]
|
||||
for event in subs.events:
|
||||
event.start = max(event.start, low) - low
|
||||
event.end = min(event.end, high) - low
|
||||
subs.save(str(self.path))
|
||||
except (pysubs2.exceptions.Pysubs2Error, UnicodeDecodeError):
|
||||
return False
|
||||
self.sample_start = start
|
||||
return True
|
||||
|
||||
def strip_hearing_impaired(self) -> None:
|
||||
"""
|
||||
Remove the SDH captions.
|
||||
|
||||
@@ -3,18 +3,23 @@ import html
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
from bisect import bisect_left, bisect_right
|
||||
from collections import defaultdict
|
||||
from copy import copy
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable, Optional, Union
|
||||
from typing import Any, Callable, Iterable, Optional, Sequence, Union
|
||||
from uuid import UUID
|
||||
from zlib import crc32
|
||||
|
||||
import click
|
||||
from construct import ConstructError
|
||||
from langcodes import Language
|
||||
from pymp4.parser import Box
|
||||
from requests import Response, Session
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
|
||||
@@ -364,6 +369,31 @@ def assert_fragments_decrypted(path: Path) -> None:
|
||||
)
|
||||
|
||||
|
||||
SAMPLE_PROBE_BYTES = 64 * 1024
|
||||
SAMPLE_PROBE_LIMIT = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def parse_sidx(data: bytes, offset: int) -> tuple[int, list[tuple[int, int, int]]]:
|
||||
"""Read a ``sidx`` box that starts at byte ``offset`` of its file.
|
||||
|
||||
Returns the timescale and one (start time, first byte, last byte) for each subsegment. The list
|
||||
is empty when the box is not a ``sidx`` or when it points at more indexes and not at media.
|
||||
"""
|
||||
try:
|
||||
box = Box.parse(data)
|
||||
except ConstructError:
|
||||
return 0, []
|
||||
if box.type != b"sidx" or any(reference.reference_type != "MEDIA" for reference in box.references):
|
||||
return 0, []
|
||||
start, byte = box.earliest_presentation_time, offset + box.end + box.first_offset
|
||||
subsegments: list[tuple[int, int, int]] = []
|
||||
for reference in box.references:
|
||||
subsegments.append((start, byte, byte + reference.referenced_size - 1))
|
||||
start += reference.segment_duration
|
||||
byte += reference.referenced_size
|
||||
return box.timescale, subsegments
|
||||
|
||||
|
||||
@dataclass
|
||||
class DownloadContext:
|
||||
"""Shared arguments passed to each manifest's ``download_track``."""
|
||||
@@ -396,6 +426,8 @@ class Track:
|
||||
DASH = 3 # https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
|
||||
ISM = 4 # https://learn.microsoft.com/en-us/silverlight/smooth-streaming
|
||||
|
||||
sample_tail = 0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url: Union[str, list[str]],
|
||||
@@ -497,6 +529,77 @@ class Track:
|
||||
|
||||
# TODO: Currently using OnFoo event naming, change to just segment_filter
|
||||
self.OnSegmentFilter: Optional[Callable] = None
|
||||
self.sample_start: float = 0.0
|
||||
self.sample_bytes: Optional[tuple[bytes, str]] = None
|
||||
|
||||
def sample_slice(
|
||||
self, starts: Sequence[float], timescale: float = 1, window: Optional[tuple[int, int]] = None
|
||||
) -> slice:
|
||||
"""Return the slice of segments that hold ``window``, from the start time of each segment.
|
||||
|
||||
Sets ``sample_start`` to the start time of the first kept segment, in seconds. A video keeps
|
||||
``sample_tail`` segments after the window: mkvmerge ends the cut only at a video keyframe, and
|
||||
with no such keyframe the audio and the subtitles continue to their own end.
|
||||
"""
|
||||
self.sample_start = 0.0
|
||||
if not window or not starts:
|
||||
return slice(None)
|
||||
low, high = (starts[0] + seconds * timescale for seconds in window)
|
||||
if low > starts[-1] and len(starts) > 1:
|
||||
raise click.ClickException(
|
||||
"The title ends before the sample window starts. Use --sample START-END with an earlier window."
|
||||
)
|
||||
first = max(bisect_right(starts, low) - 1, 0)
|
||||
self.sample_start = (starts[first] - starts[0]) / timescale
|
||||
return slice(first, max(bisect_left(starts, high) + self.sample_tail, first + 1))
|
||||
|
||||
def sample_byte_range(self, session: Union[Session, "RnetSession"]) -> Optional[tuple[bytes, str]]:
|
||||
"""Find the bytes of a one-file track that hold the sample window.
|
||||
|
||||
Reads the start of the file for a ``sidx`` box. Returns the bytes before that box, which hold
|
||||
the init data, and the byte range of the window. Returns None when the file has no such index.
|
||||
"""
|
||||
if self.sample_bytes or not isinstance(self.url, str):
|
||||
return self.sample_bytes
|
||||
head = b""
|
||||
|
||||
def read_to(end: int) -> None:
|
||||
nonlocal head
|
||||
if end > len(head):
|
||||
res = session.get(self.url, headers={"Range": f"bytes={len(head)}-{end - 1}"})
|
||||
if res.ok:
|
||||
head += res.content
|
||||
|
||||
pos = 0
|
||||
while pos < SAMPLE_PROBE_LIMIT:
|
||||
if pos + 8 > len(head):
|
||||
read_to(pos + SAMPLE_PROBE_BYTES)
|
||||
if pos + 8 > len(head):
|
||||
return None
|
||||
size, kind = struct.unpack(">I4s", head[pos : pos + 8])
|
||||
if size < 8:
|
||||
return None
|
||||
if kind != b"sidx":
|
||||
pos += size
|
||||
continue
|
||||
read_to(pos + size)
|
||||
timescale, subsegments = parse_sidx(head[pos : pos + size], pos)
|
||||
if not subsegments:
|
||||
return None
|
||||
kept = subsegments[self.sample_slice([start for start, _, _ in subsegments], timescale, config.sample)]
|
||||
self.sample_bytes = head[:pos], f"{kept[0][1]}-{kept[-1][2]}"
|
||||
return self.sample_bytes
|
||||
return None
|
||||
|
||||
def can_sample(self, session: Union[Session, "RnetSession"]) -> bool:
|
||||
"""Return False when a sample cannot cut this track, because it is one file with no segment index."""
|
||||
if self.descriptor == self.Descriptor.URL:
|
||||
return bool(self.sample_byte_range(session))
|
||||
if self.descriptor == self.Descriptor.DASH:
|
||||
from unshackle.core.manifests import DASH
|
||||
|
||||
return DASH.has_segment_timing(self)
|
||||
return True
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{name}({items})".format(
|
||||
@@ -741,8 +844,17 @@ class Track:
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
else:
|
||||
sample_range = None
|
||||
if config.sample and track_type in ("Video", "Audio"):
|
||||
sample_range = self.sample_byte_range(dl_session)
|
||||
if not sample_range:
|
||||
raise click.ClickException(
|
||||
"--sample cannot cut this track: it is one file with no segment index."
|
||||
)
|
||||
for status_update in self.downloader(
|
||||
urls=self.url,
|
||||
urls=[{"url": self.url, "headers": {"Range": f"bytes={sample_range[1]}"}}]
|
||||
if sample_range
|
||||
else self.url,
|
||||
output_dir=save_path.parent,
|
||||
filename=save_path.name,
|
||||
headers=dl_session.headers,
|
||||
@@ -760,6 +872,14 @@ class Track:
|
||||
status_update["downloaded"] = f"URL {downloaded}"
|
||||
progress(**status_update)
|
||||
|
||||
if sample_range:
|
||||
media_path = save_path.with_name(f"{save_path.name}.media")
|
||||
save_path.replace(media_path)
|
||||
with save_path.open("wb") as joined, media_path.open("rb") as media:
|
||||
joined.write(sample_range[0])
|
||||
shutil.copyfileobj(media, joined)
|
||||
media_path.unlink()
|
||||
|
||||
self.path = save_path
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=self)
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ from unshackle.core.utilities import (
|
||||
valid_language,
|
||||
)
|
||||
from unshackle.core.utils.collections import as_list, flatten
|
||||
from unshackle.core.utils.subprocess import run_step
|
||||
|
||||
MP4BOX_PROGRESS = re.compile(r"\((\d{1,3})/100\)")
|
||||
MP4BOX_OPEN_FAILED = re.compile(r"error while opening|Error opening file|Invalid IsoMedia File", re.I)
|
||||
@@ -495,6 +496,11 @@ class Tracks:
|
||||
selected.append(track)
|
||||
return selected
|
||||
|
||||
@property
|
||||
def sample_base(self) -> float:
|
||||
"""The earliest ``sample_start`` of the video and audio tracks, which a sample mux uses as time zero."""
|
||||
return min((t.sample_start for t in (*self.videos, *self.audio)), default=0.0)
|
||||
|
||||
def _mux_mp4(
|
||||
self,
|
||||
title: str,
|
||||
@@ -524,6 +530,7 @@ class Tracks:
|
||||
progress = progress or partial(lambda **kwargs: None)
|
||||
|
||||
cl = [str(mp4box)]
|
||||
sample_base = self.sample_base
|
||||
names: list[str] = []
|
||||
cleaned: list[Path] = []
|
||||
track_id = 0
|
||||
@@ -557,7 +564,8 @@ class Tracks:
|
||||
elif candidate.exists():
|
||||
candidate.unlink()
|
||||
|
||||
cl.extend(["-add", f"{source}:lang={track.language}"])
|
||||
delay = round((track.sample_start - sample_base) * 1000) if config.sample else 0
|
||||
cl.extend(["-add", f"{source}:lang={track.language}" + (f":delay={delay}" if delay else "")])
|
||||
name = "" if isinstance(track, Video) else (track.get_track_name() or "")
|
||||
if name:
|
||||
names.extend(["-name", f"{track_id}={name}"])
|
||||
@@ -568,7 +576,7 @@ class Tracks:
|
||||
cl.extend(names)
|
||||
|
||||
chapters_path = None
|
||||
if self.chapters:
|
||||
if self.chapters and not config.sample:
|
||||
chapters_path = config.directories.temp / config.filenames.chapters.format(
|
||||
title=sanitize_filename(title), random=f"{self.chapters.id}_{os.getpid()}_{threading.get_ident()}"
|
||||
)
|
||||
@@ -632,6 +640,19 @@ class Tracks:
|
||||
returncode = p.wait()
|
||||
if returncode < 2 and any(MP4BOX_OPEN_FAILED.search(line) for line in errors):
|
||||
returncode = 2
|
||||
if config.sample and returncode == 0:
|
||||
start, end = (seconds - sample_base for seconds in config.sample)
|
||||
cut_path = output_path.with_suffix(".cut.mp4")
|
||||
try:
|
||||
run_step(
|
||||
[mp4box, "-splitx", f"{start:.3f}:{end:.3f}", output_path, "-out", cut_path],
|
||||
output=cut_path,
|
||||
label="MP4Box sample cut",
|
||||
)
|
||||
os.replace(cut_path, output_path)
|
||||
except RuntimeError as e:
|
||||
returncode = 2
|
||||
errors.append(f"MP4Box could not cut the sample window: {e}")
|
||||
mux_duration_ms = round((time.monotonic() - mux_start_time) * 1000, 1)
|
||||
output_size = output_path.stat().st_size if output_path.exists() else 0
|
||||
|
||||
@@ -729,6 +750,16 @@ class Tracks:
|
||||
"--no-date", # remove dates from the output for security
|
||||
]
|
||||
|
||||
sample_base = self.sample_base
|
||||
|
||||
def sample_sync(start: float) -> list[str]:
|
||||
shift = round((start - sample_base) * 1000)
|
||||
return ["--sync", f"0:{shift}"] if config.sample and shift else []
|
||||
|
||||
if config.sample:
|
||||
start, end = (seconds - sample_base for seconds in config.sample)
|
||||
cl.extend(["--split", f"parts:{start:.3f}s-{end:.3f}s"])
|
||||
|
||||
if config.muxing.get("set_title", True):
|
||||
cl.extend(["--title", title])
|
||||
|
||||
@@ -782,6 +813,7 @@ class Tracks:
|
||||
f"0:{vt.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none",
|
||||
*sample_sync(vt.sample_start),
|
||||
]
|
||||
|
||||
# Add FPS fix if needed (typically for hybrid mode to prevent sync issues)
|
||||
@@ -839,6 +871,7 @@ class Tracks:
|
||||
f"0:{at.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none",
|
||||
*sample_sync(at.sample_start),
|
||||
"(",
|
||||
str(at.path),
|
||||
")",
|
||||
@@ -872,6 +905,7 @@ class Tracks:
|
||||
f"0:{st.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none",
|
||||
*sample_sync(st.sample_start),
|
||||
"(",
|
||||
str(st.path),
|
||||
")",
|
||||
@@ -883,6 +917,8 @@ class Tracks:
|
||||
title=sanitize_filename(title), random=f"{self.chapters.id}_{os.getpid()}_{threading.get_ident()}"
|
||||
)
|
||||
self.chapters.dump(chapters_path, fallback_name=config.chapter_fallback_name)
|
||||
if config.sample and sample_base:
|
||||
cl.extend(["--chapter-sync", str(round(-sample_base * 1000))])
|
||||
cl.extend(["--chapter-charset", "UTF-8", "--chapters", str(chapters_path)])
|
||||
else:
|
||||
chapters_path = None
|
||||
|
||||
@@ -20,6 +20,8 @@ from unshackle.core.utils.subprocess import log_tool_run
|
||||
|
||||
|
||||
class Video(Track):
|
||||
sample_tail = 1
|
||||
|
||||
class Codec(str, Enum):
|
||||
AVC = "H.264"
|
||||
HEVC = "H.265"
|
||||
|
||||
@@ -6,6 +6,7 @@ import click
|
||||
from click.shell_completion import CompletionItem
|
||||
from pywidevine.cdm import Cdm as WidevineCdm
|
||||
|
||||
from unshackle.core.constants import DEFAULT_SAMPLE
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
@@ -505,6 +506,26 @@ class SlowDelayRange(click.ParamType):
|
||||
return (low, high)
|
||||
|
||||
|
||||
class SampleRange(click.ParamType):
|
||||
"""Parses a sample window string like '60-120' into a tuple of (start, end) seconds."""
|
||||
|
||||
name = "sample_range"
|
||||
|
||||
def convert(
|
||||
self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]
|
||||
) -> Optional[tuple[int, int]]:
|
||||
if isinstance(value, bool):
|
||||
return DEFAULT_SAMPLE if value else None
|
||||
if isinstance(value, (list, tuple)) and len(value) == 2:
|
||||
value = f"{value[0]}-{value[1]}"
|
||||
|
||||
match = re.match(r"^(\d+)-(\d+)$", str(value))
|
||||
if not match or int(match.group(1)) >= int(match.group(2)):
|
||||
self.fail(f"'{value}' is not a valid sample window. Use format: START-END (e.g., 60-120)", param, ctx)
|
||||
|
||||
return (int(match.group(1)), int(match.group(2)))
|
||||
|
||||
|
||||
SEASON_RANGE = SeasonRange()
|
||||
LANGUAGE_RANGE = LanguageRange()
|
||||
QUALITY_LIST = QualityList()
|
||||
@@ -512,3 +533,4 @@ AUDIO_CODEC_LIST = AudioCodecList(Audio.Codec)
|
||||
VIDEO_CODEC_LIST = MultipleVideoCodecChoice(Video.Codec)
|
||||
SUBTITLE_CODEC = SubtitleCodecChoice(Subtitle.Codec)
|
||||
SLOW_DELAY_RANGE = SlowDelayRange()
|
||||
SAMPLE_RANGE = SampleRange()
|
||||
|
||||
Reference in New Issue
Block a user