@boy-offi9-inc/tidepull 0.0.0-stage → 0.1.0-rc.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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +3 -0
  5. package/dist/core/downloader.d.ts +44 -0
  6. package/dist/core/downloader.js +160 -0
  7. package/dist/core/errors.d.ts +11 -0
  8. package/dist/core/errors.js +22 -0
  9. package/dist/core/events.d.ts +51 -0
  10. package/dist/core/events.js +5 -0
  11. package/dist/core/ffmpeg.d.ts +3 -0
  12. package/dist/core/ffmpeg.js +38 -0
  13. package/dist/core/hls.d.ts +41 -0
  14. package/dist/core/hls.js +102 -0
  15. package/dist/core/http.d.ts +46 -0
  16. package/dist/core/http.js +120 -0
  17. package/dist/core/meter.d.ts +6 -0
  18. package/dist/core/meter.js +17 -0
  19. package/dist/core/pipeline.d.ts +25 -0
  20. package/dist/core/pipeline.js +128 -0
  21. package/dist/core/selector.d.ts +32 -0
  22. package/dist/core/selector.js +166 -0
  23. package/dist/core/template.d.ts +3 -0
  24. package/dist/core/template.js +20 -0
  25. package/dist/core/types.d.ts +56 -0
  26. package/dist/core/types.js +1 -0
  27. package/dist/dash/index.d.ts +7 -0
  28. package/dist/dash/index.js +70 -0
  29. package/dist/dash/parse.d.ts +31 -0
  30. package/dist/dash/parse.js +140 -0
  31. package/dist/dash/xml.d.ts +9 -0
  32. package/dist/dash/xml.js +56 -0
  33. package/dist/extractors/direct.d.ts +3 -0
  34. package/dist/extractors/direct.js +34 -0
  35. package/dist/extractors/generic.d.ts +3 -0
  36. package/dist/extractors/generic.js +104 -0
  37. package/dist/extractors/hls.d.ts +3 -0
  38. package/dist/extractors/hls.js +72 -0
  39. package/dist/extractors/index.d.ts +5 -0
  40. package/dist/extractors/index.js +9 -0
  41. package/dist/extractors/util.d.ts +7 -0
  42. package/dist/extractors/util.js +13 -0
  43. package/dist/index.d.ts +14 -0
  44. package/dist/index.js +8 -0
  45. package/dist/loader.d.ts +7 -0
  46. package/dist/loader.js +76 -0
  47. package/dist/main.d.ts +3 -0
  48. package/dist/main.js +244 -0
  49. package/dist/plugins.d.ts +10 -0
  50. package/dist/plugins.js +4 -0
  51. package/dist/tidepull.d.ts +48 -0
  52. package/dist/tidepull.js +106 -0
  53. package/dist/ui/format.d.ts +4 -0
  54. package/dist/ui/format.js +26 -0
  55. package/dist/ui/log.d.ts +19 -0
  56. package/dist/ui/log.js +37 -0
  57. package/dist/ui/render.d.ts +9 -0
  58. package/dist/ui/render.js +71 -0
  59. package/package.json +66 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tidepull contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,109 @@
