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 {string} canvasId A canvas element to write fingerprints into.
21 * @param {int} width The video element's width.
22 * @param {int} width The video element's height.
24 * @return {string} Returns ok-started to the test.
27 function startDetection(videoElementId
, canvasId
, width
, height
) {
28 var video
= document
.getElementById(videoElementId
);
29 var canvas
= document
.getElementById(canvasId
);
30 var NUM_FINGERPRINTS_TO_SAVE
= 5;
32 setInterval(function() {
33 var context
= canvas
.getContext('2d');
34 captureFrame_(video
, context
, width
, height
);
35 gFingerprints
.push(fingerprint_(context
, width
, height
));
36 if (gFingerprints
.length
> NUM_FINGERPRINTS_TO_SAVE
) {
37 gFingerprints
.shift();
41 returnToTest('ok-started');
45 * Checks if we have detected any video so far.
47 * @return {string} video-playing if we detected video, otherwise
50 function isVideoPlaying() {
51 // Video is considered to be playing if at least one finger print has changed
52 // since the oldest fingerprint. Even small blips in the pixel data will cause
53 // this check to pass. We only check for rough equality though to account for
56 if (gFingerprints
.length
> 1) {
57 if (!allElementsRoughlyEqualTo_(gFingerprints
, gFingerprints
[0])) {
58 returnToTest('video-playing');
63 throw failTest('Failed to detect video: ' + exception
.message
);
65 returnToTest('video-not-playing');
71 function allElementsRoughlyEqualTo_(elements
, element_to_compare
) {
72 if (elements
.length
== 0)
75 var PIXEL_DIFF_TOLERANCE
= 100;
76 for (var i
= 0; i
< elements
.length
; i
++) {
77 if (Math
.abs(elements
[i
] - element_to_compare
) > PIXEL_DIFF_TOLERANCE
) {
85 function captureFrame_(video
, canvasContext
, width
, height
) {
86 canvasContext
.drawImage(video
, 0, 0, width
, height
);
90 function fingerprint_(canvasContext
, width
, height
) {
91 var imageData
= canvasContext
.getImageData(0, 0, width
, height
);
92 var pixels
= imageData
.data
;
95 for (var i
= 0; i
< pixels
.length
; i
++) {
96 fingerprint
+= pixels
[i
];