@boy-offi9-inc/tidepull 0.9.0 → 0.10.1

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,7 +183,7 @@ 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: live streams, 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, fMP4 subtitle tracks (WebVTT segment playlists only), 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
@@ -191,6 +191,7 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
191
191
  |---|---|
192
192
  | Direct files | resumable (`.part` + `Range`), retries with backoff |
193
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) |
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 |
194
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 |
195
196
  | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
196
197
  | Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
@@ -39,16 +39,36 @@ export interface SegmentRef {
39
39
  length: number;
40
40
  };
41
41
  }
42
+ export interface HlsOpts extends DownloadOpts {
43
+ concurrency: number;
44
+ live?: boolean;
45
+ maxDuration?: number;
46
+ maxSegments?: number;
47
+ refreshMs?: number;
48
+ }
49
+ export declare function makeSegmentFetcher(o: HlsOpts): {
50
+ fetchBuf: (u: string, range?: {
51
+ start: number;
52
+ length: number;
53
+ }) => Promise<Buffer>;
54
+ fetchSeg: (seg: SegmentRef) => Promise<Buffer>;
55
+ };
42
56
  export declare function downloadSegments(segments: SegmentRef[], dest: string, o: HlsOpts): Promise<{
43
57
  ext: "ts" | "mp4";
44
58
  }>;
45
59
  export declare function downloadHls(url: string, dest: string, o: HlsOpts): Promise<{
46
60
  ext: "ts" | "mp4";
47
61
  }>;
62
+ export interface LiveResult {
63
+ ext: "ts" | "mp4";
64
+ segments: number;
65
+ duration: number;
66
+ bytes: number;
67
+ }
68
+ export declare function downloadHlsLive(url: string, dest: string, o: HlsOpts): Promise<LiveResult>;
48
69
  export declare function downloadDash(f: {
49
70
  init?: string;
50
71
  fragments?: string[];
51
72
  }, dest: string, o: HlsOpts): Promise<{
52
73
  ext: "ts" | "mp4";
53
74
  }>;
54
- export declare function downloadHlsSubtitles(url: string, dest: string, o: HlsOpts): Promise<void>;
@@ -83,9 +83,13 @@ export async function downloadHttp(url, dest, o) {
83
83
  }
84
84
  await rename(part, dest);
85
85
  }