1
- # Temporary Holding Version
1
+ # tidepull
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A minimal, from-scratch media downloader **library** (and CLI) for Node. Minimal by design: a ~22 KB minified core with no runtime dependencies today (~9 KB gzip), fully typed, no terminal code in the core. Everything that isn't needed by every user is opt-in.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i @boy-offi9-inc/tidepull # as a library
9
+ npx @boy-offi9-inc/tidepull -F <url> # or run the CLI without installing
10
+ npm i -g @boy-offi9-inc/tidepull # installs the `tidepull` command
11
+ ```
12
+
13
+ Published under the `@boy-offi9-inc` npm scope; the command it installs is `tidepull`.
14
+
15
+ Requires Node >= 22.18. ffmpeg is optional (only needed to merge video+audio or remux).
16
+
17
+ ## Use
18
+
19
+ ```ts
20
+ import { createTidepull } from "@boy-offi9-inc/tidepull";
21
+
22
+ const g = createTidepull();
23
+ g.on((e) => e.type === "progress" && console.log(e.downloaded, e.total, e.speed));
24
+
25
+ const info = await g.extract("https://example.com/stream/master.m3u8");
26
+ const [video, audio] = g.select(info, "bv*[height<=720]+ba/b") ?? []; // pure, no network
27
+ const file = await g.download(info, { format: "bv*[height<=720]+ba/b", paths: "./out" });
28
+ ```
29
+
30
+ Cancel anything with an `AbortSignal`; partial `.part` files are kept so the next run resumes:
31
+
32
+ ```ts
33
+ const ctl = new AbortController();
34
+ setTimeout(() => ctl.abort(), 5000);
35
+ await g.pull(url, { signal: ctl.signal }); // rejects with name === "AbortError"
36
+ ```
37
+
38
+ ## API (everything else is internal)
39
+ | Export | Purpose |
40
+ |---|---|
41
+ | `createTidepull(opts?)` → `Tidepull` | `.extract(url)`, `.select(info, selector)`, `.download(info, opts)`, `.pull(url, opts)`, `.on(listener)`, `.use(plugin)`, `.extractors` |
42
+ | `definePlugin`, `PLUGIN_API_VERSION` | write extractor plugins |
43
+ | `@boy-offi9-inc/tidepull/dash` *(opt-in)* | DASH VOD: `createTidepull({ plugins: [dash] })` |
44
+ | `@boy-offi9-inc/tidepull/loader` *(opt-in)* | `loadPlugins(paths)` / `loadPlugin(file)`: load plugins from disk |
45
+ | `selectFormats`, `renderTemplate`, `parseHlsMaster/Media` | the building blocks, usable standalone |
46
+ | `Http`, `TidepullError` | redirect-safe, header-scoped HTTP client; error type |
47
+ | types | `Info`, `Format`, `Extractor`, `TidepullEvent`, `DownloadOptions`, `TidepullPlugin`, ... |
48
+
49
+ ### Events (plain JSON, ideal for GUIs/IPC)
50
+ `extract` · `start` · `progress {downloaded,total,estimated,speed,eta}` · `finish` · `merge` · `remux` · `done {file}` · `log {level,tag,message}` · `error`
51
+
52
+ CLI: `tidepull --progress-json URL` prints the same events as NDJSON on stdout.
53
+
54
+ ## Plugins (fix a site without waiting for a release)
55
+ ```ts
56
+ // ~/.config/tidepull/plugins/mysite.ts (or --plugin ./mysite.ts, or g.use(...))
57
+ import { definePlugin } from "@boy-offi9-inc/tidepull";
58
+ export default definePlugin({
59
+ name: "mysite", apiVersion: 1,
60
+ extractors: [{
61
+ name: "mysite",
62
+ suitable: (u) => u.hostname === "mysite.example",
63
+ async extract(u, ctx) { /* ctx.http is redirect-safe + cancellable */ return { id, title, extractor: "mysite", webpage_url: u.href, formats: [...] }; },
64
+ }],
65
+ });
66
+ ```
67
+ Plugins run before built-ins; the generic fallback is always last. From disk: `import { loadPlugins } from "@boy-offi9-inc/tidepull/loader"` (the CLI does this for you, and bundles DASH). A plugin targeting a different `apiVersion` is refused with a clear message instead of failing mysteriously. **Plugins execute with your privileges. Only load code you trust.** See `src/extractors/_template.ts`.
68
+
69
+ ## CLI
70
+ ```bash
71
+ tidepull -F URL # list formats
72
+ tidepull -f "bv*[height<=720]+ba/b" URL # select + merge (needs ffmpeg)
73
+ tidepull -o "%(title).60s [%(id)s].%(ext)s" -P ~/Videos URL
74
+ tidepull -j URL | jq .formats # data on stdout, logs on stderr
75
+ ```
76
+ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node >= 22.18); `npm run build` emits JS + `.d.ts`.
77
+
78
+ ## What works today
79
+ | Area | Status |
80
+ |---|---|
81
+ | Direct files | resumable (`.part` + `Range`), retries with backoff |
82
+ | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, separate audio renditions |
83
+ | 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`; encrypted (`ContentProtection`) representations are skipped, never decrypted |
84
+ | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
85
+ | Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
86
+ | Output templates | `%(title)s`, `%(x\|default)s`, `%(title).50s`, sanitized |
87
+ | Merge / remux | ffmpeg |
88
+ | Site-specific extractors | none built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin (see Plugins) |
89
+ | Not yet | live HLS/DASH, multi-period DASH, SAMPLE-AES, byte-range HLS/DASH, playlists, subtitles, cookies |
90
+
91
+ ## Footprint (enforced in CI)
92
+ The core does only what every user needs: extract → select → download, events, cancellation. Everything else is a plugin or an opt-in subpath.
93
+
94
+ | Import | Files | Raw | Gzip | Minified (gzip) |
95
+ |---|---|---|---|---|
96
+ | `@boy-offi9-inc/tidepull` (core: direct, HLS, generic page, selector, templates, resume, merge) | 18 | 44.9 KB | 13.5 KB | 22 KB (9 KB) |
97
+ | `@boy-offi9-inc/tidepull/dash` (adds XML + MPD parsing) | +6 | +14 KB | +4.7 KB | +7 KB (+3 KB) |
98
+ | `@boy-offi9-inc/tidepull/loader` (plugins from disk) | +3 | +4 KB | +1.7 KB | n/a (Node only) |
99
+
100
+ `npm run size` fails the build if the core grows past its budget. CLI and terminal UI are not part of `import "@boy-offi9-inc/tidepull"`.
101
+
102
+ ## Security model
103
+ - **No shell, ever.** ffmpeg is spawned with argv arrays. There is deliberately no `--exec` and no `--netrc-cmd`-style hook; the command-injection CVEs in this space came from exactly those features.
104
+ - **Redirect-safe HTTP.** Redirects are followed manually: on a cross-origin hop everything except `User-Agent/Accept*/Range` is dropped (Authorization, Cookie, custom tokens), non-http(s) targets are refused, loops are capped.
105
+ - **Origin-scoped secrets.** Custom headers like `Authorization`, `Cookie` or API tokens (`--header` / `http.headers`) are sent only to the origins you pass to `extract()`/`pull()`, plus any `--header-host` / `http.headerHosts` patterns (`cdn.example.com`, `*.example.com`). `Referer`, `Origin`, `Accept*`, `User-Agent` and `Range` are never treated as secret. Using one `Tidepull` instance for several sites trusts all of them, so use one instance per credential. The low-level `Http` class (without `headerHosts`) sends headers to each request's start origin only.
106
+ - Output filenames are built from sanitized fields only. Only `http(s)` URLs are accepted.
107
+
108
+ ## Legal
109
+ Only download content you own or are permitted to download; you're responsible for complying with site terms and local law. MIT licensed.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./main.js";
3
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,44 @@
1
+ import type { Http } from "./http.js";
2
+ import { type HlsKey } from "./hls.js";
3
+ export interface Progress {
4
+ downloaded: number;
5
+ total?: number;
6
+ /** total is a guess (HLS: extrapolated from finished segments) */
7
+ estimated?: boolean;
8
+ }
9
+ export interface DownloadOpts {
10
+ http: Http;
11
+ headers?: Record<string, string>;
12
+ signal?: AbortSignal;
13
+ onProgress: (p: Progress) => void;
14
+ }
15
+ /** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
16
+ export declare function downloadHttp(url: string, dest: string, o: DownloadOpts & {
17
+ resume: boolean;
18
+ }): Promise<void>;
19
+ export interface HlsOpts extends DownloadOpts {
20
+ concurrency: number;
21
+ }
22
+ /** A fragment to fetch. HLS segments and DASH fragments both reduce to this. */
23
+ export interface SegmentRef {
24
+ url: string;
25
+ seq: number;
26
+ key?: HlsKey;
27
+ /** init segment (fMP4); written whenever it changes */
28
+ map?: string;
29
+ }
30
+ /** Fetches fragments in parallel, writes them in order (bounded memory), decrypts AES-128. Returns the container ext. */
31
+ export declare function downloadSegments(segments: SegmentRef[], dest: string, o: HlsOpts): Promise<{
32
+ ext: "ts" | "mp4";
33
+ }>;
34
+ /** HLS VOD: parse the media playlist, then hand the segments to the shared engine. */
35
+ export declare function downloadHls(url: string, dest: string, o: HlsOpts): Promise<{
36
+ ext: "ts" | "mp4";
37
+ }>;
38
+ /** DASH: fragments were already expanded by the extractor (format.init + format.fragments). */
39
+ export declare function downloadDash(f: {
40
+ init?: string;
41
+ fragments?: string[];
42
+ }, dest: string, o: HlsOpts): Promise<{
43
+ ext: "ts" | "mp4";
44
+ }>;
@@ -0,0 +1,160 @@
1
+ import { createDecipheriv } from "node:crypto";
2
+ import { createWriteStream } from "node:fs";
3
+ import { rename, rm, stat } from "node:fs/promises";
4
+ import { Readable, Transform } from "node:stream";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { TidepullError } from "./errors.js";
7
+ import { isMasterPlaylist, parseMedia } from "./hls.js";
8
+ /** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
9
+ export async function downloadHttp(url, dest, o) {
10
+ const part = dest + ".part";
11
+ let offset = 0;
12
+ if (o.resume)
13
+ offset = await stat(part).then((s) => s.size, () => 0);
14
+ const headers = { "Accept-Encoding": "identity", ...o.headers };
15
+ if (offset > 0)
16
+ headers.Range = `bytes=${offset}-`;
17
+ const res = await o.http.request(url, { headers, signal: o.signal });
18
+ if (res.status === 416) {
19
+ // Range not satisfiable: the .part is either complete or stale.
20
+ await res.body?.cancel();
21
+ const total = /\*\/(\d+)/.exec(res.headers.get("content-range") ?? "")?.[1];
22
+ if (total && Number(total) === offset) {
23
+ await rename(part, dest);
24
+ return;
25
+ }
26
+ await rm(part, { force: true });
27
+ return downloadHttp(url, dest, { ...o, resume: false });
28
+ }
29
+ if (!res.ok) {
30
+ await res.body?.cancel();
31
+ throw new TidepullError(`HTTP ${res.status} ${res.statusText} for ${url}`);
32
+ }
33
+ if (!res.body)
34
+ throw new TidepullError(`Empty response body for ${url}`);
35
+ let append = false;
36
+ let total;
37
+ if (res.status === 206 && offset > 0) {
38
+ append = true;
39
+ const m = /bytes (\d+)-\d+\/(\d+)/.exec(res.headers.get("content-range") ?? "");
40
+ total = m ? Number(m[2]) : undefined;
41
+ }
42
+ else {
43
+ offset = 0; // no usable Range response: start over
44
+ const cl = res.headers.get("content-length");
45
+ total = cl ? Number(cl) : undefined;
46
+ }
47
+ let done = offset;
48
+ const counter = new Transform({
49
+ transform(chunk, _enc, cb) {
50
+ done += chunk.length;
51
+ o.onProgress({ downloaded: done, total });
52
+ cb(null, chunk);
53
+ },
54
+ });
55
+ await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(part, { flags: append ? "a" : "w" }), { signal: o.signal });
56
+ if (total !== undefined && done !== total) {
57
+ throw new TidepullError(`Incomplete download (${done}/${total} bytes). Re-run to resume.`);
58
+ }
59
+ await rename(part, dest);
60
+ }
61
+ /** Fetches fragments in parallel, writes them in order (bounded memory), decrypts AES-128. Returns the container ext. */
62
+ export async function downloadSegments(segments, dest, o) {
63
+ if (!segments.length)
64
+ throw new TidepullError("No segments to download");
65
+ const keyCache = new Map();
66
+ const getKey = (uri) => {
67
+ let p = keyCache.get(uri);
68
+ if (!p) {
69
+ p = o.http.request(uri, { headers: o.headers, signal: o.signal }).then(async (r) => {
70
+ if (!r.ok)
71
+ throw new TidepullError(`HTTP ${r.status} fetching HLS key`);
72
+ return Buffer.from(await r.arrayBuffer());
73
+ });
74
+ keyCache.set(uri, p);
75
+ }
76
+ return p;
77
+ };
78
+ const fetchBuf = async (u) => {
79
+ const r = await o.http.request(u, { headers: o.headers, signal: o.signal });
80
+ if (!r.ok) {
81
+ await r.body?.cancel();
82
+ throw new TidepullError(`HTTP ${r.status} for segment ${u}`);
83
+ }
84
+ return Buffer.from(await r.arrayBuffer());
85
+ };
86
+ const fetchSeg = async (i) => {
87
+ const seg = segments[i];
88
+ let buf = await fetchBuf(seg.url);
89
+ if (seg.key) {
90
+ const key = await getKey(seg.key.uri);
91
+ let iv = seg.key.iv;
92
+ if (!iv) {
93
+ iv = Buffer.alloc(16); // default IV = segment sequence number, big-endian
94
+ iv.writeUInt32BE(seg.seq >>> 0, 12);
95
+ }
96
+ const d = createDecipheriv("aes-128-cbc", key, iv);
97
+ buf = Buffer.concat([d.update(buf), d.final()]);
98
+ }
99
+ return buf;
100
+ };
101
+ const part = dest + ".part";
102
+ const out = createWriteStream(part);
103
+ const write = (b) => new Promise((res, rej) => out.write(b, (e) => (e ? rej(e) : res())));
104
+ const n = segments.length;
105
+ const inflight = new Array(n);
106
+ const start = (i) => {
107
+ inflight[i] = fetchSeg(i);
108
+ inflight[i].catch(() => { }); // handled when awaited in order
109
+ };
110
+ let ext = "ts";
111
+ let lastMap;
112
+ let bytes = 0;
113
+ try {
114
+ let next = Math.min(Math.max(1, o.concurrency), n);
115
+ for (let i = 0; i < next; i++)
116
+ start(i);
117
+ for (let i = 0; i < n; i++) {
118
+ o.signal?.throwIfAborted();
119
+ const buf = await inflight[i];
120
+ inflight[i] = undefined;
121
+ const map = segments[i].map;
122
+ if (map && map !== lastMap) {
123
+ const init = await fetchBuf(map);
124
+ await write(init);
125
+ bytes += init.length;
126
+ lastMap = map;
127
+ ext = "mp4";
128
+ }
129
+ await write(buf);
130
+ bytes += buf.length;
131
+ if (next < n)
132
+ start(next++);
133
+ o.onProgress({ downloaded: bytes, total: Math.round((bytes / (i + 1)) * n), estimated: i + 1 < n });
134
+ }
135
+ await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
136
+ }
137
+ catch (e) {
138
+ out.destroy();
139
+ await rm(part, { force: true });
140
+ throw e;
141
+ }
142
+ await rename(part, dest);
143
+ return { ext };
144
+ }
145
+ /** HLS VOD: parse the media playlist, then hand the segments to the shared engine. */
146
+ export async function downloadHls(url, dest, o) {
147
+ const { text, finalUrl } = await o.http.text(url, { headers: o.headers, signal: o.signal });
148
+ if (isMasterPlaylist(text))
149
+ throw new TidepullError("Expected a media playlist, got a master playlist");
150
+ const media = parseMedia(text, finalUrl);
151
+ if (!media.endList)
152
+ throw new TidepullError("Live HLS streams are not supported yet");
153
+ return downloadSegments(media.segments, dest, o);
154
+ }
155
+ /** DASH: fragments were already expanded by the extractor (format.init + format.fragments). */
156
+ export function downloadDash(f, dest, o) {
157
+ if (!f.fragments?.length)
158
+ throw new TidepullError("DASH format has no fragments");
159
+ return downloadSegments(f.fragments.map((url, seq) => ({ url, seq, map: f.init })), dest, o);
160
+ }
@@ -0,0 +1,11 @@
1
+ export declare class TidepullError extends Error {
2
+ exitCode: number;
3
+ constructor(message: string, exitCode?: number);
4
+ }
5
+ export declare const errMsg: (e: unknown) => string;
6
+ /** Thrown when a caller's AbortSignal fires. name === "AbortError" so it works with standard abort handling. */
7
+ export declare function abortError(): TidepullError;
8
+ /** Redirect policy violations. Never retried. */
9
+ export declare class RedirectError extends TidepullError {
10
+ constructor(message: string);
11
+ }
@@ -0,0 +1,22 @@
1
+ export class TidepullError extends Error {
2
+ exitCode;
3
+ constructor(message, exitCode = 1) {
4
+ super(message);
5
+ this.name = "TidepullError";
6
+ this.exitCode = exitCode;
7
+ }
8
+ }
9
+ export const errMsg = (e) => (e instanceof Error ? e.message : String(e));
10
+ /** Thrown when a caller's AbortSignal fires. name === "AbortError" so it works with standard abort handling. */
11
+ export function abortError() {
12
+ const e = new TidepullError("Aborted", 130);
13
+ e.name = "AbortError";
14
+ return e;
15
+ }
16
+ /** Redirect policy violations. Never retried. */
17
+ export class RedirectError extends TidepullError {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "RedirectError";
21
+ }
22
+ }
@@ -0,0 +1,51 @@
1
+ export type LogLevel = "debug" | "info" | "warn";
2
+ /** Everything the engine reports. Plain JSON-serializable objects, so they can be piped, logged or sent over IPC. */
3
+ export type TidepullEvent = {
4
+ type: "log";
5
+ level: LogLevel;
6
+ tag?: string;
7
+ message: string;
8
+ } | {
9
+ type: "extract";
10
+ extractor: string;
11
+ url: string;
12
+ } | {
13
+ type: "start";
14
+ format_id: string;
15
+ dest: string;
16
+ } | {
17
+ type: "progress";
18
+ format_id: string;
19
+ downloaded: number;
20
+ total?: number;
21
+ estimated?: boolean;
22
+ speed?: number;
23
+ eta?: number;
24
+ } | {
25
+ type: "finish";
26
+ format_id: string;
27
+ bytes: number;
28
+ seconds: number;
29
+ speed?: number;
30
+ } | {
31
+ type: "merge";
32
+ output: string;
33
+ } | {
34
+ type: "remux";
35
+ output: string;
36
+ } | {
37
+ type: "done";
38
+ file: string;
39
+ } | {
40
+ type: "error";
41
+ message: string;
42
+ url?: string;
43
+ };
44
+ export type Emit = (e: TidepullEvent) => void;
45
+ /** Logging interface exposed to extractors. */
46
+ export interface Log {
47
+ debug(msg: string): void;
48
+ info(tag: string, msg: string): void;
49
+ warn(msg: string): void;
50
+ }
51
+ export declare const makeLog: (emit: Emit) => Log;
@@ -0,0 +1,5 @@
1
+ export const makeLog = (emit) => ({
2
+ debug: (message) => emit({ type: "log", level: "debug", message }),
3
+ info: (tag, message) => emit({ type: "log", level: "info", tag, message }),
4
+ warn: (message) => emit({ type: "log", level: "warn", message }),
5
+ });
@@ -0,0 +1,3 @@
1
+ export declare function findFfmpeg(location?: string): string | undefined;
2
+ export declare const mergeStreams: (bin: string, video: string, audio: string, out: string) => Promise<void>;
3
+ export declare const remux: (bin: string, input: string, out: string) => Promise<void>;
@@ -0,0 +1,38 @@
1
+ import { spawn } from "node:child_process";
2
+ import { statSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { TidepullError } from "./errors.js";
5
+ export function findFfmpeg(location) {
6
+ const exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
7
+ const isFile = (p) => {
8
+ try {
9
+ return statSync(p).isFile();
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ };
15
+ if (location) {
16
+ if (isFile(location))
17
+ return location;
18
+ const inDir = path.join(location, exe);
19
+ return isFile(inDir) ? inDir : undefined;
20
+ }
21
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
22
+ const p = path.join(dir, exe);
23
+ if (dir && isFile(p))
24
+ return p;
25
+ }
26
+ return undefined;
27
+ }
28
+ function run(bin, args) {
29
+ return new Promise((resolve, reject) => {
30
+ const p = spawn(bin, ["-y", "-loglevel", "error", ...args], { stdio: ["ignore", "ignore", "pipe"] });
31
+ let err = "";
32
+ p.stderr.on("data", (d) => (err += d.toString()));
33
+ p.on("error", (e) => reject(new TidepullError(`Failed to run ffmpeg: ${e.message}`)));
34
+ p.on("close", (code) => (code === 0 ? resolve() : reject(new TidepullError(`ffmpeg failed: ${err.trim().split("\n").slice(-3).join(" | ")}`))));
35
+ });
36
+ }
37
+ export const mergeStreams = (bin, video, audio, out) => run(bin, ["-i", video, "-i", audio, "-map", "0:v:0", "-map", "1:a:0", "-c", "copy", out]);
38
+ export const remux = (bin, input, out) => run(bin, ["-i", input, "-c", "copy", out]);
@@ -0,0 +1,41 @@
1
+ export interface HlsVariant {
2
+ url: string;
3
+ bandwidth: number;
4
+ width?: number;
5
+ height?: number;
6
+ fps?: number;
7
+ codecs?: string;
8
+ audioGroup?: string;
9
+ }
10
+ export interface HlsRendition {
11
+ type: string;
12
+ groupId: string;
13
+ name: string;
14
+ uri?: string;
15
+ isDefault: boolean;
16
+ language?: string;
17
+ }
18
+ export interface HlsMaster {
19
+ variants: HlsVariant[];
20
+ renditions: HlsRendition[];
21
+ }
22
+ export interface HlsKey {
23
+ method: "AES-128";
24
+ uri: string;
25
+ iv?: Buffer;
26
+ }
27
+ export interface HlsSegment {
28
+ url: string;
29
+ duration: number;
30
+ seq: number;
31
+ key?: HlsKey;
32
+ map?: string;
33
+ }
34
+ export interface HlsMedia {
35
+ segments: HlsSegment[];
36
+ endList: boolean;
37
+ }
38
+ export declare function isMasterPlaylist(text: string): boolean;
39
+ export declare function parseAttributes(s: string): Record<string, string>;
40
+ export declare function parseMaster(text: string, base: string): HlsMaster;
41
+ export declare function parseMedia(text: string, base: string): HlsMedia;
@@ -0,0 +1,102 @@
1
+ import { TidepullError } from "./errors.js";
2
+ const val = (line) => line.slice(line.indexOf(":") + 1);
3
+ const lines = (text) => text.split(/\r?\n/).map((l) => l.trim());
4
+ export function isMasterPlaylist(text) {
5
+ return text.includes("#EXT-X-STREAM-INF");
6
+ }
7
+ export function parseAttributes(s) {
8
+ const out = {};
9
+ const re = /([A-Z0-9-]+)=("[^"]*"|[^,]*)/g;
10
+ let m;
11
+ while ((m = re.exec(s))) {
12
+ let v = m[2];
13
+ if (v.startsWith('"') && v.endsWith('"'))
14
+ v = v.slice(1, -1);
15
+ out[m[1]] = v;
16
+ }
17
+ return out;
18
+ }
19
+ export function parseMaster(text, base) {
20
+ const ls = lines(text);
21
+ const variants = [];
22
+ const renditions = [];
23
+ for (let i = 0; i < ls.length; i++) {
24
+ const line = ls[i];
25
+ if (line.startsWith("#EXT-X-STREAM-INF:")) {
26
+ const a = parseAttributes(val(line));
27
+ let j = i + 1;
28
+ while (j < ls.length && (ls[j] === "" || ls[j].startsWith("#")))
29
+ j++;
30
+ if (!ls[j])
31
+ continue;
32
+ const [w, h] = (a.RESOLUTION ?? "").split("x").map(Number);
33
+ variants.push({
34
+ url: new URL(ls[j], base).href,
35
+ bandwidth: Number(a.BANDWIDTH ?? 0),
36
+ width: w || undefined,
37
+ height: h || undefined,
38
+ fps: a["FRAME-RATE"] ? Number(a["FRAME-RATE"]) : undefined,
39
+ codecs: a.CODECS,
40
+ audioGroup: a.AUDIO,
41
+ });
42
+ i = j;
43
+ }
44
+ else if (line.startsWith("#EXT-X-MEDIA:")) {
45
+ const a = parseAttributes(val(line));
46
+ renditions.push({
47
+ type: a.TYPE ?? "",
48
+ groupId: a["GROUP-ID"] ?? "",
49
+ name: a.NAME ?? "",
50
+ uri: a.URI ? new URL(a.URI, base).href : undefined,
51
+ isDefault: a.DEFAULT === "YES",
52
+ language: a.LANGUAGE,
53
+ });
54
+ }
55
+ }
56
+ return { variants, renditions };
57
+ }
58
+ function parseIv(s) {
59
+ return Buffer.from(s.replace(/^0x/i, "").padStart(32, "0"), "hex");
60
+ }
61
+ export function parseMedia(text, base) {
62
+ const ls = lines(text).filter(Boolean);
63
+ if (ls[0] !== "#EXTM3U")
64
+ throw new TidepullError("Not an HLS playlist (missing #EXTM3U)");
65
+ let seq = 0;
66
+ let dur = 0;
67
+ let endList = false;
68
+ let key;
69
+ let map;
70
+ const segments = [];
71
+ for (const line of ls) {
72
+ if (line.startsWith("#EXT-X-MEDIA-SEQUENCE:"))
73
+ seq = Number(val(line)) || 0;
74
+ else if (line.startsWith("#EXTINF:"))
75
+ dur = parseFloat(val(line)) || 0;
76
+ else if (line.startsWith("#EXT-X-ENDLIST"))
77
+ endList = true;
78
+ else if (line.startsWith("#EXT-X-BYTERANGE"))
79
+ throw new TidepullError("HLS byte-range segments are not supported yet");
80
+ else if (line.startsWith("#EXT-X-KEY:")) {
81
+ const a = parseAttributes(val(line));
82
+ if (a.METHOD === "NONE")
83
+ key = undefined;
84
+ else if (a.METHOD === "AES-128" && a.URI) {
85
+ key = { method: "AES-128", uri: new URL(a.URI, base).href, iv: a.IV ? parseIv(a.IV) : undefined };
86
+ }
87
+ else
88
+ throw new TidepullError(`Unsupported HLS encryption: ${a.METHOD}`);
89
+ }
90
+ else if (line.startsWith("#EXT-X-MAP:")) {
91
+ const a = parseAttributes(val(line));
92
+ if (a.BYTERANGE)
93
+ throw new TidepullError("HLS byte-range init segments are not supported yet");
94
+ map = a.URI ? new URL(a.URI, base).href : undefined;
95
+ }
96
+ else if (!line.startsWith("#")) {
97
+ segments.push({ url: new URL(line, base).href, duration: dur, seq: seq + segments.length, key, map });
98
+ dur = 0;
99
+ }
100
+ }
101
+ return { segments, endList };
102
+ }