2 * Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
7 // This file requires the functions defined in test_functions.js.
9 var gFingerprints = [];
14 * Starts capturing frames from a video tag. The algorithm will fingerprint a
15 * a frame every now and then. After calling this function and running for a
16 * while (at least 200 ms) you will be able to call isVideoPlaying to see if
17 * we detected any video.
19 * @param {string} videoElementId The video element to analyze.
20 * @param {int} width The video element's width.
21 * @param {int} width The video element's height.
23 * @return {string} Returns ok-started to the test.
26 function startDetection(videoElementId, width, height) {
27 var video = document.getElementById(videoElementId);
29 throw failTest('Could not find video element with id ' + videoElementId);
31 var NUM_FINGERPRINTS_TO_SAVE = 5;
32 var canvas = document.createElement('canvas');
33 canvas.style.display = 'none';
35 setInterval(function() {
36 var context = canvas.getContext('2d');
37 if (video.videoWidth == 0)
38 return; // The video element isn't playing anything.
40 captureFrame_(video, context, width, height);
41 gFingerprints.push(fingerprint_(context, width, height));
42 if (gFingerprints.length > NUM_FINGERPRINTS_TO_SAVE) {
43 gFingerprints.shift();
47 returnToTest('ok-started');
51 * Checks if we have detected any video so far.
53 * @return {string} video-playing if we detected video, otherwise
56 function isVideoPlaying() {
57 // Video is considered to be playing if at least one finger print has changed
58 // since the oldest fingerprint. Even small blips in the pixel data will cause
59 // this check to pass. We only check for rough equality though to account for
62 if (gFingerprints.length > 1) {
63 if (!allElementsRoughlyEqualTo_(gFingerprints, gFingerprints[0])) {
64 returnToTest('video-playing');
69 throw failTest('Failed to detect video: ' + exception.message);
71 returnToTest('video-not-playing');
77 function allElementsRoughlyEqualTo_(elements, element_to_compare) {
78 if (elements.length == 0)
81 var PIXEL_DIFF_TOLERANCE = 100;
82 for (var i = 0; i < elements.length; i++) {
83 if (Math.abs(elements[i] - element_to_compare) > PIXEL_DIFF_TOLERANCE) {
91 function captureFrame_(video, canvasContext, width, height) {
92 canvasContext.drawImage(video, 0, 0, width, height);
96 function fingerprint_(canvasContext, width, height) {
97 var imageData = canvasContext.getImageData(0, 0, width, height);
98 var pixels = imageData.data;
101 for (var i = 0; i < pixels.length; i++) {
102 fingerprint += pixels[i];