-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.js
256 lines (237 loc) · 7.44 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
const fetch = require("node-fetch");
const { AbortController } = require("abort-controller");
const debug = require("debug")("hls-vodtolive");
function keysToM3u8(keys) {
let m3u8 = "";
for (const keyFormat of Object.keys(keys)) {
const key = keys[keyFormat];
m3u8 += `#EXT-X-KEY:METHOD=${key.method}`;
m3u8 += key.uri ? `,URI=${key.uri}` : "";
m3u8 += key.iv ? `,IV=${key.iv}` : "";
m3u8 += key.keyId ? `,KEYID=${key.keyId}` : "";
m3u8 += key.keyFormatVersions ? `,KEYFORMATVERSIONS=${key.keyFormatVersions}` : "";
m3u8 += key.keyFormat ? `,KEYFORMAT=${key.keyFormat}` : "";
m3u8 += "\n";
}
return m3u8;
}
function daterangeAttribute (key, attr) {
if (key === "planned-duration" || key === "duration") {
return key.toUpperCase() + "=" + `${attr.toFixed(3)}`;
} else {
return key.toUpperCase() + "=" + `"${attr}"`;
}
}
function urlResolve(from, to) {
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
if (resolvedUrl.protocol === 'resolve:') {
// `from` is a relative URL.
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
}
function segToM3u8(v, i, len, nextSegment, previousSegment) {
let m3u8 = "";
if (previousSegment != null) {
if (previousSegment.discontinuity) {
if (v.initSegment) {
let byteRangeStr = "";
if (v.initSegmentByteRange) {
byteRangeStr = `,BYTERANGE="${v.initSegmentByteRange}"`;
}
m3u8 += `#EXT-X-MAP:URI="${v.initSegment}"${byteRangeStr}\n`;
}
if (v.keys) {
m3u8 += keysToM3u8(v.keys);
}
}
}
if (i === 0) {
if (v.initSegment) {
let byteRangeStr = "";
if (v.initSegmentByteRange) {
byteRangeStr = `,BYTERANGE="${v.initSegmentByteRange}"`;
}
m3u8 += `#EXT-X-MAP:URI="${v.initSegment}"${byteRangeStr}\n`;
}
if (v.keys) {
m3u8 += keysToM3u8(v.keys);
}
}
if (!v.discontinuity) {
if (v.daterange) {
const dateRangeAttributes = Object.keys(v.daterange)
.map((key) => daterangeAttribute(key, v.daterange[key]))
.join(",");
if ((nextSegment && !nextSegment.timelinePosition) && v.daterange["start-date"]) {
m3u8 += "#EXT-X-PROGRAM-DATE-TIME:" + v.daterange["start-date"] + "\n";
}
m3u8 += "#EXT-X-DATERANGE:" + dateRangeAttributes + "\n";
}
if (v.cue && v.cue.out) {
if (v.cue.scteData) {
m3u8 += "#EXT-OATCLS-SCTE35:" + v.cue.scteData + "\n";
}
if (v.cue.assetData) {
m3u8 += "#EXT-X-ASSET:" + v.cue.assetData + "\n";
}
m3u8 += "#EXT-X-CUE-OUT:DURATION=" + v.cue.duration + "\n";
}
if (v.cue && v.cue.cont) {
if (v.cue.scteData) {
m3u8 += "#EXT-X-CUE-OUT-CONT:ElapsedTime=" + v.cue.cont + ",Duration=" + v.cue.duration + ",SCTE35=" + v.cue.scteData + "\n";
} else {
m3u8 += "#EXT-X-CUE-OUT-CONT:" + v.cue.cont + "/" + v.cue.duration + "\n";
}
}
if (v.cue && v.cue.in) {
if (nextSegment && nextSegment.discontinuity && i + 1 == len - 1) {
// Do not add a closing cue-in if next is not a segment and last one in the list
} else {
m3u8 += "#EXT-X-CUE-IN" + "\n";
}
}
if (v.uri) {
if (v.timelinePosition) {
const d = new Date(v.timelinePosition);
m3u8 += "#EXT-X-PROGRAM-DATE-TIME:" + d.toISOString() + "\n";
}
m3u8 += "#EXTINF:" + v.duration.toFixed(3) + ",\n";
if (v.byteRange) {
m3u8 += `#EXT-X-BYTERANGE:${v.byteRange}\n`;
}
m3u8 += v.uri + "\n";
}
} else {
if (i != 0 && i != len - 1) {
m3u8 += "#EXT-X-DISCONTINUITY\n";
if (v.cue && v.cue.in) {
m3u8 += "#EXT-X-CUE-IN" + "\n";
}
}
if (v.daterange && i != len - 1 && !(v.daterange["CLASS"] == "com.apple.hls.interstitial" && v.daterange["CUE"])) {
const dateRangeAttributes = Object.keys(v.daterange)
.map((key) => daterangeAttribute(key, v.daterange[key]))
.join(",");
if (nextSegment && !nextSegment.timelinePosition && v.daterange["start-date"]) {
m3u8 += "#EXT-X-PROGRAM-DATE-TIME:" + v.daterange["start-date"] + "\n";
}
m3u8 += "#EXT-X-DATERANGE:" + dateRangeAttributes + "\n";
}
}
return m3u8;
}
async function fetchWithRetry(uri, opts, maxRetries, retryDelayMs, timeoutMs, debug) {
if (!debug) {
var debug = (msg) => {
if (process.env.ENVIRONMENT === "development") {
console.log(msg);
}
};
}
let tryFetchCount = 0;
const RETRY_LIMIT = maxRetries || 5;
const TIMEOUT_LIMIT = timeoutMs || 10 * 1000;
const RETRY_DELAY = retryDelayMs || 1000;
while (tryFetchCount < RETRY_LIMIT) {
tryFetchCount++;
debug(`Fetching URI -> ${uri}, attempt ${tryFetchCount} of ${maxRetries}`);
const controller = new AbortController();
const timeout = setTimeout(() => {
`Request Timeout after (${TIMEOUT_LIMIT})ms @ ${uri}`;
controller.abort();
}, TIMEOUT_LIMIT);
try {
const fetchOpts = Object.assign({ signal: controller.signal }, opts);
const response = await fetch(uri, fetchOpts);
if (response.status >= 400 && response.status < 600) {
const msg = `Bad response from URI: ${uri}\nReturned Status Code: ${response.status}`;
debug(msg);
if (tryFetchCount === maxRetries) {
return Promise.resolve(response);
}
debug(`Going to try fetch again in ${RETRY_DELAY}ms`);
await timer(RETRY_DELAY);
continue;
}
// Return Good response
return Promise.resolve(response);
} catch (err) {
debug(`Node-Fetch Error on URI: ${uri}\nFull Error -> ${err}`);
if (tryFetchCount === maxRetries) {
return Promise.reject(err);
}
continue;
} finally {
clearTimeout(timeout);
}
}
}
function findIndexReversed(arr, fn) {
const size = arr.length;
for (let i = size - 1; i >= 0; i--) {
const item = arr[i];
const verdict = fn(item);
if (verdict) {
return i;
}
}
return -1;
};
const findBottomSegItem = (arr) => {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i].hasOwnProperty('duration')) {
return arr[i];
}
}
return null;
}
const fixedNumber = (n) => {
// Avoid JS floating point error
let o = Math.round(n*100) / 100;
return o;
}
const inspectForVodTransition = (list) => {
let count = 0;
let foundVodTransition = false;
for (let i = 0; i < list.length; i++) {
if (foundVodTransition) {
count++;
}
if (list[i].vodTransition) {
foundVodTransition = true;
}
}
return [count, foundVodTransition];
};
const playlistItemWithInterstitialsMetadata = (pli) => {
const daterange = pli.attributes.attributes.daterange;
if (daterange && daterange["CLASS"] == "com.apple.hls.interstitial") {
return true;
}
return false;
};
const appendHlsInterstitialLineWithCUE = (m3u8Str, data) => {
// FOR LIVE AND CUED HLS-INTERSTITIAL TAGS, Place them at the bottom of each window
if (data) {
const dateRangeAttributes = Object.keys(data)
.map((key) => daterangeAttribute(key, data[key]))
.join(",");
m3u8Str += "#EXT-X-DATERANGE:" + dateRangeAttributes + "\n";
}
return m3u8Str;
}
module.exports = {
daterangeAttribute,
keysToM3u8,
segToM3u8,
urlResolve,
fetchWithRetry,
findIndexReversed,
findBottomSegItem,
fixedNumber,
inspectForVodTransition,
playlistItemWithInterstitialsMetadata,
appendHlsInterstitialLineWithCUE
}