-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
drm_engine.js
2422 lines (2098 loc) · 79.2 KB
/
drm_engine.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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.media.DrmEngine');
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.media.Transmuxer');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.util.BufferUtils');
goog.require('shaka.util.Destroyer');
goog.require('shaka.util.Error');
goog.require('shaka.util.EventManager');
goog.require('shaka.util.FakeEvent');
goog.require('shaka.util.IDestroyable');
goog.require('shaka.util.Iterables');
goog.require('shaka.util.Lazy');
goog.require('shaka.util.MapUtils');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.Platform');
goog.require('shaka.util.PublicPromise');
goog.require('shaka.util.StreamUtils');
goog.require('shaka.util.StringUtils');
goog.require('shaka.util.Timer');
goog.require('shaka.util.Uint8ArrayUtils');
/** @implements {shaka.util.IDestroyable} */
shaka.media.DrmEngine = class {
/**
* @param {shaka.media.DrmEngine.PlayerInterface} playerInterface
* @param {number=} updateExpirationTime
*/
constructor(playerInterface, updateExpirationTime = 1) {
/** @private {?shaka.media.DrmEngine.PlayerInterface} */
this.playerInterface_ = playerInterface;
/** @private {!Set.<string>} */
this.supportedTypes_ = new Set();
/** @private {MediaKeys} */
this.mediaKeys_ = null;
/** @private {HTMLMediaElement} */
this.video_ = null;
/** @private {boolean} */
this.initialized_ = false;
/** @private {boolean} */
this.initializedForStorage_ = false;
/** @private {number} */
this.licenseTimeSeconds_ = 0;
/** @private {?shaka.extern.DrmInfo} */
this.currentDrmInfo_ = null;
/** @private {shaka.util.EventManager} */
this.eventManager_ = new shaka.util.EventManager();
/**
* @private {!Map.<MediaKeySession,
* shaka.media.DrmEngine.SessionMetaData>}
*/
this.activeSessions_ = new Map();
/** @private {!Array.<string>} */
this.offlineSessionIds_ = [];
/** @private {!shaka.util.PublicPromise} */
this.allSessionsLoaded_ = new shaka.util.PublicPromise();
/** @private {?shaka.extern.DrmConfiguration} */
this.config_ = null;
/** @private {function(!shaka.util.Error)} */
this.onError_ = (err) => {
this.allSessionsLoaded_.reject(err);
playerInterface.onError(err);
};
/**
* The most recent key status information we have.
* We may not have announced this information to the outside world yet,
* which we delay to batch up changes and avoid spurious "missing key"
* errors.
* @private {!Map.<string, string>}
*/
this.keyStatusByKeyId_ = new Map();
/**
* The key statuses most recently announced to other classes.
* We may have more up-to-date information being collected in
* this.keyStatusByKeyId_, which has not been batched up and released yet.
* @private {!Map.<string, string>}
*/
this.announcedKeyStatusByKeyId_ = new Map();
/** @private {shaka.util.Timer} */
this.keyStatusTimer_ =
new shaka.util.Timer(() => this.processKeyStatusChanges_());
/** @private {boolean} */
this.usePersistentLicenses_ = false;
/** @private {!Array.<!MediaKeyMessageEvent>} */
this.mediaKeyMessageEvents_ = [];
/** @private {boolean} */
this.initialRequestsSent_ = false;
/** @private {?shaka.util.Timer} */
this.expirationTimer_ = new shaka.util.Timer(() => {
this.pollExpiration_();
}).tickEvery(/* seconds= */ updateExpirationTime);
// Add a catch to the Promise to avoid console logs about uncaught errors.
const noop = () => {};
this.allSessionsLoaded_.catch(noop);
/** @const {!shaka.util.Destroyer} */
this.destroyer_ = new shaka.util.Destroyer(() => this.destroyNow_());
/** @private {boolean} */
this.srcEquals_ = false;
/** @private {Promise} */
this.mediaKeysAttached_ = null;
}
/** @override */
destroy() {
return this.destroyer_.destroy();
}
/**
* Destroy this instance of DrmEngine. This assumes that all other checks
* about "if it should" have passed.
*
* @private
*/
async destroyNow_() {
// |eventManager_| should only be |null| after we call |destroy|. Destroy it
// first so that we will stop responding to events.
this.eventManager_.release();
this.eventManager_ = null;
// Since we are destroying ourselves, we don't want to react to the "all
// sessions loaded" event.
this.allSessionsLoaded_.reject();
// Stop all timers. This will ensure that they do not start any new work
// while we are destroying ourselves.
this.expirationTimer_.stop();
this.expirationTimer_ = null;
this.keyStatusTimer_.stop();
this.keyStatusTimer_ = null;
// Close all open sessions.
await this.closeOpenSessions_();
// |video_| will be |null| if we never attached to a video element.
if (this.video_) {
goog.asserts.assert(!this.video_.src, 'video src must be removed first!');
try {
await this.video_.setMediaKeys(null);
} catch (error) {
// Ignore any failures while removing media keys from the video element.
}
this.video_ = null;
}
// Break references to everything else we hold internally.
this.currentDrmInfo_ = null;
this.supportedTypes_.clear();
this.mediaKeys_ = null;
this.offlineSessionIds_ = [];
this.config_ = null;
this.onError_ = () => {};
this.playerInterface_ = null;
this.srcEquals_ = false;
this.mediaKeysAttached_ = null;
}
/**
* Called by the Player to provide an updated configuration any time it
* changes.
* Must be called at least once before init().
*
* @param {shaka.extern.DrmConfiguration} config
*/
configure(config) {
this.config_ = config;
}
/**
* @param {!boolean} value
*/
setSrcEquals(value) {
this.srcEquals_ = value;
}
/**
* Initialize the drm engine for storing and deleting stored content.
*
* @param {!Array.<shaka.extern.Variant>} variants
* The variants that are going to be stored.
* @param {boolean} usePersistentLicenses
* Whether or not persistent licenses should be requested and stored for
* |manifest|.
* @return {!Promise}
*/
initForStorage(variants, usePersistentLicenses) {
this.initializedForStorage_ = true;
// There are two cases for this call:
// 1. We are about to store a manifest - in that case, there are no offline
// sessions and therefore no offline session ids.
// 2. We are about to remove the offline sessions for this manifest - in
// that case, we don't need to know about them right now either as
// we will be told which ones to remove later.
this.offlineSessionIds_ = [];
// What we really need to know is whether or not they are expecting to use
// persistent licenses.
this.usePersistentLicenses_ = usePersistentLicenses;
return this.init_(variants);
}
/**
* Initialize the drm engine for playback operations.
*
* @param {!Array.<shaka.extern.Variant>} variants
* The variants that we want to support playing.
* @param {!Array.<string>} offlineSessionIds
* @return {!Promise}
*/
initForPlayback(variants, offlineSessionIds) {
this.offlineSessionIds_ = offlineSessionIds;
this.usePersistentLicenses_ = offlineSessionIds.length > 0;
return this.init_(variants);
}
/**
* Initializes the drm engine for removing persistent sessions. Only the
* removeSession(s) methods will work correctly, creating new sessions may not
* work as desired.
*
* @param {string} keySystem
* @param {string} licenseServerUri
* @param {Uint8Array} serverCertificate
* @param {!Array.<MediaKeySystemMediaCapability>} audioCapabilities
* @param {!Array.<MediaKeySystemMediaCapability>} videoCapabilities
* @return {!Promise}
*/
initForRemoval(keySystem, licenseServerUri, serverCertificate,
audioCapabilities, videoCapabilities) {
/** @type {!Map.<string, MediaKeySystemConfiguration>} */
const configsByKeySystem = new Map();
/** @type {MediaKeySystemConfiguration} */
const config = {
audioCapabilities: audioCapabilities,
videoCapabilities: videoCapabilities,
distinctiveIdentifier: 'optional',
persistentState: 'required',
sessionTypes: ['persistent-license'],
label: keySystem, // Tracked by us, ignored by EME.
};
// TODO: refactor, don't stick drmInfos onto MediaKeySystemConfiguration
config['drmInfos'] = [{ // Non-standard attribute, ignored by EME.
keySystem: keySystem,
licenseServerUri: licenseServerUri,
distinctiveIdentifierRequired: false,
persistentStateRequired: true,
audioRobustness: '', // Not required by queryMediaKeys_
videoRobustness: '', // Same
serverCertificate: serverCertificate,
serverCertificateUri: '',
initData: null,
keyIds: null,
}];
configsByKeySystem.set(keySystem, config);
return this.queryMediaKeys_(configsByKeySystem,
/* variants= */ []);
}
/**
* Negotiate for a key system and set up MediaKeys.
* This will assume that both |usePersistentLicences_| and
* |offlineSessionIds_| have been properly set.
*
* @param {!Array.<shaka.extern.Variant>} variants
* The variants that we expect to operate with during the drm engine's
* lifespan of the drm engine.
* @return {!Promise} Resolved if/when a key system has been chosen.
* @private
*/
async init_(variants) {
goog.asserts.assert(this.config_,
'DrmEngine configure() must be called before init()!');
// ClearKey config overrides the manifest DrmInfo if present. The variants
// are modified so that filtering in Player still works.
// This comes before hadDrmInfo because it influences the value of that.
/** @type {?shaka.extern.DrmInfo} */
const clearKeyDrmInfo = this.configureClearKey_();
if (clearKeyDrmInfo) {
for (const variant of variants) {
if (variant.video) {
variant.video.drmInfos = [clearKeyDrmInfo];
}
if (variant.audio) {
variant.audio.drmInfos = [clearKeyDrmInfo];
}
}
}
const hadDrmInfo = variants.some((variant) => {
if (variant.video && variant.video.drmInfos.length) {
return true;
}
if (variant.audio && variant.audio.drmInfos.length) {
return true;
}
return false;
});
// When preparing to play live streams, it is possible that we won't know
// about some upcoming encrypted content. If we initialize the drm engine
// with no key systems, we won't be able to play when the encrypted content
// comes.
//
// To avoid this, we will set the drm engine up to work with as many key
// systems as possible so that we will be ready.
if (!hadDrmInfo) {
const servers = shaka.util.MapUtils.asMap(this.config_.servers);
shaka.media.DrmEngine.replaceDrmInfo_(variants, servers);
}
// Make sure all the drm infos are valid and filled in correctly.
for (const variant of variants) {
const drmInfos = this.getVariantDrmInfos_(variant);
for (const info of drmInfos) {
shaka.media.DrmEngine.fillInDrmInfoDefaults_(
info,
shaka.util.MapUtils.asMap(this.config_.servers),
shaka.util.MapUtils.asMap(this.config_.advanced || {}),
this.config_.keySystemsMapping);
}
}
/** @type {!Map.<string, MediaKeySystemConfiguration>} */
let configsByKeySystem;
// We should get the decodingInfo results for the variants after we filling
// in the drm infos, and before queryMediaKeys_().
await shaka.util.StreamUtils.getDecodingInfosForVariants(variants,
this.usePersistentLicenses_, this.srcEquals_);
const hasDrmInfo = hadDrmInfo || Object.keys(this.config_.servers).length;
// An unencrypted content is initialized.
if (!hasDrmInfo) {
this.initialized_ = true;
return Promise.resolve();
}
const p = this.queryMediaKeys_(configsByKeySystem, variants);
// TODO(vaage): Look into the assertion below. If we do not have any drm
// info, we create drm info so that content can play if it has drm info
// later.
// However it is okay if we fail to initialize? If we fail to initialize,
// it means we won't be able to play the later-encrypted content, which is
// not okay.
// If the content did not originally have any drm info, then it doesn't
// matter if we fail to initialize the drm engine, because we won't need it
// anyway.
return hadDrmInfo ? p : p.catch(() => {});
}
/**
* Attach MediaKeys to the video element
* @return {Promise}
* @private
*/
async attachMediaKeys_() {
if (this.video_.mediaKeys) {
return;
}
// An attach process has already started, let's wait it out
if (this.mediaKeysAttached_) {
await this.mediaKeysAttached_;
return;
}
try {
this.mediaKeysAttached_ = this.video_.setMediaKeys(this.mediaKeys_);
await this.mediaKeysAttached_;
} catch (exception) {
goog.asserts.assert(exception instanceof Error, 'Wrong error type!');
this.onError_(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.FAILED_TO_ATTACH_TO_VIDEO,
exception.message));
}
this.destroyer_.ensureNotDestroyed();
}
/**
* Processes encrypted event and start licence challenging
* @return {!Promise}
* @private
*/
async onEncryptedEvent_(event) {
/**
* MediaKeys should be added when receiving an encrypted event. Setting
* mediaKeys before could result into encrypted event not being fired on
* some browsers
*/
await this.attachMediaKeys_();
this.newInitData(
event.initDataType,
shaka.util.BufferUtils.toUint8(event.initData));
}
/**
* Start processing events.
* @param {HTMLMediaElement} video
* @return {!Promise}
*/
async attach(video) {
if (!this.mediaKeys_) {
// Unencrypted, or so we think. We listen for encrypted events in order
// to warn when the stream is encrypted, even though the manifest does
// not know it.
// Don't complain about this twice, so just listenOnce().
// FIXME: This is ineffective when a prefixed event is translated by our
// polyfills, since those events are only caught and translated by a
// MediaKeys instance. With clear content and no polyfilled MediaKeys
// instance attached, you'll never see the 'encrypted' event on those
// platforms (Safari).
this.eventManager_.listenOnce(video, 'encrypted', (event) => {
this.onError_(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.ENCRYPTED_CONTENT_WITHOUT_DRM_INFO));
});
return;
}
this.video_ = video;
this.eventManager_.listenOnce(this.video_, 'play', () => this.onPlay_());
if ('webkitCurrentPlaybackTargetIsWireless' in this.video_) {
this.eventManager_.listen(this.video_,
'webkitcurrentplaybacktargetiswirelesschanged',
() => this.closeOpenSessions_());
}
const manifestInitData = this.currentDrmInfo_.initData.find(
(initDataOverride) => initDataOverride.initData.length > 0);
/**
* We can attach media keys before the playback actually begins when:
* - Using legacy implementations requires MediaKeys to be set before
* having webkitneedkey / msneedkey event, which will be translated as
* an encrypted event by the polyfills
* - Some initData already has been generated (through the manifest)
* - In case of an offline session
*/
if (manifestInitData ||
shaka.util.Platform.isMediaKeysPolyfilled() ||
this.offlineSessionIds_.length) {
await this.attachMediaKeys_();
}
this.createOrLoad();
// Explicit init data for any one stream or an offline session is
// sufficient to suppress 'encrypted' events for all streams.
if (!manifestInitData && !this.offlineSessionIds_.length) {
this.eventManager_.listen(
this.video_, 'encrypted', (e) => this.onEncryptedEvent_(e));
}
}
/**
* Sets the server certificate based on the current DrmInfo.
*
* @return {!Promise}
*/
async setServerCertificate() {
goog.asserts.assert(this.initialized_,
'Must call init() before setServerCertificate');
if (!this.mediaKeys_ || !this.currentDrmInfo_) {
return;
}
if (this.currentDrmInfo_.serverCertificateUri &&
(!this.currentDrmInfo_.serverCertificate ||
!this.currentDrmInfo_.serverCertificate.length)) {
const request = shaka.net.NetworkingEngine.makeRequest(
[this.currentDrmInfo_.serverCertificateUri],
this.config_.retryParameters);
try {
const operation = this.playerInterface_.netEngine.request(
shaka.net.NetworkingEngine.RequestType.SERVER_CERTIFICATE,
request);
const response = await operation.promise;
this.currentDrmInfo_.serverCertificate =
shaka.util.BufferUtils.toUint8(response.data);
} catch (error) {
// Request failed!
goog.asserts.assert(error instanceof shaka.util.Error,
'Wrong NetworkingEngine error type!');
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.SERVER_CERTIFICATE_REQUEST_FAILED,
error);
}
if (this.destroyer_.destroyed()) {
return;
}
}
if (!this.currentDrmInfo_.serverCertificate ||
!this.currentDrmInfo_.serverCertificate.length) {
return;
}
try {
const supported = await this.mediaKeys_.setServerCertificate(
this.currentDrmInfo_.serverCertificate);
if (!supported) {
shaka.log.warning('Server certificates are not supported by the ' +
'key system. The server certificate has been ' +
'ignored.');
}
} catch (exception) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.INVALID_SERVER_CERTIFICATE,
exception.message);
}
}
/**
* Remove an offline session and delete it's data. This can only be called
* after a successful call to |init|. This will wait until the
* 'license-release' message is handled. The returned Promise will be rejected
* if there is an error releasing the license.
*
* @param {string} sessionId
* @return {!Promise}
*/
async removeSession(sessionId) {
goog.asserts.assert(this.mediaKeys_,
'Must call init() before removeSession');
const session = await this.loadOfflineSession_(sessionId);
// This will be null on error, such as session not found.
if (!session) {
shaka.log.v2('Ignoring attempt to remove missing session', sessionId);
return;
}
// TODO: Consider adding a timeout to get the 'message' event.
// Note that the 'message' event will get raised after the remove()
// promise resolves.
const tasks = [];
const found = this.activeSessions_.get(session);
if (found) {
// This will force us to wait until the 'license-release' message has been
// handled.
found.updatePromise = new shaka.util.PublicPromise();
tasks.push(found.updatePromise);
}
shaka.log.v2('Attempting to remove session', sessionId);
tasks.push(session.remove());
await Promise.all(tasks);
this.activeSessions_.delete(session);
}
/**
* Creates the sessions for the init data and waits for them to become ready.
*
* @return {!Promise}
*/
createOrLoad() {
// Create temp sessions.
const initDatas =
(this.currentDrmInfo_ ? this.currentDrmInfo_.initData : []) || [];
for (const initDataOverride of initDatas) {
this.newInitData(
initDataOverride.initDataType, initDataOverride.initData);
}
// Load each session.
for (const sessionId of this.offlineSessionIds_) {
this.loadOfflineSession_(sessionId);
}
// If we have no sessions, we need to resolve the promise right now or else
// it will never get resolved.
if (!initDatas.length && !this.offlineSessionIds_.length) {
this.allSessionsLoaded_.resolve();
}
return this.allSessionsLoaded_;
}
/**
* Called when new initialization data is encountered. If this data hasn't
* been seen yet, this will create a new session for it.
*
* @param {string} initDataType
* @param {!Uint8Array} initData
*/
newInitData(initDataType, initData) {
if (!initData.length) {
return;
}
// Suppress duplicate init data.
// Note that some init data are extremely large and can't portably be used
// as keys in a dictionary.
const metadatas = this.activeSessions_.values();
for (const metadata of metadatas) {
// Tizen 2015 and 2016 models will send multiple webkitneedkey events
// with the same init data. If the duplicates are supressed, playback
// will stall without errors.
if (shaka.util.BufferUtils.equal(initData, metadata.initData) &&
!shaka.util.Platform.isTizen2()) {
shaka.log.debug('Ignoring duplicate init data.');
return;
}
}
this.createSession(initDataType, initData,
this.currentDrmInfo_.sessionType);
}
/** @return {boolean} */
initialized() {
return this.initialized_;
}
/**
* @param {?shaka.extern.DrmInfo} drmInfo
* @return {string} */
static keySystem(drmInfo) {
return drmInfo ? drmInfo.keySystem : '';
}
/**
* @param {?string} keySystem
* @return {boolean} */
static isPlayReadyKeySystem(keySystem) {
if (keySystem) {
return !!keySystem.match(/^com\.(microsoft|chromecast)\.playready/);
}
return false;
}
/**
* @param {?string} keySystem
* @return {boolean} */
static isFairPlayKeySystem(keySystem) {
if (keySystem) {
return !!keySystem.match(/^com\.apple\.fps/);
}
return false;
}
/**
* Check if DrmEngine (as initialized) will likely be able to support the
* given content type.
*
* @param {string} contentType
* @return {boolean}
*/
willSupport(contentType) {
// Edge 14 does not report correct capabilities. It will only report the
// first MIME type even if the others are supported. To work around this,
// we say that Edge supports everything.
//
// See https://github.com/shaka-project/shaka-player/issues/1495 for details.
if (shaka.util.Platform.isLegacyEdge()) {
return true;
}
contentType = contentType.toLowerCase();
if (shaka.util.Platform.isTizen() &&
contentType.includes('codecs="ac-3"')) {
// Some Tizen devices seem to misreport AC-3 support. This works around
// the issue, by falling back to EC-3, which seems to be supported on the
// same devices and be correctly reported in all cases we have observed.
// See https://github.com/shaka-project/shaka-player/issues/2989 for
// details.
const fallback = contentType.replace('ac-3', 'ec-3');
return this.supportedTypes_.has(contentType) ||
this.supportedTypes_.has(fallback);
}
return this.supportedTypes_.has(contentType);
}
/**
* Returns the ID of the sessions currently active.
*
* @return {!Array.<string>}
*/
getSessionIds() {
const sessions = this.activeSessions_.keys();
const ids = shaka.util.Iterables.map(sessions, (s) => s.sessionId);
// TODO: Make |getSessionIds| return |Iterable| instead of |Array|.
return Array.from(ids);
}
/**
* Returns the next expiration time, or Infinity.
* @return {number}
*/
getExpiration() {
// This will equal Infinity if there are no entries.
let min = Infinity;
const sessions = this.activeSessions_.keys();
for (const session of sessions) {
if (!isNaN(session.expiration)) {
min = Math.min(min, session.expiration);
}
}
return min;
}
/**
* Returns the time spent on license requests during this session, or NaN.
*
* @return {number}
*/
getLicenseTime() {
if (this.licenseTimeSeconds_) {
return this.licenseTimeSeconds_;
}
return NaN;
}
/**
* Returns the DrmInfo that was used to initialize the current key system.
*
* @return {?shaka.extern.DrmInfo}
*/
getDrmInfo() {
return this.currentDrmInfo_;
}
/**
* Return the media keys created from the current mediaKeySystemAccess.
* @return {MediaKeys}
*/
getMediaKeys() {
return this.mediaKeys_;
}
/**
* Returns the current key statuses.
*
* @return {!Object.<string, string>}
*/
getKeyStatuses() {
return shaka.util.MapUtils.asObject(this.announcedKeyStatusByKeyId_);
}
/**
* Returns the current media key sessions.
*
* @return {!Array.<MediaKeySession>}
*/
getMediaKeySessions() {
return Array.from(this.activeSessions_.keys());
}
/**
* @param {shaka.extern.Stream} stream
* @param {string=} codecOverride
* @return {string}
* @private
*/
static computeMimeType_(stream, codecOverride) {
const realMimeType = shaka.util.MimeUtils.getFullType(stream.mimeType,
codecOverride || stream.codecs);
if (shaka.media.Transmuxer.isSupported(realMimeType)) {
// This will be handled by the Transmuxer, so use the MIME type that the
// Transmuxer will produce.
return shaka.media.Transmuxer.convertTsCodecs(stream.type, realMimeType);
}
return realMimeType;
}
/**
* @param {!Map.<string, MediaKeySystemConfiguration>} configsByKeySystem
* A dictionary of configs, indexed by key system, with an iteration order
* (insertion order) that reflects the preference for the application.
* @param {!Array.<shaka.extern.Variant>} variants
* @return {!Promise} Resolved if/when a key system has been chosen.
* @private
*/
async queryMediaKeys_(configsByKeySystem, variants) {
const drmInfosByKeySystem = new Map();
const mediaKeySystemAccess = variants.length ?
this.getKeySystemAccessFromVariants_(variants, drmInfosByKeySystem) :
await this.getKeySystemAccessByConfigs_(configsByKeySystem);
if (!mediaKeySystemAccess) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE);
}
this.destroyer_.ensureNotDestroyed();
try {
// Get the set of supported content types from the audio and video
// capabilities. Avoid duplicates so that it is easier to read what is
// supported.
this.supportedTypes_.clear();
// Store the capabilities of the key system.
const realConfig = mediaKeySystemAccess.getConfiguration();
shaka.log.v2(
'Got MediaKeySystemAccess with configuration',
realConfig);
const audioCaps = realConfig.audioCapabilities || [];
const videoCaps = realConfig.videoCapabilities || [];
for (const cap of audioCaps) {
this.supportedTypes_.add(cap.contentType.toLowerCase());
}
for (const cap of videoCaps) {
this.supportedTypes_.add(cap.contentType.toLowerCase());
}
goog.asserts.assert(this.supportedTypes_.size,
'We should get at least one supported MIME type');
if (variants.length) {
this.currentDrmInfo_ = this.createDrmInfoByInfos_(
mediaKeySystemAccess.keySystem,
drmInfosByKeySystem.get(mediaKeySystemAccess.keySystem));
} else {
this.currentDrmInfo_ = shaka.media.DrmEngine.createDrmInfoByConfigs_(
mediaKeySystemAccess.keySystem,
configsByKeySystem.get(mediaKeySystemAccess.keySystem));
}
if (!this.currentDrmInfo_.licenseServerUri) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.NO_LICENSE_SERVER_GIVEN,
this.currentDrmInfo_.keySystem);
}
const mediaKeys = await mediaKeySystemAccess.createMediaKeys();
this.destroyer_.ensureNotDestroyed();
shaka.log.info('Created MediaKeys object for key system',
this.currentDrmInfo_.keySystem);
this.mediaKeys_ = mediaKeys;
this.initialized_ = true;
await this.setServerCertificate();
this.destroyer_.ensureNotDestroyed();
} catch (exception) {
this.destroyer_.ensureNotDestroyed(exception);
// Don't rewrap a shaka.util.Error from earlier in the chain:
this.currentDrmInfo_ = null;
this.supportedTypes_.clear();
if (exception instanceof shaka.util.Error) {
throw exception;
}
// We failed to create MediaKeys. This generally shouldn't happen.
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.FAILED_TO_CREATE_CDM,
exception.message);
}
}
/**
* Get the MediaKeySystemAccess from the decodingInfos of the variants.
* @param {!Array.<shaka.extern.Variant>} variants
* @param {!Map.<string, !Array.<shaka.extern.DrmInfo>>} drmInfosByKeySystem
* A dictionary of drmInfos, indexed by key system.
* @return {MediaKeySystemAccess}
* @private
*/
getKeySystemAccessFromVariants_(variants, drmInfosByKeySystem) {
for (const variant of variants) {
// Get all the key systems in the variant that shouldHaveLicenseServer.
const drmInfos = this.getVariantDrmInfos_(variant);
for (const info of drmInfos) {
if (!drmInfosByKeySystem.has(info.keySystem)) {
drmInfosByKeySystem.set(info.keySystem, []);
}
drmInfosByKeySystem.get(info.keySystem).push(info);
}
}
if (drmInfosByKeySystem.size == 1 && drmInfosByKeySystem.has('')) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS);
}
// If we have configured preferredKeySystems, choose a preferred keySystem
// if available.
for (const preferredKeySystem of this.config_.preferredKeySystems) {
for (const variant of variants) {
const decodingInfo = variant.decodingInfos.find((decodingInfo) => {
return decodingInfo.supported &&
decodingInfo.keySystemAccess != null &&
decodingInfo.keySystemAccess.keySystem == preferredKeySystem;
});
if (decodingInfo) {
return decodingInfo.keySystemAccess;
}
}
}
// Try key systems with configured license servers first. We only have to
// try key systems without configured license servers for diagnostic
// reasons, so that we can differentiate between "none of these key
// systems are available" and "some are available, but you did not
// configure them properly." The former takes precedence.
for (const shouldHaveLicenseServer of [true, false]) {
for (const variant of variants) {
for (const decodingInfo of variant.decodingInfos) {
if (!decodingInfo.supported || !decodingInfo.keySystemAccess) {
continue;
}
const drmInfos =
drmInfosByKeySystem.get(decodingInfo.keySystemAccess.keySystem);
for (const info of drmInfos) {
if (!!info.licenseServerUri == shouldHaveLicenseServer) {
return decodingInfo.keySystemAccess;
}
}
}
}
}
return null;
}