1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // These must match with how the video and canvas tags are declared in html. 6 const VIDEO_TAG_WIDTH = 320; 7 const VIDEO_TAG_HEIGHT = 240; 8 9 // Number of test events to occur before the test pass. When the test pass, 10 // the function gAllEventsOccured is called. 11 var gNumberOfExpectedEvents = 0; 12 13 // Number of events that currently have occurred. 14 var gNumberOfEvents = 0; 15 16 var gAllEventsOccured = function () {}; 17 18 // Use this function to set a function that will be called once all expected 19 // events has occurred. 20 function setAllEventsOccuredHandler(handler) { 21 gAllEventsOccured = handler; 22 } 23 24 function detectVideoIn(videoElementName, callback) { 25 var width = VIDEO_TAG_WIDTH; 26 var height = VIDEO_TAG_HEIGHT; 27 var videoElement = $(videoElementName); 28 var canvas = $(videoElementName + '-canvas'); 29 var waitVideo = setInterval(function() { 30 var context = canvas.getContext('2d'); 31 context.drawImage(videoElement, 0, 0, width, height); 32 var pixels = context.getImageData(0, 0, width, height).data; 33 34 if (isVideoPlaying(pixels, width, height)) { 35 clearInterval(waitVideo); 36 callback(); 37 } 38 }, 100); 39 } 40 41 function waitForVideo(videoElement) { 42 document.title = 'Waiting for video...'; 43 addExpectedEvent(); 44 detectVideoIn(videoElement, function () { eventOccured(); }); 45 } 46 47 function waitForConnectionToStabilize(peerConnection) { 48 addExpectedEvent(); 49 var waitForStabilization = setInterval(function() { 50 if (peerConnection.signalingState == 'stable') { 51 clearInterval(waitForStabilization); 52 eventOccured(); 53 } 54 }, 100); 55 } 56 57 function addExpectedEvent() { 58 ++gNumberOfExpectedEvents; 59 } 60 61 function eventOccured() { 62 ++gNumberOfEvents; 63 if (gNumberOfEvents == gNumberOfExpectedEvents) { 64 gAllEventsOccured(); 65 } 66 } 67 68 // This very basic video verification algorithm will be satisfied if any 69 // pixels are nonzero in a small sample area in the middle. It relies on the 70 // assumption that a video element with null source just presents zeroes. 71 function isVideoPlaying(pixels, width, height) { 72 // Sample somewhere near the middle of the image. 73 var middle = width * height / 2; 74 for (var i = 0; i < 20; i++) { 75 if (pixels[middle + i] > 0) { 76 return true; 77 } 78 } 79 return false; 80 } 81 82 // This function matches |left| and |right| and throws an exception if the 83 // values don't match. 84 function expectEquals(left, right) { 85 if (left != right) { 86 var s = "expectEquals failed left: " + left + " right: " + right; 87 document.title = s; 88 throw s; 89 } 90 }