@boy-offi9-inc/tidepull 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -183,14 +183,14 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
183
183
  - No site-specific extractors are built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin
184
184
  - No DRM: protected streams (Widevine, PlayReady, FairPlay, encrypted DASH) are not supported and will not be
185
185
  - No circumvention: it cannot get past logins, paywalls or geo-blocks. With `--cookies` it only fetches what your own session can already see
186
- - Not implemented yet: SAMPLE-AES, fMP4 subtitle tracks (WebVTT segment playlists only), playlists from video sites (they need a plugin), a proxy option
186
+ - Not implemented yet: SAMPLE-AES, playlists from video sites (they need a plugin), a proxy option
187
187
  - Cookies are read-only: `Set-Cookie` responses are not stored
188
188
 
189
189
  ### Details
190
190
  | Area | Behavior |
191
191
  |---|---|
192
192
  | Direct files | resumable (`.part` + `Range`), retries with backoff |
193
- | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, `EXT-X-BYTERANGE` segments and ranged init maps, separate audio renditions, `SUBTITLES` renditions with `--write-subs` (WebVTT segments joined into one `.vtt` per language), time-range clipping with `--from SEC` / `--to SEC` (whole segments, partial overlaps included; DASH and live playlists are not clippable) |
193
+ | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, `EXT-X-BYTERANGE` segments and ranged init maps, separate audio renditions, `SUBTITLES` renditions with `--write-subs` (WebVTT segments joined into one `.vtt` per language; fMP4/WVTT segment playlists are converted to `.vtt` with absolute timestamps), time-range clipping with `--from SEC` / `--to SEC` (whole segments, partial overlaps included; DASH and live playlists are not clippable) |
194
194
  | HLS live (`--live`) | playlist refresh + append by media sequence, stops on `EXT-X-ENDLIST` / `--max-duration SEC` / `--max-segments N` / Ctrl-C (Ctrl-C keeps what was captured); AES-128 + fMP4 init maps supported mid-stream |
195
195
  | DASH VOD (`.mpd`), opt-in via `@boy-offi9-inc/tidepull/dash` (built into the CLI) | `SegmentTemplate` (`$Number%05d$`, `$Time$`, timelines, durations), `SegmentList`, single-file `SegmentBase`, nested `BaseURL`; multiple `Period`s merged by representation (fragments concatenated in order, init from the first period); encrypted (`ContentProtection`) representations are skipped, never decrypted |
196
196
  | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
