-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathkey-loader.ts
More file actions
365 lines (339 loc) · 10.9 KB
/
key-loader.ts
File metadata and controls
365 lines (339 loc) · 10.9 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import { LoadError } from './fragment-loader';
import { LevelKey } from './level-key';
import { ErrorDetails, ErrorTypes } from '../errors';
import { LoaderContextType } from '../types/loader';
import { arrayToHex } from '../utils/hex';
import { Logger } from '../utils/logger';
import { parseKeyIdsFromTenc } from '../utils/mp4-tools';
import type { HlsConfig } from '../config';
import type EMEController from '../controller/eme-controller';
import type { EncryptedFragment, Fragment } from '../loader/fragment';
import type { ComponentAPI } from '../types/component-api';
import type { KeyLoadedData } from '../types/events';
import type {
KeyLoaderContext,
Loader,
LoaderCallbacks,
LoaderConfiguration,
LoaderResponse,
LoaderStats,
PlaylistLevelType,
} from '../types/loader';
import type { NullableNetworkDetails } from '../types/network-details';
import type { ILogger } from '../utils/logger';
import type { KeySystemFormats } from '../utils/mediakeys-helper';
export interface KeyLoaderInfo {
decryptdata: LevelKey;
keyLoadPromise?: Promise<KeyLoadedData> | null;
loader?: Loader<KeyLoaderContext> | null;
}
export default class KeyLoader extends Logger implements ComponentAPI {
private readonly config: HlsConfig;
private keyLoaderInfo: { [keyId: string]: KeyLoaderInfo | undefined } = {};
public emeController: EMEController | null = null;
constructor(config: HlsConfig, logger: ILogger) {
super('key-loader', logger);
this.config = config;
}
public abort(type?: PlaylistLevelType) {
for (const uri in this.keyLoaderInfo) {
const loader = this.keyLoaderInfo[uri]!.loader;
if (loader) {
if (type && type !== loader.context?.frag.type) {
return;
}
loader.abort();
}
}
}
public destroy() {
for (const uri in this.keyLoaderInfo) {
const loader = this.keyLoaderInfo[uri]!.loader;
if (loader) {
loader.destroy();
}
}
this.keyLoaderInfo = {};
}
public loadClear(
loadingFrag: Fragment,
encryptedFragments: Fragment[],
startFragRequested: boolean,
): Promise<void> | null {
if (this.emeController) {
return this.emeController.loadClear(
loadingFrag,
encryptedFragments,
startFragRequested,
);
}
return null;
}
public load(frag: Fragment): Promise<KeyLoadedData> {
if (
!frag.decryptdata &&
frag.encrypted &&
this.emeController &&
this.config.emeEnabled
) {
// Multiple keys, but none selected, resolve in eme-controller
return this.emeController
.selectKeySystemFormat(frag)
.then((keySystemFormat) => {
return this.loadInternal(frag, keySystemFormat);
});
}
return this.loadInternal(frag);
}
private loadInternal(
frag: Fragment,
keySystemFormat?: KeySystemFormats,
): Promise<KeyLoadedData> {
if (__USE_EME_DRM__ && keySystemFormat) {
frag.setKeyFormat(keySystemFormat);
}
const decryptdata = frag.decryptdata;
if (!decryptdata) {
const error = new Error(
keySystemFormat
? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}`
: `Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController && this.config.emeEnabled})`,
);
return Promise.reject(
createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error),
);
}
const encryptedFrag = frag as EncryptedFragment;
// Return the key-load promise
switch (decryptdata.method) {
case 'SAMPLE-AES':
case 'SAMPLE-AES-CENC':
case 'SAMPLE-AES-CTR':
if (decryptdata.keyFormat === 'identity') {
// loadKeyHTTP handles http(s) and data URLs
return this.loadKeyHTTP(encryptedFrag);
}
return this.loadKeyEME(encryptedFrag);
case 'AES-128':
case 'AES-256':
case 'AES-256-CTR':
return this.loadKeyHTTP(encryptedFrag);
default:
return Promise.reject(
createKeyLoadError(
frag,
ErrorDetails.KEY_LOAD_ERROR,
new Error(
`Key supplied with unsupported METHOD: "${decryptdata.method}"`,
),
),
);
}
}
private loadKeyEME(frag: EncryptedFragment): Promise<KeyLoadedData> {
if (this.emeController && this.config.emeEnabled) {
if (!frag.decryptdata.keyId && frag.initSegment?.data) {
const keyIds = parseKeyIdsFromTenc(
frag.initSegment.data as Uint8Array<ArrayBuffer>,
);
if (keyIds.length) {
let keyId = keyIds[0];
const keyUri = frag.decryptdata.uri;
if (keyId.some((b) => b !== 0)) {
this.log(
`Using keyId found in init segment ${arrayToHex(keyId)} keyUri: ${keyUri}`,
);
LevelKey.setKeyIdForUri(keyUri, keyId);
} else {
this.log(
`Patching empty keyId with ${arrayToHex(keyId)} keyUri: ${keyUri}`,
);
keyId = LevelKey.addKeyIdForUri(keyUri);
}
frag.decryptdata.keyId = keyId;
}
}
return this.emeController.loadKey(frag).then(() => ({
frag,
keyInfo: {
decryptdata: frag.decryptdata,
},
}));
}
return Promise.reject(
createKeyLoadError(
frag,
ErrorDetails.KEY_LOAD_ERROR,
new Error(
`emeEnabled with controller: ${this.emeController && this.config.emeEnabled})`,
),
),
);
}
private loadKeyHTTP(frag: EncryptedFragment): Promise<KeyLoadedData> {
const decryptdata = frag.decryptdata;
const uri = decryptdata.uri;
if (!uri) {
return Promise.reject(
createKeyLoadError(
frag,
ErrorDetails.KEY_LOAD_ERROR,
new Error(`Invalid key URI: "${uri}"`),
),
);
}
const cachedKeyInfo = this.keyLoaderInfo[uri];
if (cachedKeyInfo) {
// LevelKey matches previously loaded key
if (cachedKeyInfo.decryptdata.key) {
decryptdata.key = cachedKeyInfo.decryptdata.key;
cachedKeyInfo.keyLoadPromise = null;
return Promise.resolve({ frag, keyInfo: cachedKeyInfo });
}
// LevelKey loading for other fragment
if (cachedKeyInfo.keyLoadPromise) {
return cachedKeyInfo.keyLoadPromise.then((keyLoadedData) => {
decryptdata.key = cachedKeyInfo.decryptdata.key;
return { ...keyLoadedData, frag };
});
}
}
this.log(
`Loading${decryptdata.keyId ? ' keyId: ' + arrayToHex(decryptdata.keyId) : ''} URI: ${decryptdata.uri} from ${frag.type} ${frag.level}`,
);
// Load LevelKey
const config = this.config;
const Loader = config.loader;
const keyLoader = new Loader(config) as Loader<KeyLoaderContext>;
frag.keyLoader = keyLoader;
const keyInfo: KeyLoaderInfo = (this.keyLoaderInfo[uri] = {
decryptdata,
keyLoadPromise: null,
loader: keyLoader,
});
return (keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
const loaderContext: KeyLoaderContext = {
type: LoaderContextType.KEY,
keyInfo,
frag,
responseType: 'arraybuffer',
url: uri,
};
// maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
// key-loader will trigger an error and rely on stream-controller to handle retry logic.
// this will also align retry logic with fragment-loader
const loadPolicy = config.keyLoadPolicy.default;
const loaderConfig: LoaderConfiguration = {
loadPolicy,
timeout: loadPolicy.maxLoadTimeMs,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: 0,
};
const loaderCallbacks: LoaderCallbacks<KeyLoaderContext> = {
onSuccess: (
response: LoaderResponse,
stats: LoaderStats,
context: KeyLoaderContext,
networkDetails: NullableNetworkDetails,
) => {
const { frag, keyInfo, url } = context;
if (!frag.decryptdata || keyInfo !== this.keyLoaderInfo[url]) {
return reject(
createKeyLoadError(
frag,
ErrorDetails.KEY_LOAD_ERROR,
new Error('after key load, decryptdata unset or changed'),
networkDetails,
),
);
}
keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(
response.data as ArrayBuffer,
);
// detach fragment key loader on load success
frag.keyLoader = keyInfo.loader = keyInfo.keyLoadPromise = null;
resolve({ frag, keyInfo });
},
onError: (
response: { code: number; text: string },
context: KeyLoaderContext,
networkDetails: NullableNetworkDetails,
stats: LoaderStats,
) => {
this.resetLoader(context);
reject(
createKeyLoadError(
frag,
ErrorDetails.KEY_LOAD_ERROR,
new Error(
`HTTP Error ${response.code} loading key ${response.text}`,
),
networkDetails,
{ url: uri, data: undefined, ...response },
),
);
},
onTimeout: (
stats: LoaderStats,
context: KeyLoaderContext,
networkDetails: NullableNetworkDetails,
) => {
this.resetLoader(context);
reject(
createKeyLoadError(
frag,
ErrorDetails.KEY_LOAD_TIMEOUT,
new Error('key loading timed out'),
networkDetails,
),
);
},
onAbort: (
stats: LoaderStats,
context: KeyLoaderContext,
networkDetails: NullableNetworkDetails,
) => {
this.resetLoader(context);
reject(
createKeyLoadError(
frag,
ErrorDetails.INTERNAL_ABORTED,
new Error('key loading aborted'),
networkDetails,
),
);
},
};
keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
}));
}
private resetLoader(context: KeyLoaderContext) {
const { frag, keyInfo, url } = context;
const loader = keyInfo.loader;
if (frag.keyLoader === loader) {
frag.keyLoader = keyInfo.loader = keyInfo.keyLoadPromise = null;
}
delete this.keyLoaderInfo[url];
if (loader) {
loader.destroy();
}
}
}
function createKeyLoadError(
frag: Fragment,
details: ErrorDetails = ErrorDetails.KEY_LOAD_ERROR,
error: Error,
networkDetails?: NullableNetworkDetails,
response?: { url: string; data: undefined; code: number; text: string },
): LoadError {
return new LoadError({
type: ErrorTypes.NETWORK_ERROR,
details,
fatal: false,
frag,
response,
error,
networkDetails: networkDetails || null,
});
}