-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathdrm_engine.js
1503 lines (1278 loc) · 49.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
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('shaka.media.DrmEngine');
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.util.ArrayUtils');
goog.require('shaka.util.Error');
goog.require('shaka.util.EventManager');
goog.require('shaka.util.Functional');
goog.require('shaka.util.IDestroyable');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MapUtils');
goog.require('shaka.util.PublicPromise');
goog.require('shaka.util.StringUtils');
goog.require('shaka.util.Timer');
goog.require('shaka.util.Uint8ArrayUtils');
/**
* @constructor
* @param {!shaka.net.NetworkingEngine} networkingEngine
* @param {function(!shaka.util.Error)} onError Called when an error occurs.
* @param {function(!Object.<string, string>)} onKeyStatus Called when key
* status changes. Argument is a map of hex key IDs to statuses.
* @param {function(string, number)} onExpirationUpdated
* @struct
* @implements {shaka.util.IDestroyable}
*/
shaka.media.DrmEngine = function(
networkingEngine, onError, onKeyStatus, onExpirationUpdated) {
/** @private {Array.<string>} */
this.supportedTypes_ = null;
/** @private {MediaKeys} */
this.mediaKeys_ = null;
/** @private {HTMLMediaElement} */
this.video_ = null;
/** @private {boolean} */
this.initialized_ = false;
/** @private {?shakaExtern.DrmInfo} */
this.currentDrmInfo_ = null;
/** @private {shaka.util.EventManager} */
this.eventManager_ = new shaka.util.EventManager();
/** @private {!Array.<shaka.media.DrmEngine.ActiveSession>} */
this.activeSessions_ = [];
/** @private {!Array.<string>} */
this.offlineSessionIds_ = [];
/** @private {!shaka.util.PublicPromise} */
this.allSessionsLoaded_ = new shaka.util.PublicPromise();
/** @private {shaka.net.NetworkingEngine} */
this.networkingEngine_ = networkingEngine;
/** @private {?shakaExtern.DrmConfiguration} */
this.config_ = null;
/** @private {?function(!shaka.util.Error)} */
this.onError_ = (function(err) {
this.allSessionsLoaded_.reject(err);
onError(err);
}.bind(this));
/** @private {!Object.<string, string>} */
this.keyStatusByKeyId_ = {};
/** @private {?function(!Object.<string, string>)} */
this.onKeyStatus_ = onKeyStatus;
/** @private {?function(string, number)} */
this.onExpirationUpdated_ = onExpirationUpdated;
/** @private {shaka.util.Timer} */
this.keyStatusTimer_ = new shaka.util.Timer(
this.processKeyStatusChanges_.bind(this));
/** @private {boolean} */
this.destroyed_ = false;
/** @private {boolean} */
this.isOffline_ = false;
/** @private {!Array.<!MediaKeyMessageEvent>} */
this.mediaKeyMessageEvents_ = [];
/** @private {boolean} */
this.initialRequestsSent_ = false;
/** @private {?number} */
this.expirationInterval_ = setInterval(this.pollExpiration_.bind(this), 1000);
// Add a catch to the Promise to avoid console logs about uncaught errors.
this.allSessionsLoaded_.catch(function() {});
};
/**
* @typedef {{
* loaded: boolean,
* initData: Uint8Array,
* session: !MediaKeySession,
* oldExpiration: number,
* updatePromise: shaka.util.PublicPromise
* }}
*
* @description A record to track sessions and suppress duplicate init data.
* @property {boolean} loaded
* True once the key status has been updated (to a non-pending state). This
* does not mean the session is 'usable'.
* @property {Uint8Array} initData
* The init data used to create the session.
* @property {!MediaKeySession} session
* The session object.
* @property {number} oldExpiration
* The expiration of the session on the last check. This is used to fire
* an event when it changes.
* @property {shaka.util.PublicPromise} updatePromise
* An optional Promise that will be resolved/rejected on the next update()
* call. This is used to track the 'license-release' message when calling
* remove().
*/
shaka.media.DrmEngine.ActiveSession;
/** @override */
shaka.media.DrmEngine.prototype.destroy = function() {
var Functional = shaka.util.Functional;
this.destroyed_ = true;
var async = this.activeSessions_.map(function(activeSession) {
// Ignore any errors when closing the sessions. One such error would be
// an invalid state error triggered by closing a session which has not
// generated any key requests.
// Chrome sometimes returns |undefined|: https://crbug.com/690664
var p = activeSession.session.close() || Promise.resolve();
return p.catch(Functional.noop);
});
this.allSessionsLoaded_.reject();
if (this.eventManager_)
async.push(this.eventManager_.destroy());
if (this.video_) {
goog.asserts.assert(!this.video_.src, 'video src must be removed first!');
async.push(this.video_.setMediaKeys(null).catch(Functional.noop));
}
if (this.expirationInterval_) {
clearInterval(this.expirationInterval_);
this.expirationInterval_ = null;
}
if (this.keyStatusTimer_) {
this.keyStatusTimer_.cancel();
}
this.keyStatusTimer_ = null;
this.currentDrmInfo_ = null;
this.supportedTypes_ = null;
this.mediaKeys_ = null;
this.video_ = null;
this.eventManager_ = null;
this.activeSessions_ = [];
this.offlineSessionIds_ = [];
this.networkingEngine_ = null; // We don't own it, don't destroy() it.
this.config_ = null;
this.onError_ = null;
this.onExpirationUpdated_ = null;
return Promise.all(async);
};
/**
* Called by the Player to provide an updated configuration any time it changes.
* Must be called at least once before init().
*
* @param {shakaExtern.DrmConfiguration} config
*/
shaka.media.DrmEngine.prototype.configure = function(config) {
this.config_ = config;
};
/**
* Negotiate for a key system and set up MediaKeys.
* @param {!shakaExtern.Manifest} manifest The manifest is read for MIME type
* and DRM information to query EME. If the 'clearKeys' configuration is
* used, the manifest will be modified to force the use of Clear Key.
* @param {boolean} offline True if we are storing or loading offline content.
* @return {!Promise} Resolved if/when a key system has been chosen.
*/
shaka.media.DrmEngine.prototype.init = function(manifest, offline) {
goog.asserts.assert(this.config_,
'DrmEngine configure() must be called before init()!');
/** @type {!Object.<string, MediaKeySystemConfiguration>} */
var configsByKeySystem = {};
/** @type {!Array.<string>} */
var keySystemsInOrder = [];
// |isOffline_| determines what kind of session to create. The argument to
// |prepareMediaKeyConfigs_| determines the kind of CDM to query for. So
// we still need persistent state when we are loading offline sessions.
this.isOffline_ = offline;
this.offlineSessionIds_ = manifest.offlineSessionIds;
this.prepareMediaKeyConfigs_(
manifest, offline || manifest.offlineSessionIds.length > 0,
configsByKeySystem, keySystemsInOrder);
if (!keySystemsInOrder.length) {
// Unencrypted.
this.initialized_ = true;
return Promise.resolve();
}
return this.queryMediaKeys_(configsByKeySystem, keySystemsInOrder);
};
/**
* Attach MediaKeys to the video element and start processing events.
* @param {HTMLMediaElement} video
* @return {!Promise}
*/
shaka.media.DrmEngine.prototype.attach = function(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().
this.eventManager_.listenOnce(video, 'encrypted', function(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));
}.bind(this));
return Promise.resolve();
}
this.video_ = video;
this.eventManager_.listenOnce(this.video_, 'play', this.onPlay_.bind(this));
var setMediaKeys = this.video_.setMediaKeys(this.mediaKeys_);
setMediaKeys = setMediaKeys.catch(function(exception) {
return Promise.reject(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));
});
var setServerCertificate = null;
if (this.currentDrmInfo_.serverCertificate &&
this.currentDrmInfo_.serverCertificate.length) {
setServerCertificate = this.mediaKeys_.setServerCertificate(
this.currentDrmInfo_.serverCertificate).then(function(supported) {
if (!supported) {
shaka.log.warning('Server certificates are not supported by the key' +
' system. The server certificate has been ignored.');
}
}).catch(function(exception) {
return Promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.INVALID_SERVER_CERTIFICATE,
exception.message));
});
}
return Promise.all([setMediaKeys, setServerCertificate]).then(function() {
if (this.destroyed_) return Promise.reject();
this.createOrLoad();
if (!this.currentDrmInfo_.initData.length &&
!this.offlineSessionIds_.length) {
// Explicit init data for any one stream or an offline session is
// sufficient to suppress 'encrypted' events for all streams.
var onEncrypted = /** @type {shaka.util.EventManager.ListenerType} */(
this.onEncrypted_.bind(this));
this.eventManager_.listen(this.video_, 'encrypted', onEncrypted);
}
}.bind(this)).catch(function(error) {
if (this.destroyed_) return Promise.resolve(); // Ignore destruction errors
return Promise.reject(error);
}.bind(this));
};
/**
* Removes the given offline sessions and deletes their data. Must call init()
* before this. This will wait until the 'license-release' message is handled
* and the resulting Promise will be rejected if there is an error with that.
*
* @param {!Array.<string>} sessions
* @return {!Promise}
*/
shaka.media.DrmEngine.prototype.removeSessions = function(sessions) {
goog.asserts.assert(this.mediaKeys_ || !sessions.length,
'Must call init() before removeSessions');
return Promise.all(sessions.map(function(sessionId) {
return this.loadOfflineSession_(sessionId).then(function(session) {
// This will be null on error, such as session not found.
if (session) {
var p = new shaka.util.PublicPromise();
// TODO: Consider adding a timeout to get the 'message' event.
// Note that the 'message' event will get raised after the remove()
// promise resolves.
for (var i = 0; i < this.activeSessions_.length; i++) {
if (this.activeSessions_[i].session == session) {
this.activeSessions_[i].updatePromise = p;
break;
}
}
return Promise.all([session.remove(), p]);
}
}.bind(this));
}.bind(this)));
};
/**
* Creates the sessions for the init data and waits for them to become ready.
*
* @return {!Promise}
*/
shaka.media.DrmEngine.prototype.createOrLoad = function() {
var initDatas = this.currentDrmInfo_ ? this.currentDrmInfo_.initData : [];
initDatas.forEach(function(initDataOverride) {
this.createTemporarySession_(
initDataOverride.initDataType, initDataOverride.initData);
}.bind(this));
this.offlineSessionIds_.forEach(function(sessionId) {
this.loadOfflineSession_(sessionId);
}.bind(this));
if (!initDatas.length && !this.offlineSessionIds_.length)
this.allSessionsLoaded_.resolve();
return this.allSessionsLoaded_;
};
/** @return {boolean} */
shaka.media.DrmEngine.prototype.initialized = function() {
return this.initialized_;
};
/** @return {string} */
shaka.media.DrmEngine.prototype.keySystem = function() {
return this.currentDrmInfo_ ? this.currentDrmInfo_.keySystem : '';
};
/**
* Returns an array of the media types supported by the current key system.
* These will be full mime types (e.g. 'video/webm; codecs="vp8"').
*
* @return {Array.<string>}
*/
shaka.media.DrmEngine.prototype.getSupportedTypes = function() {
return this.supportedTypes_;
};
/**
* Returns the ID of the sessions currently active.
*
* @return {!Array.<string>}
*/
shaka.media.DrmEngine.prototype.getSessionIds = function() {
return this.activeSessions_.map(function(session) {
return session.session.sessionId;
});
};
/**
* Returns the next expiration time, or Infinity.
* @return {number}
*/
shaka.media.DrmEngine.prototype.getExpiration = function() {
var expirations = this.activeSessions_.map(function(session) {
var expiration = session.session.expiration;
return isNaN(expiration) ? Infinity : expiration;
});
// This will equal Infinity if there are no entries.
return Math.min.apply(Math, expirations);
};
/**
* Returns the DrmInfo that was used to initialize the current key system.
*
* @return {?shakaExtern.DrmInfo}
*/
shaka.media.DrmEngine.prototype.getDrmInfo = function() {
return this.currentDrmInfo_;
};
/**
* @param {!shakaExtern.Manifest} manifest
* @param {boolean} offline True if we are storing or loading offline content.
* @param {!Object.<string, MediaKeySystemConfiguration>} configsByKeySystem
* (Output parameter.) A dictionary of configs, indexed by key system.
* @param {!Array.<string>} keySystemsInOrder
* (Output parameter.) A list of key systems in the order in which we
* encounter them.
* @see https://goo.gl/nwdYnY for MediaKeySystemConfiguration spec
* @private
*/
shaka.media.DrmEngine.prototype.prepareMediaKeyConfigs_ =
function(manifest, offline, configsByKeySystem, keySystemsInOrder) {
var clearKeyDrmInfo = this.configureClearKey_();
manifest.periods.forEach(function(period) {
period.variants.forEach(function(variant) {
// clearKey config overrides manifest DrmInfo if present.
// The manifest is modified so that filtering in Player still works.
if (clearKeyDrmInfo) {
variant.drmInfos = [clearKeyDrmInfo];
}
variant.drmInfos.forEach(function(drmInfo) {
this.fillInDrmInfoDefaults_(drmInfo);
// Chromecast has a variant of PlayReady that uses a different key
// system ID. Since manifest parsers convert the standard PlayReady
// UUID to the standard PlayReady key system ID, here we will switch
// to the Chromecast version if we are running on that platform.
// Note that this must come after fillInDrmInfoDefaults_, since the
// player config uses the standard PlayReady ID for license server
// configuration.
if (window.cast && window.cast.__platform__) {
if (drmInfo.keySystem == 'com.microsoft.playready') {
drmInfo.keySystem = 'com.chromecast.playready';
}
}
var config = configsByKeySystem[drmInfo.keySystem];
if (!config) {
config = {
// ignore initDataTypes
audioCapabilities: [],
videoCapabilities: [],
distinctiveIdentifier: 'optional',
persistentState: offline ? 'required' : 'optional',
sessionTypes: [offline ? 'persistent-license' : 'temporary'],
label: drmInfo.keySystem,
drmInfos: [] // tracked by us, ignored by EME
};
configsByKeySystem[drmInfo.keySystem] = config;
keySystemsInOrder.push(drmInfo.keySystem);
}
config.drmInfos.push(drmInfo);
if (drmInfo.distinctiveIdentifierRequired)
config.distinctiveIdentifier = 'required';
if (drmInfo.persistentStateRequired)
config.persistentState = 'required';
var streams = [];
if (variant.video) streams.push(variant.video);
if (variant.audio) streams.push(variant.audio);
streams.forEach(function(stream) {
var ContentType = shaka.util.ManifestParserUtils.ContentType;
/** @type {!Array.<!MediaKeySystemMediaCapability>} */
var capabilities = (stream.type == ContentType.VIDEO) ?
config.videoCapabilities : config.audioCapabilities;
/** @type {string} */
var robustness = ((stream.type == ContentType.VIDEO) ?
drmInfo.videoRobustness : drmInfo.audioRobustness) || '';
var fullMimeType = stream.mimeType;
if (stream.codecs) {
fullMimeType += '; codecs="' + stream.codecs + '"';
}
capabilities.push({
robustness: robustness,
contentType: fullMimeType
});
}.bind(this)); // streams.forEach (variant.video, variant.audio)
}.bind(this)); // variant.drmInfos.forEach
}.bind(this)); // periods.variants.forEach
}.bind(this)); // manifest.perios.forEach
};
/**
* @param {!Object.<string, MediaKeySystemConfiguration>} configsByKeySystem
* A dictionary of configs, indexed by key system.
* @param {!Array.<string>} keySystemsInOrder
* A list of key systems in the order in which we should query them.
* On a browser which supports multiple key systems, the order may indicate
* a real preference for the application.
* @return {!Promise} Resolved if/when a key system has been chosen.
* @private
*/
shaka.media.DrmEngine.prototype.queryMediaKeys_ =
function(configsByKeySystem, keySystemsInOrder) {
if (keySystemsInOrder.length == 1 && keySystemsInOrder[0] == '') {
return Promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS));
}
// Wait to reject this initial Promise until we have built the entire chain.
var instigator = new shaka.util.PublicPromise();
var p = instigator;
// 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.
[true, false].forEach(function(shouldHaveLicenseServer) {
keySystemsInOrder.forEach(function(keySystem) {
var config = configsByKeySystem[keySystem];
var hasLicenseServer = config.drmInfos.some(function(info) {
return !!info.licenseServerUri;
});
if (hasLicenseServer != shouldHaveLicenseServer) return;
// If there are no tracks of a type, these should be not present.
// Otherwise the query will fail.
if (config.audioCapabilities.length == 0) {
delete config.audioCapabilities;
}
if (config.videoCapabilities.length == 0) {
delete config.videoCapabilities;
}
p = p.catch(function() {
if (this.destroyed_) return Promise.reject();
return navigator.requestMediaKeySystemAccess(keySystem, [config]);
}.bind(this));
}.bind(this));
}.bind(this));
p = p.catch(function() {
return Promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE));
});
p = p.then(function(mediaKeySystemAccess) {
if (this.destroyed_) return Promise.reject();
// TODO: Remove once Edge has released a fix for https://goo.gl/qMeV7v
var isEdge = navigator.userAgent.indexOf('Edge/') >= 0;
// Store the capabilities of the key system.
var realConfig = mediaKeySystemAccess.getConfiguration();
var audioCaps = realConfig.audioCapabilities || [];
var videoCaps = realConfig.videoCapabilities || [];
var caps = audioCaps.concat(videoCaps);
this.supportedTypes_ = caps.map(function(c) { return c.contentType; });
if (isEdge) {
// 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,
// set the supported types to null, which Player will use as a signal that
// the information is not available.
// See: https://goo.gl/qMeV7v
this.supportedTypes_ = null;
}
goog.asserts.assert(!this.supportedTypes_ || this.supportedTypes_.length,
'We should get at least one supported MIME type');
var originalConfig = configsByKeySystem[mediaKeySystemAccess.keySystem];
this.createCurrentDrmInfo_(
mediaKeySystemAccess.keySystem, originalConfig,
originalConfig.drmInfos);
if (!this.currentDrmInfo_.licenseServerUri) {
return Promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.NO_LICENSE_SERVER_GIVEN));
}
return mediaKeySystemAccess.createMediaKeys();
}.bind(this)).then(function(mediaKeys) {
if (this.destroyed_) return Promise.reject();
this.mediaKeys_ = mediaKeys;
this.initialized_ = true;
}.bind(this)).catch(function(exception) {
if (this.destroyed_) return Promise.resolve(); // Ignore destruction errors
// Don't rewrap a shaka.util.Error from earlier in the chain:
this.currentDrmInfo_ = null;
this.supportedTypes_ = null;
if (exception instanceof shaka.util.Error) {
return Promise.reject(exception);
}
// We failed to create MediaKeys. This generally shouldn't happen.
return Promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.FAILED_TO_CREATE_CDM,
exception.message));
}.bind(this));
instigator.reject();
return p;
};
/**
* Use this.config_ to fill in missing values in drmInfo.
* @param {shakaExtern.DrmInfo} drmInfo
* @private
*/
shaka.media.DrmEngine.prototype.fillInDrmInfoDefaults_ = function(drmInfo) {
var keySystem = drmInfo.keySystem;
if (!keySystem) {
// This is a placeholder from the manifest parser for an unrecognized key
// system. Skip this entry, to avoid logging nonsensical errors.
return;
}
if (!drmInfo.licenseServerUri) {
var server = this.config_.servers[keySystem];
if (server) {
drmInfo.licenseServerUri = server;
} else {
shaka.log.error('No license server configured for ' + keySystem);
}
}
if (!drmInfo.keyIds) {
drmInfo.keyIds = [];
}
var advanced = this.config_.advanced[keySystem];
if (advanced) {
if (!drmInfo.distinctiveIdentifierRequired) {
drmInfo.distinctiveIdentifierRequired =
advanced.distinctiveIdentifierRequired;
}
if (!drmInfo.persistentStateRequired) {
drmInfo.persistentStateRequired = advanced.persistentStateRequired;
}
if (!drmInfo.videoRobustness) {
drmInfo.videoRobustness = advanced.videoRobustness;
}
if (!drmInfo.audioRobustness) {
drmInfo.audioRobustness = advanced.audioRobustness;
}
if (!drmInfo.serverCertificate) {
drmInfo.serverCertificate = advanced.serverCertificate;
}
}
};
/**
* Create a DrmInfo using configured clear keys.
* The server URI will be a data URI which decodes to a clearkey license.
* @return {?shakaExtern.DrmInfo} or null if clear keys are not configured.
* @private
* @see https://goo.gl/6nPdhF for the spec on the clearkey license format.
*/
shaka.media.DrmEngine.prototype.configureClearKey_ = function() {
var hasClearKeys = !shaka.util.MapUtils.empty(this.config_.clearKeys);
if (!hasClearKeys) return null;
var StringUtils = shaka.util.StringUtils;
var Uint8ArrayUtils = shaka.util.Uint8ArrayUtils;
var keys = [];
var keyIds = [];
for (var keyIdHex in this.config_.clearKeys) {
var keyHex = this.config_.clearKeys[keyIdHex];
var keyId = Uint8ArrayUtils.fromHex(keyIdHex);
var key = Uint8ArrayUtils.fromHex(keyHex);
var keyObj = {
kty: 'oct',
kid: Uint8ArrayUtils.toBase64(keyId, false),
k: Uint8ArrayUtils.toBase64(key, false)
};
keys.push(keyObj);
keyIds.push(keyObj.kid);
}
var jwkSet = {keys: keys};
var license = JSON.stringify(jwkSet);
// Use the keyids init data since is suggested by EME.
// Suggestion: https://goo.gl/R72xp4
// Format: https://goo.gl/75RCP6
var initDataStr = JSON.stringify({'kids': keyIds});
var initData = new Uint8Array(StringUtils.toUTF8(initDataStr));
var initDatas = [{initData: initData, initDataType: 'keyids'}];
return {
keySystem: 'org.w3.clearkey',
licenseServerUri: 'data:application/json;base64,' + window.btoa(license),
distinctiveIdentifierRequired: false,
persistentStateRequired: false,
audioRobustness: '',
videoRobustness: '',
serverCertificate: null,
initData: initDatas,
keyIds: []
};
};
/**
* Creates a DrmInfo object describing the settings used to initialize the
* engine.
*
* @param {string} keySystem
* @param {MediaKeySystemConfiguration} config
* @param {!Array.<shakaExtern.DrmInfo>} drmInfos
* @private
*/
shaka.media.DrmEngine.prototype.createCurrentDrmInfo_ = function(
keySystem, config, drmInfos) {
/** @type {!Array.<string>} */
var licenseServers = [];
/** @type {!Array.<!Uint8Array>} */
var serverCerts = [];
/** @type {!Array.<!shakaExtern.InitDataOverride>} */
var initDatas = [];
/** @type {!Array.<string>} */
var keyIds = [];
this.processDrmInfos_(drmInfos, licenseServers, serverCerts, initDatas,
keyIds);
if (serverCerts.length > 1) {
shaka.log.warning('Multiple unique server certificates found! ' +
'Only the first will be used.');
}
if (licenseServers.length > 1) {
shaka.log.warning('Multiple unique license server URIs found! ' +
'Only the first will be used.');
}
// TODO: This only works when all DrmInfo have the same robustness.
var audioRobustness =
config.audioCapabilities ? config.audioCapabilities[0].robustness : '';
var videoRobustness =
config.videoCapabilities ? config.videoCapabilities[0].robustness : '';
this.currentDrmInfo_ = {
keySystem: keySystem,
licenseServerUri: licenseServers[0],
distinctiveIdentifierRequired: (config.distinctiveIdentifier == 'required'),
persistentStateRequired: (config.persistentState == 'required'),
audioRobustness: audioRobustness,
videoRobustness: videoRobustness,
serverCertificate: serverCerts[0],
initData: initDatas,
keyIds: keyIds
};
};
/**
* Extract license server, server cert, and init data from DrmInfos, taking
* care to eliminate duplicates.
*
* @param {!Array.<shakaExtern.DrmInfo>} drmInfos
* @param {!Array.<string>} licenseServers
* @param {!Array.<!Uint8Array>} serverCerts
* @param {!Array.<!shakaExtern.InitDataOverride>} initDatas
* @param {!Array.<string>} keyIds
* @private
*/
shaka.media.DrmEngine.prototype.processDrmInfos_ =
function(drmInfos, licenseServers, serverCerts, initDatas, keyIds) {
/**
* @param {shakaExtern.InitDataOverride} a
* @param {shakaExtern.InitDataOverride} b
* @return {boolean}
*/
function initDataOverrideEqual(a, b) {
if (a.keyId && a.keyId == b.keyId) {
// Two initDatas with the same keyId are considered to be the same,
// unless that "same keyId" is null.
return true;
}
return a.initDataType == b.initDataType &&
shaka.util.Uint8ArrayUtils.equal(a.initData, b.initData);
}
drmInfos.forEach(function(drmInfo) {
// Aliases:
var ArrayUtils = shaka.util.ArrayUtils;
var Uint8ArrayUtils = shaka.util.Uint8ArrayUtils;
// Build an array of unique license servers.
if (licenseServers.indexOf(drmInfo.licenseServerUri) == -1) {
licenseServers.push(drmInfo.licenseServerUri);
}
// Build an array of unique server certs.
if (drmInfo.serverCertificate) {
if (ArrayUtils.indexOf(serverCerts, drmInfo.serverCertificate,
Uint8ArrayUtils.equal) == -1) {
serverCerts.push(drmInfo.serverCertificate);
}
}
// Build an array of unique init datas.
if (drmInfo.initData) {
drmInfo.initData.forEach(function(initDataOverride) {
if (ArrayUtils.indexOf(initDatas, initDataOverride,
initDataOverrideEqual) == -1) {
initDatas.push(initDataOverride);
}
});
}
if (drmInfo.keyIds) {
for (var i = 0; i < drmInfo.keyIds.length; ++i) {
if (keyIds.indexOf(drmInfo.keyIds[i]) == -1) {
keyIds.push(drmInfo.keyIds[i]);
}
}
}
});
};
/**
* @param {!MediaEncryptedEvent} event
* @private
*/
shaka.media.DrmEngine.prototype.onEncrypted_ = function(event) {
// Aliases:
var Uint8ArrayUtils = shaka.util.Uint8ArrayUtils;
var initData = new Uint8Array(event.initData);
// Suppress duplicate init data.
// Note that some init data are extremely large and can't portably be used as
// keys in a dictionary.
for (var i = 0; i < this.activeSessions_.length; ++i) {
if (Uint8ArrayUtils.equal(initData, this.activeSessions_[i].initData)) {
shaka.log.debug('Ignoring duplicate init data.');
return;
}
}
this.createTemporarySession_(event.initDataType, initData);
};
/**
* @param {string} sessionId
* @return {!Promise.<MediaKeySession>}
* @private
*/
shaka.media.DrmEngine.prototype.loadOfflineSession_ = function(sessionId) {
var session;
try {
session = this.mediaKeys_.createSession('persistent-license');
} catch (exception) {
var error = new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
exception.message);
this.onError_(error);
return Promise.reject(error);
}
this.eventManager_.listen(session, 'message',
/** @type {shaka.util.EventManager.ListenerType} */(
this.onSessionMessage_.bind(this)));
this.eventManager_.listen(session, 'keystatuseschange',
this.onKeyStatusesChange_.bind(this));
var activeSession = {
initData: null,
session: session,
loaded: false,
oldExpiration: Infinity,
updatePromise: null
};
this.activeSessions_.push(activeSession);
return session.load(sessionId).then(function(present) {
if (this.destroyed_) return;
if (!present) {
var i = this.activeSessions_.indexOf(activeSession);
goog.asserts.assert(i >= 0, 'Session must be in the array');
this.activeSessions_.splice(i, 1);
this.onError_(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.OFFLINE_SESSION_REMOVED));
return;
}
// TODO: We should get a key status change event. Remove once Chrome CDM
// is fixed.
activeSession.loaded = true;
if (this.activeSessions_.every(function(s) { return s.loaded; }))
this.allSessionsLoaded_.resolve();
return session;
}.bind(this), function(error) {
if (this.destroyed_) return;
var i = this.activeSessions_.indexOf(activeSession);
goog.asserts.assert(i >= 0, 'Session must be in the array');
this.activeSessions_.splice(i, 1);
this.onError_(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
error.message));
}.bind(this));
};
/**
* @param {string} initDataType
* @param {!Uint8Array} initData
* @private
*/
shaka.media.DrmEngine.prototype.createTemporarySession_ =
function(initDataType, initData) {
var session;
try {
if (this.isOffline_) {
session = this.mediaKeys_.createSession('persistent-license');
} else {
session = this.mediaKeys_.createSession();
}
} catch (exception) {
this.onError_(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
exception.message));
return;
}
this.eventManager_.listen(session, 'message',
/** @type {shaka.util.EventManager.ListenerType} */(
this.onSessionMessage_.bind(this)));
this.eventManager_.listen(session, 'keystatuseschange',
this.onKeyStatusesChange_.bind(this));
this.activeSessions_.push({