summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/encrypted-media/util
diff options
context:
space:
mode:
Diffstat (limited to 'testing/web-platform/tests/encrypted-media/util')
-rw-r--r--testing/web-platform/tests/encrypted-media/util/clearkey-messagehandler.js64
-rw-r--r--testing/web-platform/tests/encrypted-media/util/drm-messagehandler.js265
-rw-r--r--testing/web-platform/tests/encrypted-media/util/testmediasource.js49
-rw-r--r--testing/web-platform/tests/encrypted-media/util/utf8.js2
-rw-r--r--testing/web-platform/tests/encrypted-media/util/utils.js293
5 files changed, 673 insertions, 0 deletions
diff --git a/testing/web-platform/tests/encrypted-media/util/clearkey-messagehandler.js b/testing/web-platform/tests/encrypted-media/util/clearkey-messagehandler.js
new file mode 100644
index 0000000000..c91a57f6d4
--- /dev/null
+++ b/testing/web-platform/tests/encrypted-media/util/clearkey-messagehandler.js
@@ -0,0 +1,64 @@
+// Expect utf8decoder and utf8decoder to be TextEncoder('utf-8') and TextDecoder('utf-8') respectively
+
+function MessageHandler( keysystem, content ) {
+ this._keysystem = keysystem;
+ this._content = content;
+ this.messagehandler = MessageHandler.prototype.messagehandler.bind( this );
+ this.servercertificate = undefined;
+}
+
+MessageHandler.prototype.messagehandler = function messagehandler( messageType, message )
+{
+ if ( messageType === 'license-request' )
+ {
+ var request = fromUtf8( message );
+
+ var keys = request.kids.map( function( kid ) {
+
+ var key;
+ for( var i=0; i < this._content.keys.length; ++i )
+ {
+ if ( base64urlEncode( this._content.keys[ i ].kid ) === kid )
+ {
+ key = base64urlEncode( this._content.keys[ i ].key );
+ break;
+ }
+ }
+
+ return { kty: 'oct', kid: kid, k: key };
+
+ }.bind( this ) );
+
+ return Promise.resolve( toUtf8( { keys: keys } ) );
+ }
+ else if ( messageType === 'license-release' )
+ {
+ var release = fromUtf8( message );
+
+ // TODO: Check the license release message here
+
+ return Promise.resolve( toUtf8( { kids: release.kids } ) );
+ }
+
+ throw new TypeError( 'Unsupported message type for ClearKey' );
+};
+
+MessageHandler.prototype.createJWKSet = function createJWKSet(keyId, key) {
+ var jwkSet = '{"keys":[';
+ for (var i = 0; i < arguments.length; i++) {
+ if (i != 0)
+ jwkSet += ',';
+ jwkSet += arguments[i];
+ }
+ jwkSet += ']}';
+ return jwkSet;
+};
+
+MessageHandler.prototype.createJWK = function createJWK(keyId, key) {
+ var jwk = '{"kty":"oct","alg":"A128KW","kid":"';
+ jwk += base64urlEncode(keyId);
+ jwk += '","k":"';
+ jwk += base64urlEncode(key);
+ jwk += '"}';
+ return jwk;
+}; \ No newline at end of file
diff --git a/testing/web-platform/tests/encrypted-media/util/drm-messagehandler.js b/testing/web-platform/tests/encrypted-media/util/drm-messagehandler.js
new file mode 100644
index 0000000000..5c5577c6d6
--- /dev/null
+++ b/testing/web-platform/tests/encrypted-media/util/drm-messagehandler.js
@@ -0,0 +1,265 @@
+(function(){
+// Expect utf8decoder and utf8decoder to be TextEncoder('utf-8') and TextDecoder('utf-8') respectively
+//
+// drmconfig format:
+// { <keysystem> : { "serverURL" : <the url for the server>,
+// "httpRequestHeaders" : <map of HTTP request headers>,
+// "servertype" : "microsoft" | "drmtoday", // affects how request parameters are formed
+// "certificate" : <base64 encoded server certificate> } }
+//
+
+drmtodaysecret = Uint8Array.from( [144, 34, 109, 76, 134, 7, 97, 107, 98, 251, 140, 28, 98, 79, 153, 222, 231, 245, 154, 226, 193, 1, 213, 207, 152, 204, 144, 15, 13, 2, 37, 236] );
+
+drmconfig = {
+ "com.widevine.alpha": [ {
+ "serverURL": "https://lic.staging.drmtoday.com/license-proxy-widevine/cenc/",
+ "servertype" : "drmtoday",
+ "merchant" : "w3c-eme-test",
+ "secret" : drmtodaysecret
+ } ],
+ "com.microsoft.playready": [ {
+ "serverURL": "http://playready-testserver.azurewebsites.net/rightsmanager.asmx",
+ "servertype": "microsoft",
+ "sessionTypes" : [ "persistent-usage-record" ],
+ "certificate" : "Q0hBSQAAAAEAAAUEAAAAAAAAAAJDRVJUAAAAAQAAAfQAAAFkAAEAAQAAAFjt9G6KdS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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgFBsYXlSZWFkeSBTTDAgTWV0ZXJpbmcgUm9vdCBDQQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgDEuMC4wLjEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEACAAAAJAAAQBArAKJsEIDWNG5ulOgLvSUb8I2zZ0c5lZGYvpIO56Z0UNk/uC4Mq3jwXQUUN6m/48V5J/vuLDhWu740aRQc1dDDAAAAgCGTWHP8iVuQixWizwoABz7PhUnZYWEugUht5sYKNk23h2Cao/D5uf6epDVyilG8fZKLvufXc/+fkNOtEKT+sWr"
+ },
+ {
+ "serverURL": "http://playready.directtaps.net/pr/svc/rightsmanager.asmx",
+ "servertype": "microsoft",
+ "sessionTypes" : [ "persistent-usage-record" ],
+ "certificate" : "Q0hBSQAAAAEAAAUEAAAAAAAAAAJDRVJUAAAAAQAAAfQAAAFkAAEAAQAAAFjt9G6KdSncCkrjbTQPN+/2AAAAAAAAAAAAAAAJIPbrW9dj0qydQFIomYFHOwbhGZVGP2ZsPwcvjh+NFkP/////AAAAAAAAAAAAAAAAAAAAAAABAAoAAABYxw6TjIuUUmvdCcl00t4RBAAAADpodHRwOi8vcGxheXJlYWR5LmRpcmVjdHRhcHMubmV0L3ByL3N2Yy9yaWdodHNtYW5hZ2VyLmFzbXgAAAAAAQAFAAAADAAAAAAAAQAGAAAAXAAAAAEAAQIAAAAAADBRmRRpqV4cfRLcWz9WoXIGZ5qzD9xxJe0CSI2mXJQdPHEFZ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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEACAAAAJAAAQBArAKJsEIDWNG5ulOgLvSUb8I2zZ0c5lZGYvpIO56Z0UNk/uC4Mq3jwXQUUN6m/48V5J/vuLDhWu740aRQc1dDDAAAAgCGTWHP8iVuQixWizwoABz7PhUnZYWEugUht5sYKNk23h2Cao/D5uf6epDVyilG8fZKLvufXc/+fkNOtEKT+sWr"
+ },
+ {
+ "serverURL": "https://lic.staging.drmtoday.com/license-proxy-headerauth/drmtoday/RightsManager.asmx",
+ "servertype" : "drmtoday",
+ "sessionTypes" : [ "temporary", "persistent-usage-record", "persistent-license" ],
+ "merchant" : "w3c-eme-test",
+ "secret" : drmtodaysecret
+ } ]
+};
+
+
+var keySystemWrappers = {
+ // Key System wrappers map messages and pass to a handler, then map the response and return to caller
+ //
+ // function wrapper(handler, messageType, message, params)
+ //
+ // where:
+ // Promise<response> handler(messageType, message, responseType, headers, params);
+ //
+
+ 'com.widevine.alpha': function(handler, messageType, message, params) {
+ return handler.call(this, messageType, new Uint8Array(message), 'json', null, params).then(function(response){
+ return base64DecodeToUnit8Array(response.license);
+ });
+ },
+
+ 'com.microsoft.playready': function(handler, messageType, message, params) {
+ var msg, xmlDoc;
+ var licenseRequest = null;
+ var headers = {};
+ var parser = new DOMParser();
+ var dataview = new Uint16Array(message);
+
+ msg = String.fromCharCode.apply(null, dataview);
+ xmlDoc = parser.parseFromString(msg, 'application/xml');
+
+ if (xmlDoc.getElementsByTagName('Challenge')[0]) {
+ var challenge = xmlDoc.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue;
+ if (challenge) {
+ licenseRequest = atob(challenge);
+ }
+ }
+
+ var headerNameList = xmlDoc.getElementsByTagName('name');
+ var headerValueList = xmlDoc.getElementsByTagName('value');
+ for (var i = 0; i < headerNameList.length; i++) {
+ headers[headerNameList[i].childNodes[0].nodeValue] = headerValueList[i].childNodes[0].nodeValue;
+ }
+ // some versions of the PlayReady CDM return 'Content' instead of 'Content-Type',
+ // but the license server expects 'Content-Type', so we fix it up here.
+ if (headers.hasOwnProperty('Content')) {
+ headers['Content-Type'] = headers.Content;
+ delete headers.Content;
+ }
+
+ return handler.call(this, messageType, licenseRequest, 'arraybuffer', headers, params).catch(function(response){
+ return response.text().then( function( error ) { throw error; } );
+ });
+ }
+};
+
+const requestConstructors = {
+ // Server request construction functions
+ //
+ // Promise<request> constructRequest(config, sessionType, content, messageType, message, params)
+ //
+ // request = { url: ..., headers: ..., body: ... }
+ //
+ // content = { assetId: ..., variantId: ..., key: ... }
+ // params = { expiration: ... }
+
+ 'drmtoday': function(config, sessionType, content, messageType, message, headers, params) {
+ var optData = JSON.stringify({merchant: config.merchant, userId:"12345", sessionId:""});
+ var crt = {};
+ if (messageType === 'license-request') {
+ crt = {assetId: content.assetId,
+ outputProtection: {digital : false, analogue: false, enforce: false},
+ storeLicense: (sessionType === 'persistent-license')};
+
+ if (!params || (params.expiration === undefined && params.playDuration === undefined)) {
+ crt.profile = {purchase: {}};
+ } else {
+ var expiration = params.expiration || (Date.now().valueOf() + 3600000),
+ playDuration = params.playDuration || 3600000;
+
+ crt.profile = {rental: {absoluteExpiration: (new Date(expiration)).toISOString(),
+ playDuration: playDuration } };
+ }
+
+ if (content.variantId !== undefined) {
+ crt.variantId = content.variantId;
+ }
+ }
+
+ return JWT.encode("HS256", {optData: optData, crt: JSON.stringify([crt])}, config.secret).then(function(jwt){
+ headers = headers || {};
+ headers['x-dt-auth-token'] = jwt;
+ return {url: config.serverURL, headers: headers, body: message};
+ });
+ },
+
+ 'microsoft': function(config, sessionType, content, messageType, message, headers, params) {
+ var url = config.serverURL;
+ if (messageType === 'license-request') {
+ url += "?";
+ if (sessionType === 'temporary' || sessionType === 'persistent-usage-record') {
+ url += "UseSimpleNonPersistentLicense=1&";
+ }
+ if (sessionType === 'persistent-usage-record') {
+ url += "SecureStop=1&";
+ }
+ url += "PlayEnablers=B621D91F-EDCC-4035-8D4B-DC71760D43E9&"; // disable output protection
+ url += "ContentKey=" + btoa(String.fromCharCode.apply(null, content.key));
+ return url;
+ }
+
+ // TODO: Include expiration time in URL
+ return Promise.resolve({url: url, headers: headers, body: message});
+ }
+};
+
+MessageHandler = function(keysystem, content, sessionType) {
+ sessionType = sessionType || "temporary";
+
+ this._keysystem = keysystem;
+ this._content = content;
+ this._sessionType = sessionType;
+ try {
+ this._drmconfig = drmconfig[this._keysystem].filter(function(drmconfig) {
+ return drmconfig.sessionTypes === undefined || (drmconfig.sessionTypes.indexOf(sessionType) !== -1);
+ })[0];
+ this._requestConstructor = requestConstructors[this._drmconfig.servertype];
+
+ this.messagehandler = keySystemWrappers[keysystem].bind(this, MessageHandler.prototype.messagehandler);
+
+ if (this._drmconfig && this._drmconfig.certificate) {
+ this.servercertificate = stringToUint8Array(atob(this._drmconfig.certificate));
+ }
+ } catch(e) {
+ return null;
+ }
+}
+
+MessageHandler.prototype.messagehandler = function messagehandler(messageType, message, responseType, headers, params) {
+
+ var variantId = params ? params.variantId : undefined;
+ var key;
+ if( variantId ) {
+ var keys = this._content.keys.filter(function(k){return k.variantId === variantId;});
+ if (keys[0]) key = keys[0].key;
+ }
+ if (!key) {
+ key = this._content.keys[0].key;
+ }
+
+ var content = {assetId: this._content.assetId,
+ variantId: variantId,
+ key: key};
+
+ return this._requestConstructor(this._drmconfig, this._sessionType, content, messageType, message, headers, params).then(function(request){
+ return fetch(request.url, {
+ method: 'POST',
+ headers: request.headers,
+ body: request.body });
+ }).then(function(fetchresponse){
+ if(fetchresponse.status !== 200) {
+ throw fetchresponse;
+ }
+
+ if(responseType === 'json') {
+ return fetchresponse.json();
+ } else if(responseType === 'arraybuffer') {
+ return fetchresponse.arrayBuffer();
+ }
+ });
+}
+
+})();
+
+(function() {
+
+ var subtlecrypto = window.crypto.subtle;
+
+ // Encoding / decoding utilities
+ function b64pad(b64) { return b64+"==".substr(0,(b64.length%4)?(4-b64.length%4):0); }
+ function str2b64url(str) { return btoa(str).replace(/=+$/g, '').replace(/\+/g, "-").replace(/\//g, "_"); }
+ function b64url2str(b64) { return atob(b64pad(b64.replace(/\-/g, "+").replace(/\_/g, "/"))); }
+ function str2ab(str) { return Uint8Array.from( str.split(''), function(s){return s.charCodeAt(0)} ); }
+ function ab2str(ab) { return String.fromCharCode.apply(null, new Uint8Array(ab)); }
+
+ function jwt2webcrypto(alg) {
+ if (alg === "HS256") return {name: "HMAC", hash: "SHA-256", length: 256};
+ else if (alg === "HS384") return { name: "HMAC", hash: "SHA-384", length: 384};
+ else if (alg === "HS512") return { name: "HMAC", hash: "SHA-512", length: 512};
+ else throw new Error("Unrecognized JWT algorithm: " + alg);
+ }
+
+ JWT = {
+ encode: function encode(alg, claims, secret) {
+ var algorithm = jwt2webcrypto(alg);
+ if (secret.byteLength !== algorithm.length / 8) throw new Error("Unexpected secret length: " + secret.byteLength);
+
+ if (!claims.iat) claims.iat = ((Date.now() / 1000) | 0) - 60;
+ if (!claims.jti) {
+ var nonce = new Uint8Array(16);
+ window.crypto.getRandomValues(nonce);
+ claims.jti = str2b64url( ab2str(nonce) );
+ }
+
+ var header = {typ: "JWT", alg: alg};
+ var plaintext = str2b64url(JSON.stringify(header)) + '.' + str2b64url(JSON.stringify(claims));
+ return subtlecrypto.importKey("raw", secret, algorithm, false, [ "sign" ]).then( function(key) {
+ return subtlecrypto.sign(algorithm, key, str2ab(plaintext));
+ }).then(function(hmac){
+ return plaintext + '.' + str2b64url(ab2str(hmac));
+ });
+ },
+
+ decode: function decode(jwt, secret) {
+ var jwtparts = jwt.split('.');
+ var header = JSON.parse( b64url2str(jwtparts[0]));
+ var claims = JSON.parse( b64url2str(jwtparts[1]));
+ var hmac = str2ab(b64url2str(jwtparts[2]));
+ var algorithm = jwt2webcrypto(header.alg);
+ if (secret.byteLength !== algorithm.length / 8) throw new Error("Unexpected secret length: " + secret.byteLength);
+
+ return subtlecrypto.importKey("raw", secret, algorithm, false, ["sign", "verify"]).then(function(key) {
+ return subtlecrypto.verify(algorithm, key, hmac, str2ab(jwtparts[0] + '.' + jwtparts[1]));
+ }).then(function(success){
+ if (!success) throw new Error("Invalid signature");
+ return claims;
+ });
+ }
+ };
+})();
diff --git a/testing/web-platform/tests/encrypted-media/util/testmediasource.js b/testing/web-platform/tests/encrypted-media/util/testmediasource.js
new file mode 100644
index 0000000000..47cfeb4512
--- /dev/null
+++ b/testing/web-platform/tests/encrypted-media/util/testmediasource.js
@@ -0,0 +1,49 @@
+function testmediasource(config) {
+
+ return new Promise(function(resolve, reject) {
+ // Fetch the media resources
+ var fetches = [config.audioPath, config.videoPath].map(function(path) {
+ return fetch(path).then(function(response) {
+ if (!response.ok) throw new Error('Resource fetch failed');
+ return response.arrayBuffer();
+ });
+ });
+
+ Promise.all(fetches).then(function(resources) {
+ config.audioMedia = resources[0];
+ config.videoMedia = resources[1];
+
+ // Create media source
+ var source = new MediaSource();
+ source.done = new Promise(function(resolvesource,rejectsource){
+
+ // Create and fill source buffers when the media source is opened
+ source.addEventListener('sourceopen', onSourceOpen);
+ resolve(source);
+
+ function onSourceOpen(event) {
+ var audioSourceBuffer = source.addSourceBuffer(config.audioType),
+ videoSourceBuffer = source.addSourceBuffer(config.videoType);
+
+ audioSourceBuffer.addEventListener('updateend',onUpdateEnd);
+ videoSourceBuffer.addEventListener('updateend',onUpdateEnd);
+
+ audioSourceBuffer.appendBuffer(config.audioMedia);
+ videoSourceBuffer.appendBuffer(config.videoMedia);
+
+ function onUpdateEnd(event){
+ event.target.removeEventListener('updateend', onUpdateEnd);
+ if (!audioSourceBuffer.updating && !videoSourceBuffer.updating) {
+ if (source.readyState !== 'open') {
+ rejectsource(new Error("Media source error"));
+ } else {
+ source.endOfStream();
+ resolvesource();
+ }
+ }
+ }
+ }
+ });
+ });
+ });
+}
diff --git a/testing/web-platform/tests/encrypted-media/util/utf8.js b/testing/web-platform/tests/encrypted-media/util/utf8.js
new file mode 100644
index 0000000000..aea5ad7626
--- /dev/null
+++ b/testing/web-platform/tests/encrypted-media/util/utf8.js
@@ -0,0 +1,2 @@
+toUtf8 = function( o ) { return new TextEncoder().encode( JSON.stringify( o ) ); }
+fromUtf8 = function( t ) { return JSON.parse( new TextDecoder().decode( t ) ); }
diff --git a/testing/web-platform/tests/encrypted-media/util/utils.js b/testing/web-platform/tests/encrypted-media/util/utils.js
new file mode 100644
index 0000000000..79f8c7ea6d
--- /dev/null
+++ b/testing/web-platform/tests/encrypted-media/util/utils.js
@@ -0,0 +1,293 @@
+function testnamePrefix( qualifier, keysystem ) {
+ return ( qualifier || '' ) + ( keysystem === 'org.w3.clearkey' ? keysystem : 'drm' );
+}
+
+function getInitData(initDataType) {
+
+ // FIXME: This is messed up, because here we are hard coding the key ids for the different content
+ // that we use for clearkey testing: webm and mp4. For keyids we return the mp4 one
+ //
+ // The content used with the DRM today servers has a different key id altogether
+
+ if (initDataType == 'webm') {
+ return new Uint8Array([
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
+ ]);
+ }
+
+ if (initDataType == 'cenc') {
+ return new Uint8Array([
+ 0x00, 0x00, 0x00, 0x34, // size
+ 0x70, 0x73, 0x73, 0x68, // 'pssh'
+ 0x01, // version = 1
+ 0x00, 0x00, 0x00, // flags
+ 0x10, 0x77, 0xEF, 0xEC, 0xC0, 0xB2, 0x4D, 0x02, // Common SystemID
+ 0xAC, 0xE3, 0x3C, 0x1E, 0x52, 0xE2, 0xFB, 0x4B,
+ 0x00, 0x00, 0x00, 0x01, // key count
+ 0x00, 0x00, 0x00, 0x00, 0x03, 0xd2, 0xfc, 0x41, // key id
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00 // datasize
+ ]);
+ }
+ if (initDataType == 'keyids') {
+ var keyId = new Uint8Array([
+ 0x00, 0x00, 0x00, 0x00, 0x03, 0xd2, 0xfc, 0x41,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ ]);
+ return stringToUint8Array(createKeyIDs(keyId));
+ }
+ throw 'initDataType ' + initDataType + ' not supported.';
+}
+
+function stringToUint8Array(str)
+{
+ var result = new Uint8Array(str.length);
+ for(var i = 0; i < str.length; i++) {
+ result[i] = str.charCodeAt(i);
+ }
+ return result;
+}
+// Encodes |data| into base64url string. There is no '=' padding, and the
+// characters '-' and '_' must be used instead of '+' and '/', respectively.
+function base64urlEncode(data) {
+ var result = btoa(String.fromCharCode.apply(null, data));
+ return result.replace(/=+$/g, '').replace(/\+/g, "-").replace(/\//g, "_");
+}
+// Decode |encoded| using base64url decoding.
+function base64urlDecode(encoded) {
+ return atob(encoded.replace(/\-/g, "+").replace(/\_/g, "/"));
+}
+// Decode |encoded| using base64 to a Uint8Array
+function base64DecodeToUnit8Array(encoded) {
+ return new Uint8Array( atob( encoded ).split('').map( function(c){return c.charCodeAt(0);} ) );
+}
+// Clear Key can also support Key IDs Initialization Data.
+// ref: http://w3c.github.io/encrypted-media/keyids-format.html
+// Each parameter is expected to be a key id in an Uint8Array.
+function createKeyIDs() {
+ var keyIds = '{"kids":["';
+ for (var i = 0; i < arguments.length; i++) {
+ if (i != 0) keyIds += '","';
+ keyIds += base64urlEncode(arguments[i]);
+ }
+ keyIds += '"]}';
+ return keyIds;
+}
+
+function getSupportedKeySystem() {
+ var userAgent = navigator.userAgent.toLowerCase();
+ var keysystem = undefined;
+ if (userAgent.indexOf('edge') > -1 ) {
+ keysystem = 'com.microsoft.playready';
+ } else if ( userAgent.indexOf('chrome') > -1 || userAgent.indexOf('firefox') > -1 ) {
+ keysystem = 'com.widevine.alpha';
+ }
+ return keysystem;
+}
+
+function waitForEventAndRunStep(eventName, element, func, stepTest)
+{
+ var eventCallback = function(event) {
+ if (func)
+ func(event);
+ }
+
+ element.addEventListener(eventName, stepTest.step_func(eventCallback), true);
+}
+
+function waitForEvent(eventName, element) {
+ return new Promise(function(resolve) {
+ element.addEventListener(eventName, resolve, true);
+ })
+}
+
+var consoleDiv = null;
+
+function consoleWrite(text)
+{
+ if (!consoleDiv && document.body) {
+ consoleDiv = document.createElement('div');
+ document.body.appendChild(consoleDiv);
+ }
+ var span = document.createElement('span');
+ span.appendChild(document.createTextNode(text));
+ span.appendChild(document.createElement('br'));
+ consoleDiv.appendChild(span);
+}
+
+function forceTestFailureFromPromise(test, error, message)
+{
+ test.step_func(assert_unreached)(message ? message + ': ' + error.message : error);
+}
+
+// Returns an array of audioCapabilities that includes entries for a set of
+// codecs that should cover all user agents.
+function getPossibleAudioCapabilities()
+{
+ return [
+ { contentType: 'audio/mp4; codecs="mp4a.40.2"' },
+ { contentType: 'audio/webm; codecs="opus"' },
+ ];
+}
+
+// Returns a trivial MediaKeySystemConfiguration that should be accepted,
+// possibly as a subset of the specified capabilities, by all user agents.
+function getSimpleConfiguration()
+{
+ return [ {
+ initDataTypes : [ 'webm', 'cenc', 'keyids' ],
+ audioCapabilities: getPossibleAudioCapabilities()
+ } ];
+}
+
+// Returns a MediaKeySystemConfiguration for |initDataType| that should be
+// accepted, possibly as a subset of the specified capabilities, by all
+// user agents.
+function getSimpleConfigurationForInitDataType(initDataType)
+{
+ return [ {
+ initDataTypes: [ initDataType ],
+ audioCapabilities: getPossibleAudioCapabilities()
+ } ];
+}
+
+// Returns a promise that is fulfilled with true if |initDataType| is supported,
+// by keysystem or false if not.
+function isInitDataTypeSupported(keysystem,initDataType)
+{
+ return navigator.requestMediaKeySystemAccess(
+ keysystem, getSimpleConfigurationForInitDataType(initDataType))
+ .then(function() { return true; }, function() { return false; });
+}
+
+function getSupportedInitDataTypes( keysystem )
+{
+ return [ 'cenc', 'keyids', 'webm' ].filter( isInitDataTypeSupported.bind( null, keysystem ) );
+}
+
+function arrayBufferAsString(buffer)
+{
+ var array = [];
+ Array.prototype.push.apply( array, new Uint8Array( buffer ) );
+ return '0x' + array.map( function( x ) { return x < 16 ? '0'+x.toString(16) : x.toString(16); } ).join('');
+}
+
+function dumpKeyStatuses(keyStatuses,short)
+{
+ var userAgent = navigator.userAgent.toLowerCase();
+ if (userAgent.indexOf('edge') === -1) {
+ if (!short) { consoleWrite("for (var entry of keyStatuses)"); }
+ for (var entry of keyStatuses) {
+ consoleWrite(arrayBufferAsString(entry[0]) + ": " + entry[1]);
+ }
+ if (!short) {
+ consoleWrite("for (var keyId of keyStatuses.keys())");
+ for (var keyId of keyStatuses.keys()) {
+ consoleWrite(arrayBufferAsString(keyId));
+ }
+ consoleWrite("for (var status of keyStatuses.values())");
+ for (var status of keyStatuses.values()) {
+ consoleWrite(status);
+ }
+ consoleWrite("for (var entry of keyStatuses.entries())");
+ for (var entry of keyStatuses.entries()) {
+ consoleWrite(arrayBufferAsString(entry[0]) + ": " + entry[1]);
+ }
+ consoleWrite("keyStatuses.forEach()");
+ keyStatuses.forEach(function(status, keyId) {
+ consoleWrite(arrayBufferAsString(keyId) + ": " + status);
+ });
+ }
+ } else {
+ if (!short) { consoleWrite("keyStatuses.forEach()"); }
+ keyStatuses.forEach(function(keyId, status) {
+ consoleWrite(arrayBufferAsString(keyId) + ": " + status);
+ });
+ }
+}
+
+// Verify that |keyStatuses| contains just the keys in |keys.expected|
+// and none of the keys in |keys.unexpected|. All keys should have status
+// 'usable'. Example call: verifyKeyStatuses(mediaKeySession.keyStatuses,
+// { expected: [key1], unexpected: [key2] });
+function verifyKeyStatuses(keyStatuses, keys)
+{
+ var expected = keys.expected || [];
+ var unexpected = keys.unexpected || [];
+
+ // |keyStatuses| should have same size as number of |keys.expected|.
+ assert_equals(keyStatuses.size, expected.length, "keystatuses should have expected size");
+
+ // All |keys.expected| should be found.
+ expected.map(function(key) {
+ assert_true(keyStatuses.has(key), "keystatuses should have the expected keys");
+ assert_equals(keyStatuses.get(key), 'usable', "keystatus value should be 'usable'");
+ });
+
+ // All |keys.unexpected| should not be found.
+ unexpected.map(function(key) {
+ assert_false(keyStatuses.has(key), "keystatuses should not have unexpected keys");
+ assert_equals(keyStatuses.get(key), undefined, "keystatus for unexpected key should be undefined");
+ });
+}
+
+// This function checks that calling |testCase.func| returns a
+// rejected Promise with the error.name equal to
+// |testCase.exception|.
+function test_exception(testCase /*...*/) {
+ var func = testCase.func;
+ var exception = testCase.exception;
+ var args = Array.prototype.slice.call(arguments, 1);
+
+ // This should really be rewritten in terms of the promise_rejects_*
+ // testharness utility functions, but that needs the async test involved
+ // passed in, and we don't have that here.
+ return func.apply(null, args).then(
+ function (result) {
+ assert_unreached(format_value(func));
+ },
+ function (error) {
+ assert_not_equals(error.message, "", format_value(func));
+ // `exception` is a string name for the error. We can differentiate
+ // JS Errors from DOMExceptions by checking whether
+ // window[exception] exists. If it does, expectedError is the name
+ // of a JS Error subclass and window[exception] is the constructor
+ // for that subclass. Otherwise it's a name for a DOMException.
+ if (window[exception]) {
+ assert_throws_js(window[exception],
+ () => { throw error; },
+ format_value(func));
+ } else {
+ assert_throws_dom(exception,
+ () => { throw error; },
+ format_value(func));
+ }
+ }
+ );
+}
+
+// Check that the events sequence (array of strings) matches the pattern (array of either strings, or
+// arrays of strings, with the latter representing a possibly repeating sub-sequence)
+function checkEventSequence(events,pattern) {
+ function th(i) { return i + (i < 4 ? ["th", "st", "nd", "rd"][i] : "th"); }
+ var i = 0, j=0, k=0;
+ while(i < events.length && j < pattern.length) {
+ if (!Array.isArray(pattern[j])) {
+ assert_equals(events[i], pattern[j], "Expected " + th(i+1) + " event to be '" + pattern[j] + "'");
+ ++i;
+ ++j;
+ } else {
+ assert_equals(events[i], pattern[j][k], "Expected " + th(i+1) + " event to be '" + pattern[j][k] + "'");
+ ++i;
+ k = (k+1)%pattern[j].length;
+ if (k === 0 && events[i] !== pattern[j][0]) {
+ ++j;
+ }
+ }
+ }
+ assert_equals(i,events.length,"Received more events than expected");
+ assert_equals(j,pattern.length,"Expected more events than received");
+}
+
+