@@ -22,9 +22,6 @@ export interface DownloadOpts {
22
22
  export declare function downloadHttp(url: string, dest: string, o: DownloadOpts & {
23
23
  resume: boolean;
24
24
  }): Promise<void>;
25
- export interface HlsOpts extends DownloadOpts {
26
- concurrency: number;
27
- }
28
25
  export interface SegmentRef {
29
26
  url: string;
30
27
  seq: number;
@@ -219,6 +219,8 @@ export async function downloadHls(url, dest, o) {
219
219
  return downloadSegments(segments, dest, o);
220
220
  }
221
221
  export async function downloadHlsLive(url, dest, o) {
222
+ if (o.from !== undefined || o.to !== undefined)
223
+ throw new TidepullError("Time-range clipping (--from/--to) only works on VOD playlists");
222
224
  const first = await o.http.text(url, { headers: o.headers, signal: o.signal });
223
225
  if (isMasterPlaylist(first.text))
224
226
  throw new TidepullError("Expected a media playlist, got a master playlist");
@@ -93,6 +93,10 @@ export async function downloadInfo(info, opts, ctx) {
93
93
  const limiter = opts.limitRate ? new RateLimiter(opts.limitRate) : undefined;
94
94
  const common = { http: ctx.http, headers: { ...f.http_headers, ...opts.headers }, signal: ctx.signal, limiter, onProgress };
95
95
  let ext = f.ext;
96
+ if (opts.from !== undefined || opts.to !== undefined) {
97
+ if (f.protocol !== "hls")
98
+ throw new TidepullError(`Time-range clipping (--from/--to) is only supported for HLS VOD downloads, not ${f.protocol}`);
99
+ }
96
100
  if (f.protocol === "hls")
97
101
  ({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency, live: opts.live, maxDuration: opts.maxDuration, maxSegments: opts.maxSegments, from: opts.from, to: opts.to }));
98
102
  else if (f.protocol === "dash")
@@ -2,6 +2,106 @@ import { createWriteStream } from "node:fs";
2
2
  import { rename, rm } from "node:fs/promises";
3
3
  import { TidepullError } from "./errors.js";
4
4
  import { isMasterPlaylist, parseMedia } from "./hls.js";
5
+ const CONTAINERS = new Set(["moov", "trak", "mdia", "minf", "stbl", "moof", "traf", "edts", "mvex"]);
6
+ function* boxes(buf, start = 0, end = buf.length) {
7
+ let off = start;
8
+ while (off + 8 <= end) {
9
+ const dv = new DataView(buf.buffer, buf.byteOffset + off, end - off);
10
+ let size = dv.getUint32(0);
11
+ const type = new TextDecoder().decode(buf.subarray(off + 4, off + 8));
12
+ let head = 8;
13
+ if (size === 1) {
14
+ size = Number(dv.getBigUint64(8));
15
+ head = 16;
16
+ }
17
+ if (size < head || off + size > end)
18
+ throw new TidepullError(`Corrupt fMP4 subtitle segment: bad '${type}' box size`);
19
+ const content = buf.subarray(off + head, off + size);
20
+ if (type === "stsd")
21
+ yield* boxes(content, 8, content.length);
22
+ else if (CONTAINERS.has(type))
23
+ yield* boxes(content, 0, content.length);
24
+ else
25
+ yield { type, content };
26
+ off += size;
27
+ }
28
+ }
29
+ const findBoxes = (buf, type) => [...boxes(buf)].filter((b) => b.type === type);
30
+ const u32 = (b, o) => new DataView(b.buffer, b.byteOffset + o).getUint32(0);
31
+ function readTimescale(buf) {
32
+ const mdhd = findBoxes(buf, "mdhd")[0];
33
+ if (!mdhd)
34
+ throw new TidepullError("fMP4 subtitle init segment has no mdhd box (no timescale)");
35
+ const v = mdhd.content[0];
36
+ const ts = v === 1 ? u32(mdhd.content, 20) : u32(mdhd.content, 12);
37
+ if (!ts)
38
+ throw new TidepullError("fMP4 subtitle init segment has a zero timescale; cannot derive cue times");
39
+ return ts;
40
+ }
41
+ function readSamples(buf) {
42
+ const truns = findBoxes(buf, "trun");
43
+ const mdats = findBoxes(buf, "mdat");
44
+ const tfdt = findBoxes(buf, "tfdt")[0];
45
+ if (!truns.length || !mdats.length)
46
+ throw new TidepullError("fMP4 subtitle segment has no trun/mdat boxes");
47
+ if (!tfdt)
48
+ throw new TidepullError("fMP4 subtitle segment has no tfdt box (no decode timestamp)");
49
+ const base = tfdt.content[0] === 1 ? Number(new DataView(tfdt.content.buffer, tfdt.content.byteOffset).getBigUint64(4)) : u32(tfdt.content, 4);
50
+ const pool = mdats.map((m) => m.content);
51
+ let cursor = 0;
52
+ const samples = [];
53
+ let tick = base;
54
+ for (const trun of truns) {
55
+ const c = trun.content;
56
+ const flags = (c[1] << 16) | (c[2] << 8) | c[3];
57
+ if (!(flags & 0x000100) || !(flags & 0x000200)) {
58
+ throw new TidepullError("fMP4 subtitle segment trun lacks per-sample durations/sizes; cannot extract cues");
59
+ }
60
+ const count = u32(c, 4);
61
+ let off = 8 + (flags & 0x000001 ? 4 : 0) + (flags & 0x000004 ? 4 : 0);
62
+ for (let i = 0; i < count; i++) {
63
+ const duration = u32(c, off);
64
+ const size = u32(c, off + 4);
65
+ off += 8 + (flags & 0x000400 ? 4 : 0) + (flags & 0x000800 ? 4 : 0);
66
+ const slice = new Uint8Array(size);
67
+ let got = 0;
68
+ while (got < size) {
69
+ if (cursor >= pool[0].length && pool.length > 1) {
70
+ pool.shift();
71
+ cursor = 0;
72
+ }
73
+ if (cursor + (size - got) > pool[0].length && pool.length === 1 && cursor >= pool[0].length) {
74
+ throw new TidepullError("fMP4 subtitle segment mdat is smaller than its trun describes");
75
+ }
76
+ const take = Math.min(size - got, pool[0].length - cursor);
77
+ if (take <= 0)
78
+ throw new TidepullError("fMP4 subtitle segment mdat is smaller than its trun describes");
79
+ slice.set(pool[0].subarray(cursor, cursor + take), got);
80
+ cursor += take;
81
+ got += take;
82
+ }
83
+ samples.push({ time: tick, duration, bytes: slice });
84
+ tick += duration;
85
+ }
86
+ }
87
+ return { base, samples };
88
+ }
89
+ function sampleContent(bytes) {
90
+ const texts = [];
91
+ let empty = false;
92
+ const td = new TextDecoder();
93
+ for (const b of boxes(bytes)) {
94
+ if (b.type === "vttc") {
95
+ const payl = findBoxes(b.content, "payl")[0];
96
+ if (payl)
97
+ texts.push(td.decode(payl.content).replace(/\u0000+$/, ""));
98
+ }
99
+ else if (b.type === "vtte") {
100
+ empty = true;
101
+ }
102
+ }
103
+ return { texts, empty };
104
+ }
5
105
  export async function downloadHlsSubtitles(url, dest, o) {
6
106
  const { text, finalUrl } = await o.http.text(url, { headers: o.headers, signal: o.signal });
7
107
  if (isMasterPlaylist(text))
@@ -13,27 +113,10 @@ export async function downloadHlsSubtitles(url, dest, o) {
13
113
  const out = createWriteStream(part);
14
114
  const write = (s) => new Promise((res, rej) => out.write(s, (e) => (e ? rej(e) : res())));
15
115
  try {
16
- let header = "";
17
- let lastMap;
18
- for (const seg of media.segments) {
19
- if (seg.map && seg.map !== lastMap) {
20
- out.destroy();
21
- await rm(part, { force: true });
22
- throw new TidepullError("fMP4 subtitle tracks (EXT-X-MAP) are not supported yet; only WebVTT segment playlists are");
23
- }
24
- const r = await o.http.request(seg.url, { headers: o.headers, signal: o.signal });
25
- if (!r.ok) {
26
- await r.body?.cancel();
27
- throw new TidepullError(`HTTP ${r.status} for subtitle segment ${seg.url}`);
28
- }
29
- const body = await r.text();
30
- if (!header) {
31
- header = body.slice(0, body.indexOf("\n\n") + 1);
32
- await write(header);
33
- }
34
- const cues = body.startsWith("WEBVTT") ? body.slice(body.indexOf("\n\n") + 2) : body;
35
- await write(cues.endsWith("\n") ? cues : cues + "\n");
36
- }
116
+ if (media.segments.some((s) => s.map))
117
+ await writeFmp4(media.segments, write, o);
118
+ else
119
+ await writeWebVtt(media.segments, write, o);
37
120
  await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
38
121
  }
39
122
  catch (e) {
@@ -43,3 +126,67 @@ export async function downloadHlsSubtitles(url, dest, o) {
43
126
  }
44
127
  await rename(part, dest);
45
128
  }
129
+ async function writeWebVtt(segments, write, o) {
130
+ let header = "";
131
+ for (const seg of segments) {
132
+ const r = await o.http.request(seg.url, { headers: o.headers, signal: o.signal });
133
+ if (!r.ok) {
134
+ await r.body?.cancel();
135
+ throw new TidepullError(`HTTP ${r.status} for subtitle segment ${seg.url}`);
136
+ }
137
+ const body = await r.text();
138
+ if (!header) {
139
+ header = body.slice(0, body.indexOf("\n\n") + 1);
140
+ await write(header);
141
+ }
142
+ const cues = body.startsWith("WEBVTT") ? body.slice(body.indexOf("\n\n") + 2) : body;
143
+ await write(cues.endsWith("\n") ? cues : cues + "\n");
144
+ }
145
+ }
146
+ const fmt = (s) => {
147
+ const ms = Math.max(0, Math.round(s * 1000));
148
+ const h = Math.floor(ms / 3600000);
149
+ const m = Math.floor((ms % 3600000) / 60000);
150
+ const sec = (ms % 60000) / 1000;
151
+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${sec.toFixed(3).padStart(6, "0")}`;
152
+ };
153
+ async function writeFmp4(segments, write, o) {
154
+ const maps = [...new Set(segments.map((s) => s.map).filter(Boolean))];
155
+ if (maps.length > 1)
156
+ throw new TidepullError("fMP4 subtitle playlists with changing EXT-X-MAP are not supported");
157
+ const init = await fetchBuf(maps[0], o);
158
+ if (!findBoxes(init, "wvtt").length)
159
+ throw new TidepullError("fMP4 init segment does not contain a wvtt sample entry; not a subtitle track");
160
+ const timescale = readTimescale(init);
161
+ const cues = [];
162
+ let pending = null;
163
+ for (const seg of segments) {
164
+ const { samples } = readSamples(await fetchBuf(seg.url, o));
165
+ for (const s of samples) {
166
+ const t = s.time / timescale;
167
+ const { texts, empty } = sampleContent(s.bytes);
168
+ if (texts.length) {
169
+ if (pending)
170
+ cues.push({ start: pending.start, end: t, text: pending.text });
171
+ pending = { start: t, text: texts.join("\n") };
172
+ }
173
+ else if (empty && pending) {
174
+ cues.push({ start: pending.start, end: t, text: pending.text });
175
+ pending = null;
176
+ }
177
+ }
178
+ }
179
+ if (pending)
180
+ cues.push({ start: pending.start, end: pending.start + 0.001, text: pending.text });
181
+ await write("WEBVTT\n\n");
182
+ for (const c of cues)
183
+ await write(`${fmt(c.start)} --> ${fmt(c.end)}\n${c.text}\n\n`);
184
+ }
185
+ async function fetchBuf(url, o) {
186
+ const r = await o.http.request(url, { headers: o.headers, signal: o.signal });
187
+ if (!r.ok) {
188
+ await r.body?.cancel();
189
+ throw new TidepullError(`HTTP ${r.status} for subtitle segment ${url}`);
190
+ }
191
+ return new Uint8Array(await r.arrayBuffer());
192
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boy-offi9-inc/tidepull",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "A minimal, from-scratch media downloader library: extractor plugins, yt-dlp-style format selection, resumable downloads.",
5
5
  "type": "module",
6
6
  "license": "MIT",