EME MediaKeySession Closed Reason Sample

Available in Chrome 96+ | View on GitHub | Browse Samples

Background

The current EME spec says "the CDM may close a session at any point, such as when the session is no longer needed or when system resources are lost". However, there's no way to specify the exact reason for session closure. In some cases, this is part of normal user flow, e.g. user close laptop lid to put the device into sleep mode, where the player should resume playback. In some other cases, this is due to some unrecoverable fatal error.

This is why the closed attribute on MediaKeySession is updated to provide a MediaKeySessionClosedReason so that you can handle session closure differently based on the reason.

Live Output


JavaScript Snippet

let keySession;

async function onCreateSessionButtonClick() {
  const config = [
    {
      initDataTypes: ["webm"],
      audioCapabilities: [{ contentType: 'audio/webm; codecs="opus"' }],
    },
  ];
  const keySystemAccess = await navigator.requestMediaKeySystemAccess(
    "org.w3.clearkey",
    config
  );
  // Create media keys.
  const mediaKeys = await keySystemAccess.createMediaKeys();
  // Create a key session.
  keySession = mediaKeys.createSession();
  // Generate a fake license request.
  await keySession.generateRequest("webm", new Uint8Array([1, 2, 3]));

  log(`Media key session is created.`);

  keySession.closed.then((reason) => {
    // Reason is either undefined if not supported, "internal-error",
    // "closed-by-application", "release-acknowledged",
    // "hardware-context-reset", or "resource-evicted".
    log(`Media key session was closed. Reason: "${reason}".`);
  });
}

async function onCloseSessionButtonClick() {
  // Will close media key session with "closed-by-application" reason.
  await keySession.close();
}