Bug#17470 Example code

I had an request from two meetings ago to produce some example code for pre-loading a MediaKeys instance independent of the HTMLMediaElements that the MediaKeys object may later be attached to.

Here is the example I propose:
--------
<script>

var cdm;

// Preload some keys when page loads
function load()
{
  // Create a MediaKeys instance for the desired CDM not associated with an HTMLMediaElement
  cdm = new MediaKeys("com.example.somesystem");
  if (!cdm)
      throw "Could not create MediaKeys";

  // Create a new key session using the MediaKeys instance
  var keySession = cdm.createSession(NULL, NULL);
  if (!keySession)
      throw "Could not create MediaKeySession";
  keySession.onkeymessage="handleMessage(event)";

  // Load an application defined key package into the key session
  // The key package can be hard-coded into the page or loaded as a resource
  // Loading the key package may cause additional key messages to be sent
  var Uint8Array keyToPreload;
  keySession.addKey(keyToPreload);
  keySession.close();
}

// Respond to key message
function handleMessage(event)
{
    var keySession = event.target;
    var message = event.message;

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://.../getkey", false);
    xmlhttp.send(message);

    var key = new Uint8Array(xmlhttp.response);
    keySession.addKey(key);
}

// Attach pre-initialized MediaKeys to an HTMLMediaElement
function setMediaKeys()
{
  var video = event.target;
  var initData = event.initData;

  if (!cdm)
	throw "MediaKeys was not already created!";
  if (!video.keys)
	video.keys = cdm;
  
  // Create a new key session using the mimeType and initData
  var keySession = video.keys.createSession(mimeType, initData);
  if (!keySession)
	throw "Could not create MediaKeySession";
  keySession.onkeymessage="handleMessage(event)";
}

<body onload="load()">
  <video src="foo.dash" autoplay onneedkey="setMediaKeys(event)" onkeymessage="handleMessage(event)"></video>
</body>

</script>
--------

I believe this should all work within the confines of the current draft. I am intentionally leaving how the preloaded key package is derived as an exercise for the application developer, since there are many possible ways to handle that. 

Joe Steele
steele@adobe.com

Received on Monday, 15 October 2012 18:55:46 UTC