@boy-offi9-inc/tidepull 0.0.0-stage → 0.1.0-rc.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/LICENSE +21 -0
- package/README.md +107 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +3 -0
- package/dist/core/downloader.d.ts +44 -0
- package/dist/core/downloader.js +160 -0
- package/dist/core/errors.d.ts +11 -0
- package/dist/core/errors.js +22 -0
- package/dist/core/events.d.ts +51 -0
- package/dist/core/events.js +5 -0
- package/dist/core/ffmpeg.d.ts +3 -0
- package/dist/core/ffmpeg.js +38 -0
- package/dist/core/hls.d.ts +41 -0
- package/dist/core/hls.js +102 -0
- package/dist/core/http.d.ts +46 -0
- package/dist/core/http.js +120 -0
- package/dist/core/meter.d.ts +6 -0
- package/dist/core/meter.js +17 -0
- package/dist/core/pipeline.d.ts +25 -0
- package/dist/core/pipeline.js +126 -0
- package/dist/core/selector.d.ts +32 -0
- package/dist/core/selector.js +166 -0
- package/dist/core/template.d.ts +3 -0
- package/dist/core/template.js +20 -0
- package/dist/core/types.d.ts +56 -0
- package/dist/core/types.js +1 -0
- package/dist/dash/index.d.ts +7 -0
- package/dist/dash/index.js +70 -0
- package/dist/dash/parse.d.ts +31 -0
- package/dist/dash/parse.js +140 -0
- package/dist/dash/xml.d.ts +9 -0
- package/dist/dash/xml.js +56 -0
- package/dist/extractors/direct.d.ts +3 -0
- package/dist/extractors/direct.js +34 -0
- package/dist/extractors/generic.d.ts +3 -0
- package/dist/extractors/generic.js +103 -0
- package/dist/extractors/hls.d.ts +3 -0
- package/dist/extractors/hls.js +72 -0
- package/dist/extractors/index.d.ts +5 -0
- package/dist/extractors/index.js +9 -0
- package/dist/extractors/util.d.ts +7 -0
- package/dist/extractors/util.js +13 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +8 -0
- package/dist/loader.d.ts +7 -0
- package/dist/loader.js +76 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.js +243 -0
- package/dist/plugins.d.ts +10 -0
- package/dist/plugins.js +4 -0
- package/dist/tidepull.d.ts +48 -0
- package/dist/tidepull.js +107 -0
- package/dist/ui/format.d.ts +4 -0
- package/dist/ui/format.js +26 -0
- package/dist/ui/log.d.ts +19 -0
- package/dist/ui/log.js +37 -0
- package/dist/ui/render.d.ts +9 -0
- package/dist/ui/render.js +60 -0
- package/package.json +66 -4
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in DASH (VOD) support.
|
|
3
|
+
* import dash from "@boy-offi9-inc/tidepull/dash";
|
|
4
|
+
* createTidepull({ plugins: [dash] });
|
|
5
|
+
*/
|
|
6
|
+
import { TidepullError } from "../core/errors.js";
|
|
7
|
+
import { extOf, splitCodecs, stem } from "../extractors/util.js";
|
|
8
|
+
import { definePlugin } from "../plugins.js";
|
|
9
|
+
import { parseMpd } from "./parse.js";
|
|
10
|
+
const MAX_MPD_BYTES = 5 * 1024 * 1024;
|
|
11
|
+
const extFor = (mime, kind) => mime.includes("webm") ? "webm" : mime.startsWith("audio/") || kind === "audio" ? "m4a" : "mp4";
|
|
12
|
+
export const dashExtractor = {
|
|
13
|
+
name: "dash",
|
|
14
|
+
suitable: (url) => extOf(url.pathname) === "mpd",
|
|
15
|
+
extract: (url, ctx) => extractDash(url, ctx),
|
|
16
|
+
};
|
|
17
|
+
export async function extractDash(url, ctx) {
|
|
18
|
+
const { text, finalUrl } = await ctx.http.text(url.href);
|
|
19
|
+
if (text.length > MAX_MPD_BYTES)
|
|
20
|
+
throw new TidepullError("Manifest is unreasonably large");
|
|
21
|
+
const mpd = parseMpd(text, finalUrl);
|
|
22
|
+
if (mpd.dynamic)
|
|
23
|
+
throw new TidepullError("Live DASH streams are not supported yet");
|
|
24
|
+
if (mpd.periods > 1)
|
|
25
|
+
ctx.log.warn(`Manifest has ${mpd.periods} periods; only the first is used`);
|
|
26
|
+
for (const s of mpd.skipped)
|
|
27
|
+
ctx.log.warn(`Skipping representation ${s}`);
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
const uniq = (id) => {
|
|
30
|
+
let out = id;
|
|
31
|
+
for (let n = 1; seen.has(out); n++)
|
|
32
|
+
out = `${id}-${n}`;
|
|
33
|
+
seen.add(out);
|
|
34
|
+
return out;
|
|
35
|
+
};
|
|
36
|
+
const formats = [];
|
|
37
|
+
for (const r of mpd.reps) {
|
|
38
|
+
if (r.kind === "other")
|
|
39
|
+
continue; // subtitles etc.: not yet
|
|
40
|
+
const { v, a } = splitCodecs(r.codecs);
|
|
41
|
+
const video = r.kind === "video";
|
|
42
|
+
const f = {
|
|
43
|
+
format_id: uniq(`dash-${r.id}`.replace(/[^\w.-]+/g, "_")),
|
|
44
|
+
url: r.single ?? finalUrl,
|
|
45
|
+
ext: extFor(r.mime, r.kind),
|
|
46
|
+
protocol: r.single ? "https" : "dash",
|
|
47
|
+
width: r.width,
|
|
48
|
+
height: r.height,
|
|
49
|
+
fps: r.fps,
|
|
50
|
+
vcodec: video ? (v ?? "unknown") : "none",
|
|
51
|
+
acodec: video ? "none" : (a ?? "unknown"),
|
|
52
|
+
tbr: Math.round(r.bandwidth / 1000) || undefined,
|
|
53
|
+
abr: !video ? Math.round(r.bandwidth / 1000) || undefined : undefined,
|
|
54
|
+
format_note: r.lang,
|
|
55
|
+
};
|
|
56
|
+
if (!r.single) {
|
|
57
|
+
f.init = r.init;
|
|
58
|
+
f.fragments = r.fragments;
|
|
59
|
+
}
|
|
60
|
+
formats.push(f);
|
|
61
|
+
}
|
|
62
|
+
if (!formats.length)
|
|
63
|
+
throw new TidepullError(`No downloadable representations in the manifest${mpd.skipped.length ? ` (${mpd.skipped.length} skipped)` : ""}`);
|
|
64
|
+
let name = stem(url.pathname);
|
|
65
|
+
if (/^(manifest|stream|index|master|playlist|main)$/i.test(name))
|
|
66
|
+
name = url.pathname.split("/").filter(Boolean).slice(-2, -1)[0] ?? url.hostname;
|
|
67
|
+
return { id: name || url.hostname, title: name || url.hostname, extractor: "dash", webpage_url: url.href, formats };
|
|
68
|
+
}
|
|
69
|
+
export { parseMpd };
|
|
70
|
+
export default definePlugin({ name: "dash", apiVersion: 1, extractors: [dashExtractor] });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface DashRep {
|
|
2
|
+
id: string;
|
|
3
|
+
kind: "video" | "audio" | "other";
|
|
4
|
+
mime: string;
|
|
5
|
+
codecs?: string;
|
|
6
|
+
bandwidth: number;
|
|
7
|
+
width?: number;
|
|
8
|
+
height?: number;
|
|
9
|
+
fps?: number;
|
|
10
|
+
lang?: string;
|
|
11
|
+
/** fragmented: init segment + media segments */
|
|
12
|
+
init?: string;
|
|
13
|
+
fragments?: string[];
|
|
14
|
+
/** whole-file representation (SegmentBase / plain BaseURL) */
|
|
15
|
+
single?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface DashManifest {
|
|
18
|
+
reps: DashRep[];
|
|
19
|
+
dynamic: boolean;
|
|
20
|
+
periods: number;
|
|
21
|
+
skipped: string[];
|
|
22
|
+
}
|
|
23
|
+
export declare function parseIsoDuration(s?: string): number | undefined;
|
|
24
|
+
/** $RepresentationID$, $Number$, $Bandwidth$, $Time$ (+ %0Nd width), $$ */
|
|
25
|
+
export declare function fillTemplate(tpl: string, v: {
|
|
26
|
+
RepresentationID: string;
|
|
27
|
+
Bandwidth: number;
|
|
28
|
+
Number?: number;
|
|
29
|
+
Time?: number;
|
|
30
|
+
}): string;
|
|
31
|
+
export declare function parseMpd(text: string, manifestUrl: string): DashManifest;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** Static (VOD) MPEG-DASH: SegmentTemplate (number / timeline), SegmentList, single-file SegmentBase. No DRM, no live. */
|
|
2
|
+
import { TidepullError } from "../core/errors.js";
|
|
3
|
+
import { child, kids, parseXml } from "./xml.js";
|
|
4
|
+
const MAX_FRAGMENTS = 50_000;
|
|
5
|
+
export function parseIsoDuration(s) {
|
|
6
|
+
if (!s)
|
|
7
|
+
return undefined;
|
|
8
|
+
const m = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/.exec(s);
|
|
9
|
+
if (!m)
|
|
10
|
+
return undefined;
|
|
11
|
+
return Number(m[3] ?? 0) * 86400 + Number(m[4] ?? 0) * 3600 + Number(m[5] ?? 0) * 60 + Number(m[6] ?? 0);
|
|
12
|
+
}
|
|
13
|
+
function parseRate(s) {
|
|
14
|
+
if (!s)
|
|
15
|
+
return undefined;
|
|
16
|
+
const [a, b] = s.split("/").map(Number);
|
|
17
|
+
const v = b ? a / b : a;
|
|
18
|
+
return Number.isFinite(v) ? Math.round(v * 100) / 100 : undefined;
|
|
19
|
+
}
|
|
20
|
+
function resolve(base, rel) {
|
|
21
|
+
const u = new URL(rel?.trim() ? rel.trim() : ".", base);
|
|
22
|
+
if (u.protocol !== "http:" && u.protocol !== "https:")
|
|
23
|
+
throw new TidepullError(`Refusing non-http(s) URL in manifest: ${u.protocol}`);
|
|
24
|
+
return u.href;
|
|
25
|
+
}
|
|
26
|
+
/** $RepresentationID$, $Number$, $Bandwidth$, $Time$ (+ %0Nd width), $$ */
|
|
27
|
+
export function fillTemplate(tpl, v) {
|
|
28
|
+
return tpl.replace(/\$(RepresentationID|Number|Bandwidth|Time)(?:%0(\d+)d)?\$|\$\$/g, (m, key, width) => {
|
|
29
|
+
if (m === "$$")
|
|
30
|
+
return "$";
|
|
31
|
+
const val = v[key];
|
|
32
|
+
if (val === undefined)
|
|
33
|
+
throw new TidepullError(`Manifest template uses $${key}$ where it is not defined`);
|
|
34
|
+
const s = String(val);
|
|
35
|
+
return width ? s.padStart(Number(width), "0") : s;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export function parseMpd(text, manifestUrl) {
|
|
39
|
+
const root = parseXml(text);
|
|
40
|
+
if (root.name !== "MPD")
|
|
41
|
+
throw new TidepullError("Not a DASH manifest (root element is not MPD)");
|
|
42
|
+
const dynamic = (root.attrs.type ?? "static") === "dynamic";
|
|
43
|
+
const periods = kids(root, "Period");
|
|
44
|
+
const out = { reps: [], dynamic, periods: periods.length, skipped: [] };
|
|
45
|
+
if (dynamic || !periods.length)
|
|
46
|
+
return out;
|
|
47
|
+
const period = periods[0];
|
|
48
|
+
const mpdDur = parseIsoDuration(root.attrs.mediaPresentationDuration);
|
|
49
|
+
const periodDur = parseIsoDuration(period.attrs.duration) ?? (periods.length === 1 ? mpdDur : undefined);
|
|
50
|
+
const baseP = resolve(resolve(manifestUrl, child(root, "BaseURL")?.text), child(period, "BaseURL")?.text);
|
|
51
|
+
for (const aset of kids(period, "AdaptationSet")) {
|
|
52
|
+
const baseA = resolve(baseP, child(aset, "BaseURL")?.text);
|
|
53
|
+
for (const rep of kids(aset, "Representation")) {
|
|
54
|
+
const id = rep.attrs.id ?? String(out.reps.length);
|
|
55
|
+
const mime = rep.attrs.mimeType ?? aset.attrs.mimeType ?? "";
|
|
56
|
+
const ctype = aset.attrs.contentType ?? rep.attrs.contentType ?? mime.split("/")[0];
|
|
57
|
+
const kind = ctype === "video" ? "video" : ctype === "audio" ? "audio" : "other";
|
|
58
|
+
if (child(aset, "ContentProtection") || child(rep, "ContentProtection")) {
|
|
59
|
+
out.skipped.push(`${id}: encrypted (ContentProtection), cannot be downloaded`);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const baseR = resolve(baseA, child(rep, "BaseURL")?.text);
|
|
64
|
+
const bandwidth = Number(rep.attrs.bandwidth ?? 0);
|
|
65
|
+
const r = {
|
|
66
|
+
id, kind, mime,
|
|
67
|
+
codecs: rep.attrs.codecs ?? aset.attrs.codecs,
|
|
68
|
+
bandwidth,
|
|
69
|
+
width: Number(rep.attrs.width ?? aset.attrs.width) || undefined,
|
|
70
|
+
height: Number(rep.attrs.height ?? aset.attrs.height) || undefined,
|
|
71
|
+
fps: parseRate(rep.attrs.frameRate ?? aset.attrs.frameRate),
|
|
72
|
+
lang: aset.attrs.lang,
|
|
73
|
+
};
|
|
74
|
+
const vars = { RepresentationID: id, Bandwidth: bandwidth };
|
|
75
|
+
const tplNode = child(rep, "SegmentTemplate") ?? child(aset, "SegmentTemplate");
|
|
76
|
+
const listNode = child(rep, "SegmentList") ?? child(aset, "SegmentList");
|
|
77
|
+
if (tplNode) {
|
|
78
|
+
const tpl = { ...child(aset, "SegmentTemplate")?.attrs, ...child(rep, "SegmentTemplate")?.attrs };
|
|
79
|
+
if (!tpl.media)
|
|
80
|
+
throw new TidepullError("SegmentTemplate without @media");
|
|
81
|
+
if (tpl.initialization)
|
|
82
|
+
r.init = resolve(baseR, fillTemplate(tpl.initialization, vars));
|
|
83
|
+
const timescale = Number(tpl.timescale ?? 1) || 1;
|
|
84
|
+
let n = Number(tpl.startNumber ?? 1);
|
|
85
|
+
const frags = [];
|
|
86
|
+
const push = (num, time) => {
|
|
87
|
+
if (frags.length >= MAX_FRAGMENTS)
|
|
88
|
+
throw new TidepullError(`Too many fragments (>${MAX_FRAGMENTS})`);
|
|
89
|
+
frags.push(resolve(baseR, fillTemplate(tpl.media, { ...vars, Number: num, Time: time })));
|
|
90
|
+
};
|
|
91
|
+
const timeline = child(tplNode, "SegmentTimeline") ?? child(aset, "SegmentTimeline");
|
|
92
|
+
if (timeline) {
|
|
93
|
+
let t = 0;
|
|
94
|
+
for (const s of kids(timeline, "S")) {
|
|
95
|
+
if (s.attrs.t !== undefined)
|
|
96
|
+
t = Number(s.attrs.t);
|
|
97
|
+
const d = Number(s.attrs.d);
|
|
98
|
+
if (!(d > 0))
|
|
99
|
+
throw new TidepullError("SegmentTimeline entry without a positive @d");
|
|
100
|
+
let rep_ = Number(s.attrs.r ?? 0);
|
|
101
|
+
if (rep_ < 0) {
|
|
102
|
+
if (!periodDur)
|
|
103
|
+
throw new TidepullError("Open-ended SegmentTimeline repeat needs a known duration");
|
|
104
|
+
rep_ = Math.ceil((periodDur * timescale - t) / d) - 1;
|
|
105
|
+
}
|
|
106
|
+
for (let i = 0; i <= rep_; i++, n++, t += d)
|
|
107
|
+
push(n, t);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (tpl.duration) {
|
|
111
|
+
if (!periodDur)
|
|
112
|
+
throw new TidepullError("Duration-based SegmentTemplate needs a known presentation duration");
|
|
113
|
+
const count = Math.ceil(periodDur / (Number(tpl.duration) / timescale));
|
|
114
|
+
for (let i = 0; i < count; i++)
|
|
115
|
+
push(n + i);
|
|
116
|
+
}
|
|
117
|
+
else
|
|
118
|
+
throw new TidepullError("SegmentTemplate has neither SegmentTimeline nor @duration");
|
|
119
|
+
r.fragments = frags;
|
|
120
|
+
}
|
|
121
|
+
else if (listNode) {
|
|
122
|
+
const init = child(listNode, "Initialization");
|
|
123
|
+
if (init?.attrs.range || kids(listNode, "SegmentURL").some((u) => u.attrs.mediaRange))
|
|
124
|
+
throw new TidepullError("Byte-range SegmentList is not supported yet");
|
|
125
|
+
if (init?.attrs.sourceURL)
|
|
126
|
+
r.init = resolve(baseR, init.attrs.sourceURL);
|
|
127
|
+
r.fragments = kids(listNode, "SegmentURL").map((u) => resolve(baseR, u.attrs.media));
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
r.single = baseR; // SegmentBase / plain BaseURL: one self-contained file
|
|
131
|
+
}
|
|
132
|
+
out.reps.push(r);
|
|
133
|
+
}
|
|
134
|
+
catch (e) {
|
|
135
|
+
out.skipped.push(`${id}: ${e instanceof Error ? e.message : String(e)}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface XNode {
|
|
2
|
+
name: string;
|
|
3
|
+
attrs: Record<string, string>;
|
|
4
|
+
children: XNode[];
|
|
5
|
+
text: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function parseXml(src: string): XNode;
|
|
8
|
+
export declare const child: (n: XNode, name: string) => XNode | undefined;
|
|
9
|
+
export declare const kids: (n: XNode, name: string) => XNode[];
|
package/dist/dash/xml.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Minimal, dependency-free XML parser: elements, attributes, text. No DTD/entity expansion (so no billion-laughs). Namespace prefixes are dropped. */
|
|
2
|
+
import { TidepullError } from "../core/errors.js";
|
|
3
|
+
const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
4
|
+
const decode = (s) => s.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(\w+));/gi, (m, hex, dec, name) => {
|
|
5
|
+
if (hex)
|
|
6
|
+
return String.fromCodePoint(parseInt(hex, 16));
|
|
7
|
+
if (dec)
|
|
8
|
+
return String.fromCodePoint(Number(dec));
|
|
9
|
+
return ENT[name ?? ""] ?? m;
|
|
10
|
+
});
|
|
11
|
+
const local = (n) => n.slice(n.indexOf(":") + 1);
|
|
12
|
+
const TOKEN = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<!DOCTYPE[^>]*>|<(\/?)([A-Za-z_][\w:.-]*)((?:\s+[^\s=/>]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;
|
|
13
|
+
const ATTR = /([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
|
14
|
+
const MAX_DEPTH = 64;
|
|
15
|
+
export function parseXml(src) {
|
|
16
|
+
const root = { name: "#root", attrs: {}, children: [], text: "" };
|
|
17
|
+
const stack = [root];
|
|
18
|
+
let m;
|
|
19
|
+
TOKEN.lastIndex = 0;
|
|
20
|
+
while ((m = TOKEN.exec(src))) {
|
|
21
|
+
const top = stack[stack.length - 1];
|
|
22
|
+
if (m[1] !== undefined)
|
|
23
|
+
top.text += m[1];
|
|
24
|
+
else if (m[6] !== undefined)
|
|
25
|
+
top.text += decode(m[6]);
|
|
26
|
+
else if (m[3]) {
|
|
27
|
+
const name = local(m[3]);
|
|
28
|
+
if (m[2]) {
|
|
29
|
+
if (stack.length < 2 || stack[stack.length - 1].name !== name)
|
|
30
|
+
throw new TidepullError(`Malformed XML: unexpected </${name}>`);
|
|
31
|
+
stack.pop();
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const attrs = {};
|
|
35
|
+
let a;
|
|
36
|
+
ATTR.lastIndex = 0;
|
|
37
|
+
while ((a = ATTR.exec(m[4] ?? "")))
|
|
38
|
+
attrs[local(a[1])] = decode(a[2] ?? a[3] ?? "");
|
|
39
|
+
const node = { name, attrs, children: [], text: "" };
|
|
40
|
+
top.children.push(node);
|
|
41
|
+
if (!m[5]) {
|
|
42
|
+
if (stack.length > MAX_DEPTH)
|
|
43
|
+
throw new TidepullError("XML nesting too deep");
|
|
44
|
+
stack.push(node);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (stack.length !== 1)
|
|
49
|
+
throw new TidepullError("Malformed XML: unclosed element");
|
|
50
|
+
const el = root.children[0];
|
|
51
|
+
if (!el)
|
|
52
|
+
throw new TidepullError("Malformed XML: no root element");
|
|
53
|
+
return el;
|
|
54
|
+
}
|
|
55
|
+
export const child = (n, name) => n.children.find((c) => c.name === name);
|
|
56
|
+
export const kids = (n, name) => n.children.filter((c) => c.name === name);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { TidepullError } from "../core/errors.js";
|
|
2
|
+
import { extOf, stem } from "./util.js";
|
|
3
|
+
const VIDEO = new Set(["mp4", "m4v", "webm", "mkv", "mov", "flv", "avi", "ts"]);
|
|
4
|
+
const AUDIO = new Set(["mp3", "m4a", "aac", "ogg", "oga", "opus", "wav", "flac"]);
|
|
5
|
+
export const directExtractor = {
|
|
6
|
+
name: "direct",
|
|
7
|
+
suitable: (url) => VIDEO.has(extOf(url.pathname)) || AUDIO.has(extOf(url.pathname)),
|
|
8
|
+
extract: (url, ctx) => extractDirect(url, ctx),
|
|
9
|
+
};
|
|
10
|
+
export async function extractDirect(url, ctx) {
|
|
11
|
+
const ext = extOf(url.pathname);
|
|
12
|
+
// Try HEAD first; some servers reject it, so fall back to a 1-byte ranged GET.
|
|
13
|
+
let res = await ctx.http.request(url.href, { method: "HEAD" });
|
|
14
|
+
let size = res.ok ? Number(res.headers.get("content-length")) || undefined : undefined;
|
|
15
|
+
if (!res.ok) {
|
|
16
|
+
res = await ctx.http.request(url.href, { headers: { Range: "bytes=0-0" } });
|
|
17
|
+
await res.body?.cancel();
|
|
18
|
+
if (!res.ok)
|
|
19
|
+
throw new TidepullError(`HTTP ${res.status} ${res.statusText} for ${url.href}`);
|
|
20
|
+
size = Number(/\/(\d+)$/.exec(res.headers.get("content-range") ?? "")?.[1]) || undefined;
|
|
21
|
+
}
|
|
22
|
+
const audioOnly = AUDIO.has(ext);
|
|
23
|
+
const format = {
|
|
24
|
+
format_id: "http",
|
|
25
|
+
url: res.url || url.href,
|
|
26
|
+
ext,
|
|
27
|
+
protocol: "https",
|
|
28
|
+
vcodec: audioOnly ? "none" : "unknown",
|
|
29
|
+
acodec: "unknown",
|
|
30
|
+
filesize: size,
|
|
31
|
+
};
|
|
32
|
+
const name = stem(url.pathname) || url.hostname;
|
|
33
|
+
return { id: name, title: name, extractor: "direct", webpage_url: url.href, formats: [format] };
|
|
34
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { TidepullError, errMsg } from "../core/errors.js";
|
|
2
|
+
import { extractDirect } from "./direct.js";
|
|
3
|
+
import { extractHls } from "./hls.js";
|
|
4
|
+
import { decodeEntities, extOf } from "./util.js";
|
|
5
|
+
const MEDIA_CT = /^(video|audio)\//;
|
|
6
|
+
const HLS_CT = /(mpegurl)/;
|
|
7
|
+
const DASH_CT = /dash\+xml/;
|
|
8
|
+
function attrs(tag) {
|
|
9
|
+
const out = {};
|
|
10
|
+
const re = /([a-zA-Z:_-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
|
11
|
+
let m;
|
|
12
|
+
while ((m = re.exec(tag)))
|
|
13
|
+
out[m[1].toLowerCase()] = decodeEntities(m[2] ?? m[3] ?? "");
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
function findCandidates(html, base) {
|
|
17
|
+
const found = [];
|
|
18
|
+
const add = (u) => {
|
|
19
|
+
if (!u)
|
|
20
|
+
return;
|
|
21
|
+
try {
|
|
22
|
+
found.push(new URL(decodeEntities(u).trim(), base).href);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
/* ignore bad URLs */
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
for (const m of html.matchAll(/<meta\b[^>]*>/gi)) {
|
|
29
|
+
const a = attrs(m[0]);
|
|
30
|
+
const key = (a.property ?? a.name ?? "").toLowerCase();
|
|
31
|
+
if (/^(og:video(:url|:secure_url)?|twitter:player:stream)$/.test(key))
|
|
32
|
+
add(a.content);
|
|
33
|
+
}
|
|
34
|
+
for (const m of html.matchAll(/<(?:video|source)\b[^>]*>/gi))
|
|
35
|
+
add(attrs(m[0]).src);
|
|
36
|
+
const flat = html.replace(/\\\//g, "/");
|
|
37
|
+
for (const m of flat.matchAll(/https?:\/\/[^\s"'<>\\]+?\.(?:m3u8|mpd|mp4|webm|mov|m4v|mp3|m4a)(?:\?[^\s"'<>\\]*)?/gi))
|
|
38
|
+
add(m[0]);
|
|
39
|
+
return [...new Set(found)].filter((u) => /^https?:/.test(u)).slice(0, 10);
|
|
40
|
+
}
|
|
41
|
+
async function extractOne(u, ctx) {
|
|
42
|
+
const ex = ctx.extractors.find((e) => e !== genericExtractor && e.suitable(u));
|
|
43
|
+
if (!ex)
|
|
44
|
+
throw new TidepullError(`no extractor for ${u.href}`);
|
|
45
|
+
return ex.extract(u, ctx);
|
|
46
|
+
}
|
|
47
|
+
/** Fallback: look at the page itself (media content-type, og:video, <video>, bare media URLs). */
|
|
48
|
+
export const genericExtractor = {
|
|
49
|
+
name: "generic",
|
|
50
|
+
suitable: () => true,
|
|
51
|
+
async extract(url, ctx) {
|
|
52
|
+
const res = await ctx.http.request(url.href);
|
|
53
|
+
if (!res.ok) {
|
|
54
|
+
await res.body?.cancel();
|
|
55
|
+
throw new TidepullError(`HTTP ${res.status} ${res.statusText} for ${url.href}`);
|
|
56
|
+
}
|
|
57
|
+
const ct = (res.headers.get("content-type") ?? "").toLowerCase();
|
|
58
|
+
if (MEDIA_CT.test(ct) || HLS_CT.test(ct) || DASH_CT.test(ct)) {
|
|
59
|
+
await res.body?.cancel();
|
|
60
|
+
const u = new URL(res.url || url.href);
|
|
61
|
+
if (HLS_CT.test(ct))
|
|
62
|
+
return extractHls(u, ctx);
|
|
63
|
+
if (DASH_CT.test(ct)) {
|
|
64
|
+
const dash = ctx.extractors.find((e) => e.name === "dash");
|
|
65
|
+
if (!dash)
|
|
66
|
+
throw new TidepullError('DASH manifest found; enable it with: import dash from "@boy-offi9-inc/tidepull/dash"; createTidepull({ plugins: [dash] })');
|
|
67
|
+
return dash.extract(u, ctx);
|
|
68
|
+
}
|
|
69
|
+
const info = await extractDirect(u, ctx);
|
|
70
|
+
info.formats[0].ext = extOf(u.pathname) || ct.split("/")[1].split(";")[0];
|
|
71
|
+
return info;
|
|
72
|
+
}
|
|
73
|
+
const html = await res.text();
|
|
74
|
+
const pageUrl = res.url || url.href;
|
|
75
|
+
const candidates = findCandidates(html, pageUrl);
|
|
76
|
+
ctx.log.debug(`generic: ${candidates.length} candidate(s): ${candidates.join(" ")}`);
|
|
77
|
+
const title = decodeEntities(/<meta[^>]+property=["']og:title["'][^>]*content=["']([^"']+)["']/i.exec(html)?.[1] ??
|
|
78
|
+
/<meta[^>]+content=["']([^"']+)["'][^>]*property=["']og:title["']/i.exec(html)?.[1] ??
|
|
79
|
+
/<title[^>]*>([^<]*)<\/title>/i.exec(html)?.[1] ??
|
|
80
|
+
new URL(pageUrl).hostname).trim();
|
|
81
|
+
const thumbnail = /<meta[^>]+property=["']og:image["'][^>]*content=["']([^"']+)["']/i.exec(html)?.[1];
|
|
82
|
+
const formats = [];
|
|
83
|
+
for (const [i, c] of candidates.entries()) {
|
|
84
|
+
try {
|
|
85
|
+
const info = await extractOne(new URL(c), ctx);
|
|
86
|
+
for (const f of info.formats) {
|
|
87
|
+
formats.push(candidates.length > 1 ? { ...f, format_id: `c${i}-${f.format_id}` } : f);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
catch (e) {
|
|
91
|
+
ctx.log.debug(`generic: skipped ${c}: ${errMsg(e)}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (!formats.length)
|
|
95
|
+
throw new TidepullError(`Unable to find any media on ${url.href} (no site-specific extractor matched)`);
|
|
96
|
+
const id = (await sha(pageUrl)).slice(0, 10);
|
|
97
|
+
return { id, title: title || id, extractor: "generic", webpage_url: pageUrl, thumbnail, formats };
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
async function sha(s) {
|
|
101
|
+
const { createHash } = await import("node:crypto");
|
|
102
|
+
return createHash("sha1").update(s).digest("hex");
|
|
103
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { TidepullError } from "../core/errors.js";
|
|
2
|
+
import { isMasterPlaylist, parseMaster } from "../core/hls.js";
|
|
3
|
+
import { extOf, splitCodecs, stem } from "./util.js";
|
|
4
|
+
export const hlsExtractor = {
|
|
5
|
+
name: "hls",
|
|
6
|
+
suitable: (url) => extOf(url.pathname) === "m3u8",
|
|
7
|
+
extract: (url, ctx) => extractHls(url, ctx),
|
|
8
|
+
};
|
|
9
|
+
export async function extractHls(url, ctx) {
|
|
10
|
+
const { text, finalUrl } = await ctx.http.text(url.href);
|
|
11
|
+
if (!text.trimStart().startsWith("#EXTM3U"))
|
|
12
|
+
throw new TidepullError(`Not an HLS playlist: ${url.href}`);
|
|
13
|
+
const formats = [];
|
|
14
|
+
if (isMasterPlaylist(text)) {
|
|
15
|
+
const master = parseMaster(text, finalUrl);
|
|
16
|
+
const audioGroups = new Map();
|
|
17
|
+
for (const r of master.renditions)
|
|
18
|
+
if (r.type === "AUDIO" && r.uri)
|
|
19
|
+
audioGroups.set(r.groupId, true);
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
const uniq = (id) => {
|
|
22
|
+
let out = id;
|
|
23
|
+
for (let n = 1; seen.has(out); n++)
|
|
24
|
+
out = `${id}-${n}`;
|
|
25
|
+
seen.add(out);
|
|
26
|
+
return out;
|
|
27
|
+
};
|
|
28
|
+
let audioCodec;
|
|
29
|
+
for (const v of master.variants) {
|
|
30
|
+
const { v: vc, a: ac } = splitCodecs(v.codecs);
|
|
31
|
+
// Variant points at an external audio group and lists no audio codec => video-only stream.
|
|
32
|
+
const external = !!v.audioGroup && audioGroups.has(v.audioGroup) && !ac && !!v.codecs;
|
|
33
|
+
if (ac)
|
|
34
|
+
audioCodec ??= ac;
|
|
35
|
+
formats.push({
|
|
36
|
+
format_id: uniq(`hls-${Math.round(v.bandwidth / 1000)}`),
|
|
37
|
+
url: v.url,
|
|
38
|
+
ext: "ts",
|
|
39
|
+
protocol: "hls",
|
|
40
|
+
width: v.width,
|
|
41
|
+
height: v.height,
|
|
42
|
+
fps: v.fps,
|
|
43
|
+
vcodec: vc ?? "unknown",
|
|
44
|
+
acodec: external ? "none" : (ac ?? "unknown"),
|
|
45
|
+
tbr: Math.round(v.bandwidth / 1000) || undefined,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
for (const r of master.renditions) {
|
|
49
|
+
if (r.type !== "AUDIO" || !r.uri)
|
|
50
|
+
continue;
|
|
51
|
+
formats.push({
|
|
52
|
+
format_id: uniq(`hls-audio-${r.groupId}-${r.name}`.replace(/\W+/g, "_")),
|
|
53
|
+
url: r.uri,
|
|
54
|
+
ext: "ts",
|
|
55
|
+
protocol: "hls",
|
|
56
|
+
vcodec: "none",
|
|
57
|
+
acodec: audioCodec ?? "unknown",
|
|
58
|
+
format_note: [r.name, r.language].filter(Boolean).join(" "),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (!formats.length)
|
|
62
|
+
throw new TidepullError("Master playlist has no variants");
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
formats.push({ format_id: "hls", url: finalUrl, ext: "ts", protocol: "hls", vcodec: "unknown", acodec: "unknown" });
|
|
66
|
+
}
|
|
67
|
+
let name = stem(url.pathname);
|
|
68
|
+
if (/^(index|master|playlist|manifest|stream|main)$/i.test(name)) {
|
|
69
|
+
name = url.pathname.split("/").filter(Boolean).slice(-2, -1)[0] ?? url.hostname;
|
|
70
|
+
}
|
|
71
|
+
return { id: name || url.hostname, title: name || url.hostname, extractor: "hls", webpage_url: url.href, formats };
|
|
72
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Extractor } from "../core/types.js";
|
|
2
|
+
import type { TidepullPlugin } from "../plugins.js";
|
|
3
|
+
export declare const builtinExtractors: readonly Extractor[];
|
|
4
|
+
/** First `suitable()` match wins: plugin extractors (in order), then built-ins, with the generic fallback always last. */
|
|
5
|
+
export declare function buildRegistry(plugins?: readonly TidepullPlugin[]): Extractor[];
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { directExtractor } from "./direct.js";
|
|
2
|
+
import { genericExtractor } from "./generic.js";
|
|
3
|
+
import { hlsExtractor } from "./hls.js";
|
|
4
|
+
export const builtinExtractors = [hlsExtractor, directExtractor, genericExtractor];
|
|
5
|
+
/** First `suitable()` match wins: plugin extractors (in order), then built-ins, with the generic fallback always last. */
|
|
6
|
+
export function buildRegistry(plugins = []) {
|
|
7
|
+
const specific = builtinExtractors.filter((e) => e !== genericExtractor);
|
|
8
|
+
return [...plugins.flatMap((p) => p.extractors ?? []), ...specific, genericExtractor];
|
|
9
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const decodeEntities: (s: string) => string;
|
|
2
|
+
export declare const extOf: (pathname: string) => string;
|
|
3
|
+
export declare function stem(pathname: string): string;
|
|
4
|
+
export declare function splitCodecs(codecs?: string): {
|
|
5
|
+
v?: string;
|
|
6
|
+
a?: string;
|
|
7
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", "#39": "'", "#x2F": "/", "#47": "/" };
|
|
2
|
+
export const decodeEntities = (s) => s.replace(/&(#?\w+);/g, (m, e) => ENTITIES[e] ?? m);
|
|
3
|
+
export const extOf = (pathname) => /\.([a-z0-9]{2,5})$/i.exec(pathname)?.[1]?.toLowerCase() ?? "";
|
|
4
|
+
export function stem(pathname) {
|
|
5
|
+
const base = decodeURIComponent(pathname.split("/").filter(Boolean).pop() ?? "");
|
|
6
|
+
return base.replace(/\.[a-z0-9]{2,5}$/i, "");
|
|
7
|
+
}
|
|
8
|
+
const VIDEO_CODEC = /^(avc|hvc|hev|dvh|av01|vp0?[89]|mp4v)/i;
|
|
9
|
+
const AUDIO_CODEC = /^(mp4a|opus|ac-3|ec-3|flac|vorbis|mp3)/i;
|
|
10
|
+
export function splitCodecs(codecs) {
|
|
11
|
+
const parts = (codecs ?? "").split(",").map((s) => s.trim());
|
|
12
|
+
return { v: parts.find((c) => VIDEO_CODEC.test(c)), a: parts.find((c) => AUDIO_CODEC.test(c)) };
|
|
13
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Public library API. Everything not exported here is internal. */
|
|
2
|
+
export { Tidepull, createTidepull } from "./tidepull.js";
|
|
3
|
+
export type { TidepullOptions, CallOptions, Listener } from "./tidepull.js";
|
|
4
|
+
export { definePlugin, PLUGIN_API_VERSION } from "./plugins.js";
|
|
5
|
+
export type { TidepullPlugin } from "./plugins.js";
|
|
6
|
+
export type { Info, Format, Extractor, Ctx, Protocol } from "./core/types.js";
|
|
7
|
+
export type { TidepullEvent, Log } from "./core/events.js";
|
|
8
|
+
export type { DownloadOptions } from "./core/pipeline.js";
|
|
9
|
+
export type { HttpOptions } from "./core/http.js";
|
|
10
|
+
export { Http } from "./core/http.js";
|
|
11
|
+
export { TidepullError } from "./core/errors.js";
|
|
12
|
+
export { selectFormats, DEFAULT_FORMAT } from "./core/selector.js";
|
|
13
|
+
export { renderTemplate, sanitize } from "./core/template.js";
|
|
14
|
+
export { parseMaster as parseHlsMaster, parseMedia as parseHlsMedia } from "./core/hls.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Public library API. Everything not exported here is internal. */
|
|
2
|
+
export { Tidepull, createTidepull } from "./tidepull.js";
|
|
3
|
+
export { definePlugin, PLUGIN_API_VERSION } from "./plugins.js";
|
|
4
|
+
export { Http } from "./core/http.js";
|
|
5
|
+
export { TidepullError } from "./core/errors.js";
|
|
6
|
+
export { selectFormats, DEFAULT_FORMAT } from "./core/selector.js";
|
|
7
|
+
export { renderTemplate, sanitize } from "./core/template.js";
|
|
8
|
+
export { parseMaster as parseHlsMaster, parseMedia as parseHlsMedia } from "./core/hls.js";
|
package/dist/loader.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type TidepullPlugin } from "./plugins.js";
|
|
2
|
+
export declare function validatePlugin(p: unknown, source: string): TidepullPlugin;
|
|
3
|
+
/** SECURITY: this executes the file's code with your privileges. Only load plugins you trust. */
|
|
4
|
+
export declare function loadPlugin(file: string): Promise<TidepullPlugin>;
|
|
5
|
+
/** Each path may be a plugin file, or a directory of plugin files and/or `<name>/index.*` folders (not recursive). */
|
|
6
|
+
export declare function loadPlugins(paths: string[]): Promise<TidepullPlugin[]>;
|
|
7
|
+
export declare function defaultPluginDir(env?: NodeJS.ProcessEnv): string;
|