86
- export async function downloadSegments(segments, dest, o) {
87
- if (!segments.length)
88
- throw new TidepullError("No segments to download");
86
+ function partWriter(dest) {
87
+ const out = createWriteStream(`${dest}.part`);
88
+ const write = (b) => new Promise((res, rej) => out.write(b, (e) => (e ? rej(e) : res())));
89
+ const finish = () => new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
90
+ return { out, write, finish };
91
+ }
92
+ export function makeSegmentFetcher(o) {
89
93
  const keyCache = new Map();
90
94
  const getKey = (uri) => {
91
95
  let p = keyCache.get(uri);
@@ -114,8 +118,7 @@ export async function downloadSegments(segments, dest, o) {
114
118
  }
115
119
  return buf;
116
120
  };
117
- const fetchSeg = async (i) => {
118
- const seg = segments[i];
121
+ const fetchSeg = async (seg) => {
119
122
  let buf = await fetchBuf(seg.url, seg.range);
120
123
  if (seg.key) {
121
124
  const key = await getKey(seg.key.uri);
@@ -129,13 +132,17 @@ export async function downloadSegments(segments, dest, o) {
129
132
  }
130
133
  return buf;
131
134
  };
132
- const part = dest + ".part";
133
- const out = createWriteStream(part);
134
- const write = (b) => new Promise((res, rej) => out.write(b, (e) => (e ? rej(e) : res())));
135
+ return { fetchBuf, fetchSeg };
136
+ }
137
+ export async function downloadSegments(segments, dest, o) {
138
+ if (!segments.length)
139
+ throw new TidepullError("No segments to download");
140
+ const { fetchBuf, fetchSeg } = makeSegmentFetcher(o);
141
+ const { out, write, finish } = partWriter(dest);
135
142
  const n = segments.length;
136
143
  const inflight = new Array(n);
137
144
  const start = (i) => {
138
- inflight[i] = fetchSeg(i);
145
+ inflight[i] = fetchSeg(segments[i]);
139
146
  inflight[i].catch(() => { });
140
147
  };
141
148
  let ext = "ts";
@@ -164,14 +171,14 @@ export async function downloadSegments(segments, dest, o) {
164
171
  start(next++);
165
172
  o.onProgress({ downloaded: bytes, total: Math.round((bytes / (i + 1)) * n), estimated: i + 1 < n });
166
173
  }
167
- await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
174
+ await finish();
168
175
  }
169
176
  catch (e) {
170
177
  out.destroy();
171
- await rm(part, { force: true });
178
+ await rm(`${dest}.part`, { force: true });
172
179
  throw e;
173
180
  }
174
- await rename(part, dest);
181
+ await rename(`${dest}.part`, dest);
175
182
  return { ext };
176
183
  }
177
184
  export async function downloadHls(url, dest, o) {
@@ -179,53 +186,83 @@ export async function downloadHls(url, dest, o) {
179
186
  if (isMasterPlaylist(text))
180
187
  throw new TidepullError("Expected a media playlist, got a master playlist");
181
188
  const media = parseMedia(text, finalUrl);
182
- if (!media.endList)
183
- throw new TidepullError("Live HLS streams are not supported yet");
189
+ if (!media.endList) {
190
+ if (!o.live)
191
+ throw new TidepullError("Live HLS streams are not supported yet; pass live: true to record them");
192
+ return downloadHlsLive(url, dest, o);
193
+ }
184
194
  return downloadSegments(media.segments, dest, o);
185
195
  }
186
- export function downloadDash(f, dest, o) {
187
- if (!f.fragments?.length)
188
- throw new TidepullError("DASH format has no fragments");
189
- return downloadSegments(f.fragments.map((url, seq) => ({ url, seq, map: f.init })), dest, o);
190
- }
191
- export async function downloadHlsSubtitles(url, dest, o) {
192
- const { text, finalUrl } = await o.http.text(url, { headers: o.headers, signal: o.signal });
193
- if (isMasterPlaylist(text))
194
- throw new TidepullError("Expected a subtitle media playlist, got a master playlist");
195
- const media = parseMedia(text, finalUrl);
196
- if (!media.endList)
197
- throw new TidepullError("Live subtitle streams are not supported yet");
198
- const part = dest + ".part";
199
- const out = createWriteStream(part);
200
- const write = (s) => new Promise((res, rej) => out.write(s, (e) => (e ? rej(e) : res())));
196
+ export async function downloadHlsLive(url, dest, o) {
197
+ const first = await o.http.text(url, { headers: o.headers, signal: o.signal });
198
+ if (isMasterPlaylist(first.text))
199
+ throw new TidepullError("Expected a media playlist, got a master playlist");
200
+ let current = parseMedia(first.text, first.finalUrl);
201
+ if (current.endList) {
202
+ const { ext } = await downloadSegments(current.segments, dest, o);
203
+ return { ext, segments: current.segments.length, duration: current.segments.reduce((a, s) => a + s.duration, 0), bytes: 0 };
204
+ }
205
+ const { fetchBuf, fetchSeg } = makeSegmentFetcher(o);
206
+ const { out, write, finish } = partWriter(dest);
207
+ let lastSeq = -1;
208
+ let lastMap;
209
+ let ext = "ts";
210
+ let bytes = 0;
211
+ let duration = 0;
212
+ let count = 0;
213
+ const reached = () => (o.maxSegments !== undefined && count >= o.maxSegments) ||
214
+ (o.maxDuration !== undefined && duration >= o.maxDuration);
201
215
  try {
202
- let header = "";
203
- let lastMap;
204
- for (const seg of media.segments) {
205
- if (seg.map && seg.map !== lastMap) {
206
- out.destroy();
207
- await rm(part, { force: true });
208
- throw new TidepullError("fMP4 subtitle tracks (EXT-X-MAP) are not supported yet; only WebVTT segment playlists are");
209
- }
210
- const r = await o.http.request(seg.url, { headers: o.headers, signal: o.signal });
211
- if (!r.ok) {
212
- await r.body?.cancel();
213
- throw new TidepullError(`HTTP ${r.status} for subtitle segment ${seg.url}`);
214
- }
215
- const body = await r.text();
216
- if (!header) {
217
- header = body.slice(0, body.indexOf("\n\n") + 1);
218
- await write(header);
216
+ while (true) {
217
+ o.signal?.throwIfAborted();
218
+ for (const seg of current.segments) {
219
+ if (seg.seq <= lastSeq || reached())
220
+ continue;
221
+ if (seg.map && seg.map !== lastMap) {
222
+ const init = await fetchBuf(seg.map, seg.mapRange);
223
+ await write(init);
224
+ bytes += init.length;
225
+ lastMap = seg.map;
226
+ ext = "mp4";
227
+ }
228
+ const buf = await fetchSeg(seg);
229
+ await o.limiter?.take(buf.length, o.signal);
230
+ await write(buf);
231
+ bytes += buf.length;
232
+ duration += seg.duration;
233
+ count++;
234
+ lastSeq = seg.seq;
235
+ o.onProgress({ downloaded: bytes });
219
236
  }
220
- const cues = body.startsWith("WEBVTT") ? body.slice(body.indexOf("\n\n") + 2) : body;
221
- await write(cues.endsWith("\n") ? cues : cues + "\n");
237
+ if (reached() || current.endList)
238
+ break;
239
+ const durations = current.segments.map((s) => s.duration).filter((d) => d > 0);
240
+ const target = durations.length ? Math.min(...durations) : 6;
241
+ const wait = o.refreshMs ?? Math.max(1000, Math.min(10000, target * 500));
242
+ await sleep(wait, undefined, { signal: o.signal });
243
+ const next = await o.http.text(url, { headers: o.headers, signal: o.signal });
244
+ current = parseMedia(next.text, next.finalUrl);
222
245
  }
223
- await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
246
+ await finish();
224
247
  }
225
248
  catch (e) {
249
+ if (o.signal?.aborted) {
250
+ try {
251
+ await finish();
252
+ }
253
+ catch { }
254
+ await rename(`${dest}.part`, dest);
255
+ return { ext, segments: count, duration, bytes };
256
+ }
226
257
  out.destroy();
227
- await rm(part, { force: true });
258
+ await rm(`${dest}.part`, { force: true });
228
259
  throw e;
229
260
  }
230
- await rename(part, dest);
261
+ await rename(`${dest}.part`, dest);
262
+ return { ext, segments: count, duration, bytes };
263
+ }
264
+ export function downloadDash(f, dest, o) {
265
+ if (!f.fragments?.length)
266
+ throw new TidepullError("DASH format has no fragments");
267
+ return downloadSegments(f.fragments.map((url, seq) => ({ url, seq, map: f.init })), dest, o);
231
268
  }
@@ -15,6 +15,9 @@ export interface DownloadOptions {
15
15
  limitRate?: number;
16
16
  fields?: Record<string, string | number>;
17
17
  writeSubs?: boolean;
18
+ live?: boolean;
19
+ maxDuration?: number;
20
+ maxSegments?: number;
18
21
  }
19
22
  export declare const isPlaylist: (x: Info | Playlist) => x is Playlist;
20
23
  export declare function resolveUrl(rawUrl: string, ctx: Ctx): Promise<Info | Playlist>;
@@ -1,6 +1,6 @@
1
1
  import { mkdir, rename, rm, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { downloadDash, downloadHls, downloadHlsSubtitles, downloadHttp, RateLimiter } from "./downloader.js";
3
+ import { downloadDash, downloadHls, downloadHttp, RateLimiter } from "./downloader.js";
4
4
  import { TidepullError } from "./errors.js";
5
5
  import { findFfmpeg, mergeStreams, remux, extractAudio } from "./ffmpeg.js";
6
6
  import { Meter } from "./meter.js";
@@ -94,7 +94,7 @@ export async function downloadInfo(info, opts, ctx) {
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
96
  if (f.protocol === "hls")
97
- ({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency }));
97
+ ({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency, live: opts.live, maxDuration: opts.maxDuration, maxSegments: opts.maxSegments }));
98
98
  else if (f.protocol === "dash")
99
99
  ({ ext } = await downloadDash(f, dest, { ...common, concurrency: opts.concurrency }));
100
100
  else
@@ -149,6 +149,7 @@ export async function downloadInfo(info, opts, ctx) {
149
149
  target = out;
150
150
  }
151
151
  if (opts.writeSubs && info.subtitles?.length) {
152
+ const { downloadHlsSubtitles } = await import("./subtitles.js");
152
153
  const stemBase = target.slice(0, target.length - path.extname(target).length);
153
154
  for (const sub of info.subtitles) {
154
155
  const dest = `${stemBase}.${sub.lang.replace(/\W+/g, "_")}.vtt`;
@@ -0,0 +1,4 @@
1
+ import type { DownloadOpts } from "./downloader.js";
2
+ export declare function downloadHlsSubtitles(url: string, dest: string, o: DownloadOpts & {
3
+ concurrency: number;
4
+ }): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { createWriteStream } from "node:fs";
2
+ import { rename, rm } from "node:fs/promises";
3
+ import { TidepullError } from "./errors.js";
4
+ import { isMasterPlaylist, parseMedia } from "./hls.js";
5
+ export async function downloadHlsSubtitles(url, dest, o) {
6
+ const { text, finalUrl } = await o.http.text(url, { headers: o.headers, signal: o.signal });
7
+ if (isMasterPlaylist(text))
8
+ throw new TidepullError("Expected a subtitle media playlist, got a master playlist");
9
+ const media = parseMedia(text, finalUrl);
10
+ if (!media.endList)
11
+ throw new TidepullError("Live subtitle streams are not supported yet");
12
+ const part = `${dest}.part`;
13
+ const out = createWriteStream(part);
14
+ const write = (s) => new Promise((res, rej) => out.write(s, (e) => (e ? rej(e) : res())));
15
+ 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
+ }
37
+ await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
38
+ }
39
+ catch (e) {
40
+ out.destroy();
41
+ await rm(part, { force: true });
42
+ throw e;
43
+ }
44
+ await rename(part, dest);
45
+ }
package/dist/main.js CHANGED
@@ -61,6 +61,9 @@ Config:
61
61
  Network:
62
62
  --limit-rate RATE Maximum download speed per file, e.g. 500K or 1.5M
63
63
  --write-subs Download subtitle tracks (HLS SUBTITLES renditions) as .vtt next to the media
64
+ --live Record live HLS streams (stops when the stream ends or on Ctrl-C, keeping what was captured)
65
+ --max-duration SEC Live recording: stop after SEC seconds of media
66
+ --max-segments N Live recording: stop after N segments
64
67
  --cookies FILE Send cookies from a Netscape cookies.txt file, only to the hosts they belong to
65
68
  -N, --concurrent-fragments N HLS segments fetched in parallel (default: 4)
66
69
  -R, --retries N Retries per request (default: 3)
@@ -156,6 +159,9 @@ export async function main(argv) {
156
159
  "download-archive": { type: "string" },
157
160
  "limit-rate": { type: "string" },
158
161
  "write-subs": { type: "boolean" },
162
+ live: { type: "boolean" },
163
+ "max-duration": { type: "string" },
164
+ "max-segments": { type: "string" },
159
165
  cookies: { type: "string" },
160
166
  "config-location": { type: "string" },
161
167
  "no-config": { type: "boolean" },
@@ -281,6 +287,9 @@ export async function main(argv) {
281
287
  headers,
282
288
  limitRate,
283
289
  writeSubs: !!values["write-subs"],
290
+ live: !!values.live,
291
+ maxDuration: values["max-duration"] ? num(values["max-duration"], 0) || undefined : undefined,
292
+ maxSegments: values["max-segments"] ? num(values["max-segments"], 0) || undefined : undefined,
284
293
  };
285
294
  for (const k of Object.keys(opts))
286
295
  if (opts[k] === undefined)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boy-offi9-inc/tidepull",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
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",
@@ -25,7 +25,7 @@
25
25
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node scripts/fix-dts.mjs",
26
26
  "prepack": "npm run build",
27
27
  "prepublishOnly": "npm run typecheck && npm test",
28
- "size": "node scripts/size.mjs dist/index.js --budget=52",
28
+ "size": "node scripts/size.mjs dist/index.js --budget=53",
29
29
  "lint:imports": "node scripts/lint-imports.mjs"
30
30
  },
31
31
  "devDependencies": {
@@ -78,4 +78,4 @@
78
78
  "library",
79
79
  "typescript"
80
80
  ]
81
- }
81
+ }