chaenu chaenu - 29 days ago 13
Javascript Question

How to (feature) detect if browser supports WebM alpha transparency?

I'm integrating a *.webm Video with alpha transparency. At the moment, the transparency is only supported in Chrome and Opera. (Demo: http://simpl.info/videoalpha/) Firefox for example plays the video as it supports the WebM format, but instead of the transparency, there's a black background.

My plan is to display the video poster image instead of the video, if the browser does not support alpha transparency. So the video should only play, if the browser supports WebM alpha transparency. I know how to detect the browser or the rendering engine and therefore play the video (see code below) - but is there a "feature detection" way?

var supportsAlphaVideo = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor) || (/OPR/.test (navigator.userAgent));
if (supportsAlphaVideo) {
document.querySelector(".js-video").play();
}


See also http://updates.html5rocks.com/2013/07/Alpha-transparency-in-Chrome-video

K3N K3N
Answer

There are no properties exposed giving any information about the video and its channels.

The only way to do this is either:

  • Knowing in advance, incorporate that knowledge with the data and serve it to the browser when video is requested as meta-data
  • Use a canvas to analyze the image data
  • Load the file as binary data, then parse the webm format manually to extract this information. Do-able but very inconvenient as the complete file must be downloaded, and of course a parser must be made.

If you don't know in advance, or have no way to supply the metadata, then canvas is your best option.

Canvas

You can use a canvas to test for actual transparency, however, this do have CORS requirements (video must be on the same server, or the external server need to accept cross-origin usage).

Additionally you have to actually start loading the video which of course can have an impact on bandwidth as well as performance. You probably want to do this with a dynamically created video and canvas tag.

From there, it is fairly straight forward.

  • Create a small canvas
  • Draw a frame into it (one that is expected to have an alpha channel)
  • Extract the pixels (CORS requirements here)
  • Loop through the buffer using a Uint32Array view and check for alpha channel for values < 255 (pixel & 0xff000000 !== 0xff000000).

This is fairly fast to do, you can use a frame size of half or even smaller.