Bug 1556854 - Enable ESLint for dom/media/test/ - Enable prettier and ESLint rules curly and mozilla/consistent-if-bracing. r=jya

Differential Revision: https://phabricator.services.mozilla.com/D37752

--HG--
extra : moz-landing-system : lando
This commit is contained in:
Mark Banner 2019-10-24 08:57:59 +00:00
Родитель 68f9b9a009
Коммит 729f24878c
19 изменённых файлов: 1849 добавлений и 1316 удалений

Просмотреть файл

@ -388,9 +388,7 @@ module.exports = {
],
"rules": {
"consistent-return": "off",
"curly": "off",
"dot-notation": "off",
"mozilla/consistent-if-bracing": "off",
"mozilla/no-useless-parameters": "off",
"mozilla/use-default-preference-values": "off",
"mozilla/use-services": "off",
@ -406,7 +404,6 @@ module.exports = {
"no-unused-vars": "off",
"no-useless-return": "off",
"object-shorthand": "off",
"prettier/prettier": "off",
}
}]
};

Просмотреть файл

@ -7,13 +7,13 @@ function playAndPostResult(muted, parent_window) {
document.body.appendChild(element);
let allowedToPlay = element.allowedToPlay;
element.play().then(
() => {
parent_window.postMessage({played: true, allowedToPlay}, "*");
},
() => {
parent_window.postMessage({played: false, allowedToPlay}, "*");
}
);
() => {
parent_window.postMessage({ played: true, allowedToPlay }, "*");
},
() => {
parent_window.postMessage({ played: false, allowedToPlay }, "*");
}
);
}
function nextWindowMessage() {
@ -30,10 +30,15 @@ const autoplayPermission = "autoplay-media";
async function pushAutoplayAllowedPermission() {
return new Promise((resolve, reject) => {
SpecialPowers.pushPermissions([{
'type': autoplayPermission,
'allow': true,
'context': document
}], resolve);
SpecialPowers.pushPermissions(
[
{
type: autoplayPermission,
allow: true,
context: document,
},
],
resolve
);
});
}

Просмотреть файл

@ -9,25 +9,25 @@
function startTest(test) {
info(test.desc);
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({ 'set': test.prefs }, () => {
SpecialPowers.pushPrefEnv({ set: test.prefs }, () => {
manager.runTests(test.tests, test.runTest);
});
}
function nextVideoEnded(video) {
return nextEvent(video, 'ended');
return nextEvent(video, "ended");
}
function nextVideoPlaying(video) {
return nextEvent(video, 'playing');
return nextEvent(video, "playing");
}
function nextVideoResumes(video) {
return nextEvent(video, 'mozexitvideosuspend');
return nextEvent(video, "mozexitvideosuspend");
}
function nextVideoSuspends(video) {
return nextEvent(video, 'mozentervideosuspend');
return nextEvent(video, "mozentervideosuspend");
}
/**
@ -36,10 +36,14 @@ function nextVideoSuspends(video) {
*/
function appendVideoToDoc(url, token, width, height) {
// Default size of (160, 120) is used by other media tests.
if (width === undefined) { width = 160; }
if (height === undefined) { height = 3 * width / 4; }
if (width === undefined) {
width = 160;
}
if (height === undefined) {
height = (3 * width) / 4;
}
let v = document.createElement('video');
let v = document.createElement("video");
v.token = token;
v.width = width;
v.height = height;
@ -50,10 +54,14 @@ function appendVideoToDoc(url, token, width, height) {
function appendVideoToDocWithoutLoad(token, width, height) {
// Default size of (160, 120) is used by other media tests.
if (width === undefined) { width = 160; }
if (height === undefined) { height = 3*width/4; }
if (width === undefined) {
width = 160;
}
if (height === undefined) {
height = (3 * width) / 4;
}
let v = document.createElement('video');
let v = document.createElement("video");
v.token = token;
document.body.appendChild(v);
v.width = width;
@ -64,7 +72,13 @@ function appendVideoToDocWithoutLoad(token, width, height) {
function loadAndWaitUntilLoadedmetadata(video, url, preloadType = "metadata") {
return new Promise((resolve, reject) => {
video.preload = preloadType;
video.addEventListener("loadedmetadata", () => { resolve(); }, true);
video.addEventListener(
"loadedmetadata",
() => {
resolve();
},
true
);
video.src = url;
});
}
@ -95,7 +109,9 @@ function waitUntilVisible(video) {
* @returns {Promise} Promise that is resolved when video 'playing' event fires.
*/
function waitUntilPlaying(video) {
var p = once(video, 'playing', () => { ok(true, `${video.token} played.`); });
var p = once(video, "playing", () => {
ok(true, `${video.token} played.`);
});
Log(video.token, "Start playing");
video.play();
return p;
@ -112,7 +128,9 @@ function waitUntilEnded(video) {
return Promise.resolve();
}
return once(video, 'ended', () => { ok(true, `${video.token} ended`); });
return once(video, "ended", () => {
ok(true, `${video.token} ended`);
});
}
/**
@ -121,10 +139,10 @@ function waitUntilEnded(video) {
* suspend timer.
*/
function testSuspendTimerStartedWhenHidden(video) {
var p = once(video, 'mozstartvideosuspendtimer').then(() => {
ok(true, `${video.token} suspend begins`)
var p = once(video, "mozstartvideosuspendtimer").then(() => {
ok(true, `${video.token} suspend begins`);
});
Log(video.token, 'Set Hidden');
Log(video.token, "Set Hidden");
video.setVisible(false);
return p;
}
@ -134,7 +152,7 @@ function testSuspendTimerStartedWhenHidden(video) {
* @returns {Promise} Promise that is resolved when video decode suspends.
*/
function testVideoSuspendsWhenHidden(video) {
let p = once(video, 'mozentervideosuspend').then(() => {
let p = once(video, "mozentervideosuspend").then(() => {
ok(true, `${video.token} suspends`);
});
Log(video.token, "Set hidden");
@ -147,7 +165,7 @@ function testVideoSuspendsWhenHidden(video) {
* @returns {Promise} Promise that is resolved when video decode resumes.
*/
function testVideoResumesWhenShown(video) {
var p = once(video, 'mozexitvideosuspend').then(() => {
var p = once(video, "mozexitvideosuspend").then(() => {
ok(true, `${video.token} resumes`);
});
Log(video.token, "Set visible");
@ -160,7 +178,7 @@ function testVideoResumesWhenShown(video) {
* @returns {Promise} Promise that is resolved when video decode resumes.
*/
function testVideoOnlySeekCompletedWhenShown(video) {
var p = once(video, 'mozvideoonlyseekcompleted').then(() => {
var p = once(video, "mozvideoonlyseekcompleted").then(() => {
ok(true, `${video.token} resumes`);
});
Log(video.token, "Set visible");
@ -174,8 +192,12 @@ function testVideoOnlySeekCompletedWhenShown(video) {
*/
function checkVideoDoesntSuspend(video) {
let p = Promise.race([
waitUntilEnded(video).then(() => { ok(true, `${video.token} ended before decode was suspended`) }),
once(video, 'mozentervideosuspend', () => { Promise.reject(new Error(`${video.token} suspended`)) })
waitUntilEnded(video).then(() => {
ok(true, `${video.token} ended before decode was suspended`);
}),
once(video, "mozentervideosuspend", () => {
Promise.reject(new Error(`${video.token} suspended`));
}),
]);
Log(video.token, "Set hidden.");
video.setVisible(false);
@ -190,7 +212,7 @@ function checkVideoDoesntSuspend(video) {
function waitTil(video, time) {
Log(video.token, `Waiting for time to reach ${time}s`);
return new Promise(resolve => {
video.addEventListener('timeupdate', function timeUpdateEvent() {
video.addEventListener("timeupdate", function timeUpdateEvent() {
if (video.currentTime > time) {
video.removeEventListener(name, timeUpdateEvent);
resolve();

Просмотреть файл

@ -11,10 +11,10 @@ function check_dash(v, enabled) {
check("application/dash+xml; codecs=vorbis", "probably");
check("application/dash+xml; codecs=vorbis,vp8", "probably");
check("application/dash+xml; codecs=vorbis,vp8.0", "probably");
check("application/dash+xml; codecs=\"vorbis,vp8\"", "probably");
check("application/dash+xml; codecs=\"vorbis,vp8.0\"", "probably");
check("application/dash+xml; codecs=\"vp8, vorbis\"", "probably");
check("application/dash+xml; codecs=\"vp8.0, vorbis\"", "probably");
check('application/dash+xml; codecs="vorbis,vp8"', "probably");
check('application/dash+xml; codecs="vorbis,vp8.0"', "probably");
check('application/dash+xml; codecs="vp8, vorbis"', "probably");
check('application/dash+xml; codecs="vp8.0, vorbis"', "probably");
check("application/dash+xml; codecs=vp8", "probably");
check("application/dash+xml; codecs=vp8.0", "probably");

Просмотреть файл

@ -1,4 +1,3 @@
function check_ogg(v, enabled, finish) {
function check(type, expected) {
is(v.canPlayType(type), enabled ? expected : "", type);
@ -15,7 +14,7 @@ function check_ogg(v, enabled, finish) {
check("audio/ogg; codecs=vorbis", "probably");
check("video/ogg; codecs=vorbis", "probably");
check("video/ogg; codecs=vorbis,theora", "probably");
check("video/ogg; codecs=\"vorbis, theora\"", "probably");
check('video/ogg; codecs="vorbis, theora"', "probably");
check("video/ogg; codecs=theora", "probably");
resolve();
@ -30,7 +29,9 @@ function check_ogg(v, enabled, finish) {
OpusEnabled = SpecialPowers.getBoolPref("media.opus.enabled");
} catch (ex) {
// SpecialPowers failed, perhaps because Opus isn't compiled in
console.log("media.opus.enabled pref not found; skipping Opus validation");
console.log(
"media.opus.enabled pref not found; skipping Opus validation"
);
}
if (OpusEnabled != undefined) {
resolve();
@ -41,17 +42,19 @@ function check_ogg(v, enabled, finish) {
}
function opus_enable() {
return SpecialPowers.pushPrefEnv({"set": [['media.opus.enabled', true]]})
.then(function() {
check("audio/ogg; codecs=opus", "probably");
});
return SpecialPowers.pushPrefEnv({
set: [["media.opus.enabled", true]],
}).then(function() {
check("audio/ogg; codecs=opus", "probably");
});
}
function opus_disable() {
return SpecialPowers.pushPrefEnv({"set": [['media.opus.enabled', false]]})
.then(function() {
check("audio/ogg; codecs=opus", "");
});
return SpecialPowers.pushPrefEnv({
set: [["media.opus.enabled", false]],
}).then(function() {
check("audio/ogg; codecs=opus", "");
});
}
function unspported_ogg() {
@ -64,9 +67,8 @@ function check_ogg(v, enabled, finish) {
}
basic_test()
.then(verify_opus_support)
.then(opus_enable)
.then(opus_disable)
.then(unspported_ogg, unspported_ogg);
.then(verify_opus_support)
.then(opus_enable)
.then(opus_disable)
.then(unspported_ogg, unspported_ogg);
}

Просмотреть файл

@ -15,15 +15,15 @@ function check_wave(v, enabled) {
check("audio/wave; codecs=7", "probably");
// "no codecs" should be supported, I guess
check("audio/wave; codecs=", "maybe");
check("audio/wave; codecs=\"\"", "maybe");
check('audio/wave; codecs=""', "maybe");
// Unsupported Wave codecs
check("audio/wave; codecs=0", "");
check("audio/wave; codecs=2", "");
check("audio/wave; codecs=xyz,1", "");
check("audio/wave; codecs=1,xyz", "");
check("audio/wave; codecs=\"xyz, 1\"", "");
check('audio/wave; codecs="xyz, 1"', "");
// empty codec names
check("audio/wave; codecs=,", "");
check("audio/wave; codecs=\"0, 1,\"", "");
check('audio/wave; codecs="0, 1,"', "");
}

Просмотреть файл

@ -1,14 +1,18 @@
async function check_webm(v, enabled) {
function check(type, expected) {
is(v.canPlayType(type), enabled ? expected : "", type + "='" + expected + "'");
is(
v.canPlayType(type),
enabled ? expected : "",
type + "='" + expected + "'"
);
}
// WebM types
check("video/webm", "maybe");
check("audio/webm", "maybe");
var video = ['vp8', 'vp8.0', 'vp9', 'vp9.0'];
var audio = ['vorbis', 'opus'];
var video = ["vp8", "vp8.0", "vp9", "vp9.0"];
var audio = ["vorbis", "opus"];
audio.forEach(function(acodec) {
check("audio/webm; codecs=" + acodec, "probably");
@ -17,8 +21,8 @@ async function check_webm(v, enabled) {
video.forEach(function(vcodec) {
check("video/webm; codecs=" + vcodec, "probably");
audio.forEach(function(acodec) {
check("video/webm; codecs=\"" + vcodec + ", " + acodec + "\"", "probably");
check("video/webm; codecs=\"" + acodec + ", " + vcodec + "\"", "probably");
check('video/webm; codecs="' + vcodec + ", " + acodec + '"', "probably");
check('video/webm; codecs="' + acodec + ", " + vcodec + '"', "probably");
});
});
@ -31,13 +35,13 @@ async function check_webm(v, enabled) {
var pref = false;
try {
pref = SpecialPowers.getBoolPref(name);
} catch(ex) { }
} catch (ex) {}
return pref;
}
await SpecialPowers.pushPrefEnv({"set": [["media.av1.enabled", true]]});
check("video/webm; codecs=\"av1\"", "probably");
await SpecialPowers.pushPrefEnv({ set: [["media.av1.enabled", true]] });
check('video/webm; codecs="av1"', "probably");
await SpecialPowers.pushPrefEnv({"set": [["media.av1.enabled", false]]});
check("video/webm; codecs=\"av1\"", "");
await SpecialPowers.pushPrefEnv({ set: [["media.av1.enabled", false]] });
check('video/webm; codecs="av1"', "");
}

Просмотреть файл

@ -6,14 +6,15 @@
"use strict";
const dirSvc = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
const dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(
Ci.nsIProperties
);
addMessageListener('media-test:getcwd', () => {
addMessageListener("media-test:getcwd", () => {
let cwd;
try {
cwd = dirSvc.get("CurWorkD", Ci.nsIFile).path;
} finally {
sendAsyncMessage('media-test:cwd', cwd);
sendAsyncMessage("media-test:cwd", cwd);
}
});

Просмотреть файл

@ -1,5 +1,7 @@
const TEST_VIDEO_1 = "http://mochi.test:8888/tests/dom/media/test/bipbop_225w_175kbps.mp4";
const TEST_VIDEO_2 = "http://mochi.test:8888/tests/dom/media/test/pixel_aspect_ratio.mp4";
const TEST_VIDEO_1 =
"http://mochi.test:8888/tests/dom/media/test/bipbop_225w_175kbps.mp4";
const TEST_VIDEO_2 =
"http://mochi.test:8888/tests/dom/media/test/pixel_aspect_ratio.mp4";
const LONG_VIDEO = "http://mochi.test:8888/tests/dom/media/test/gizmo.mp4";
/**
@ -9,11 +11,11 @@ const LONG_VIDEO = "http://mochi.test:8888/tests/dom/media/test/gizmo.mp4";
async function setup() {
await SpecialPowers.pushPrefEnv({
set: [
[ "media.test.video-suspend", true ],
[ "media.suspend-bkgnd-video.enabled", true ],
[ "media.suspend-bkgnd-video.delay-ms", 500 ],
[ "media.dormant-on-pause-timeout-ms", 0 ],
[ "media.cloneElementVisually.testing", true ],
["media.test.video-suspend", true],
["media.suspend-bkgnd-video.enabled", true],
["media.suspend-bkgnd-video.delay-ms", 500],
["media.dormant-on-pause-timeout-ms", 0],
["media.cloneElementVisually.testing", true],
],
});
@ -89,11 +91,19 @@ async function assertVideosMatch(video1, video2) {
let video2Frame = captureFrameImageData(video2);
let left = document.getElementById("left");
let leftCtx = getWrappedScaledCanvasContext(left, video1Frame.width, video1Frame.height);
let leftCtx = getWrappedScaledCanvasContext(
left,
video1Frame.width,
video1Frame.height
);
leftCtx.putImageData(video1Frame, 0, 0);
let right = document.getElementById("right");
let rightCtx = getWrappedScaledCanvasContext(right, video2Frame.width, video2Frame.height);
let rightCtx = getWrappedScaledCanvasContext(
right,
video2Frame.width,
video2Frame.height
);
rightCtx.putImageData(video2Frame, 0, 0);
if (video1Frame.data.length != video2Frame.data.length) {
@ -210,7 +220,7 @@ async function ensureVideoSuspendable(video) {
video.setVisible(false);
await suspendPromise;
ok(true, "Suspended after the video was made invisible.");
video.setVisible(true)
video.setVisible(true);
ok(!video.hasSuspendTaint(), "Should still be suspendable.");
@ -220,5 +230,3 @@ async function ensureVideoSuspendable(video) {
ok(true, "Shutdown decoder after the video was paused.");
await video.play();
}

Просмотреть файл

@ -1,10 +1,12 @@
const CLEARKEY_KEYSYSTEM = "org.w3.clearkey";
const gCencMediaKeySystemConfig = [{
initDataTypes: ['cenc'],
videoCapabilities: [{ contentType: 'video/mp4' }],
audioCapabilities: [{ contentType: 'audio/mp4' }],
}];
const gCencMediaKeySystemConfig = [
{
initDataTypes: ["cenc"],
videoCapabilities: [{ contentType: "video/mp4" }],
audioCapabilities: [{ contentType: "audio/mp4" }],
},
];
function IsMacOSSnowLeopardOrEarlier() {
var re = /Mac OS X (\d+)\.(\d+)/;
@ -17,23 +19,21 @@ function IsMacOSSnowLeopardOrEarlier() {
return major == 10 && minor <= 6;
}
function bail(message)
{
function bail(message) {
return function(err) {
if (err) {
message += "; " + String(err)
message += "; " + String(err);
}
ok(false, message);
if (err) {
info(String(err));
}
SimpleTest.finish();
}
};
}
function ArrayBufferToString(arr)
{
var str = '';
function ArrayBufferToString(arr) {
var str = "";
var view = new Uint8Array(arr);
for (var i = 0; i < view.length; i++) {
str += String.fromCharCode(view[i]);
@ -41,8 +41,7 @@ function ArrayBufferToString(arr)
return str;
}
function StringToArrayBuffer(str)
{
function StringToArrayBuffer(str) {
var arr = new ArrayBuffer(str.length);
var view = new Uint8Array(arr);
for (var i = 0; i < str.length; i++) {
@ -51,16 +50,15 @@ function StringToArrayBuffer(str)
return arr;
}
function StringToHex(str){
function StringToHex(str) {
var res = "";
for (var i = 0; i < str.length; ++i) {
res += ("0" + str.charCodeAt(i).toString(16)).slice(-2);
res += ("0" + str.charCodeAt(i).toString(16)).slice(-2);
}
return res;
}
function Base64ToHex(str)
{
function Base64ToHex(str) {
var bin = window.atob(str.replace(/-/g, "+").replace(/_/g, "/"));
var res = "";
for (var i = 0; i < bin.length; i++) {
@ -69,46 +67,56 @@ function Base64ToHex(str)
return res;
}
function HexToBase64(hex)
{
function HexToBase64(hex) {
var bin = "";
for (var i = 0; i < hex.length; i += 2) {
bin += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return window.btoa(bin).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
return window
.btoa(bin)
.replace(/=/g, "")
.replace(/\+/g, "-")
.replace(/\//g, "_");
}
function TimeRangesToString(trs)
{
function TimeRangesToString(trs) {
var l = trs.length;
if (l === 0) { return "-"; }
if (l === 0) {
return "-";
}
var s = "";
var i = 0;
for (;;) {
s += trs.start(i) + "-" + trs.end(i);
if (++i === l) { return s; }
if (++i === l) {
return s;
}
s += ",";
}
}
function SourceBufferToString(sb)
{
return ("SourceBuffer{"
+ "AppendMode=" + (sb.AppendMode || "-")
+ ", updating=" + (sb.updating ? "true" : "false")
+ ", buffered=" + TimeRangesToString(sb.buffered)
+ ", audioTracks=" + (sb.audioTracks ? sb.audioTracks.length : "-")
+ ", videoTracks=" + (sb.videoTracks ? sb.videoTracks.length : "-")
+ "}");
function SourceBufferToString(sb) {
return (
"SourceBuffer{" +
"AppendMode=" +
(sb.AppendMode || "-") +
", updating=" +
(sb.updating ? "true" : "false") +
", buffered=" +
TimeRangesToString(sb.buffered) +
", audioTracks=" +
(sb.audioTracks ? sb.audioTracks.length : "-") +
", videoTracks=" +
(sb.videoTracks ? sb.videoTracks.length : "-") +
"}"
);
}
function SourceBufferListToString(sbl)
{
function SourceBufferListToString(sbl) {
return "SourceBufferList[" + sbl.map(SourceBufferToString).join(", ") + "]";
}
function GenerateClearKeyLicense(licenseRequest, keyStore)
{
function GenerateClearKeyLicense(licenseRequest, keyStore) {
var msgStr = ArrayBufferToString(licenseRequest);
var msg = JSON.parse(msgStr);
@ -120,34 +128,41 @@ function GenerateClearKeyLicense(licenseRequest, keyStore)
if (key) {
keys.push({
"kty": "oct",
"kid": id64,
"k": HexToBase64(key)
kty: "oct",
kid: id64,
k: HexToBase64(key),
});
}
}
return new TextEncoder().encode(JSON.stringify({
"keys" : keys,
"type" : msg.type || "temporary"
}));
return new TextEncoder().encode(
JSON.stringify({
keys: keys,
type: msg.type || "temporary",
})
);
}
function UpdateSessionFunc(test, token, sessionType, resolve, reject) {
return function(ev) {
var license = GenerateClearKeyLicense(ev.message, test.keys);
Log(token, "sending update message to CDM: " + (new TextDecoder().decode(license)));
ev.target.update(license).then(function() {
Log(token, "MediaKeySession update ok!");
resolve(ev.target);
}).catch(function(reason) {
reject(`${token} MediaKeySession update failed: ${reason}`);
});
}
Log(
token,
"sending update message to CDM: " + new TextDecoder().decode(license)
);
ev.target
.update(license)
.then(function() {
Log(token, "MediaKeySession update ok!");
resolve(ev.target);
})
.catch(function(reason) {
reject(`${token} MediaKeySession update failed: ${reason}`);
});
};
}
function MaybeCrossOriginURI(test, uri)
{
function MaybeCrossOriginURI(test, uri) {
if (test.crossOrigin) {
return "https://example.com:443/tests/dom/media/test/allowed.sjs?" + uri;
} else {
@ -155,8 +170,7 @@ function MaybeCrossOriginURI(test, uri)
}
}
function AppendTrack(test, ms, track, token)
{
function AppendTrack(test, ms, track, token) {
return new Promise(function(resolve, reject) {
var sb;
var curFragment = 0;
@ -179,7 +193,10 @@ function AppendTrack(test, ms, track, token)
req.responseType = "arraybuffer";
req.addEventListener("load", function() {
Log(token, track.name + ": fetch of " + fragmentFile + " complete, appending");
Log(
token,
track.name + ": fetch of " + fragmentFile + " complete, appending"
);
sb.appendBuffer(new Uint8Array(req.response));
});
@ -190,14 +207,26 @@ function AppendTrack(test, ms, track, token)
reject(`${token} - ${track.name}: aborted fetching ${fragmentFile}`);
});
Log(token, track.name + ": addNextFragment() fetching next fragment " + fragmentFile);
Log(
token,
track.name +
": addNextFragment() fetching next fragment " +
fragmentFile
);
req.send(null);
}
Log(token, track.name + ": addSourceBuffer(" + track.type + ")");
sb = ms.addSourceBuffer(track.type);
sb.addEventListener("updateend", function() {
Log(token, track.name + ": updateend for " + fragmentFile + ", " + SourceBufferToString(sb));
Log(
token,
track.name +
": updateend for " +
fragmentFile +
", " +
SourceBufferToString(sb)
);
addNextFragment();
});
@ -207,8 +236,7 @@ function AppendTrack(test, ms, track, token)
//Returns a promise that is resolved when the media element is ready to have
//its play() function called; when it's loaded MSE fragments.
function LoadTest(test, elem, token, endOfStream = true)
{
function LoadTest(test, elem, token, endOfStream = true) {
if (!test.tracks) {
ok(false, token + " test does not have a tracks list");
return Promise.reject();
@ -218,19 +246,27 @@ function LoadTest(test, elem, token, endOfStream = true)
elem.src = URL.createObjectURL(ms);
elem.crossOrigin = test.crossOrigin || false;
return new Promise(function (resolve, reject) {
ms.addEventListener("sourceopen", function () {
Log(token, "sourceopen");
Promise.all(test.tracks.map(function(track) {
return AppendTrack(test, ms, track, token);
})).then(function() {
Log(token, "Tracks loaded, calling MediaSource.endOfStream()");
if (endOfStream) {
ms.endOfStream();
}
resolve();
}).catch(reject);
}, {once: true});
return new Promise(function(resolve, reject) {
ms.addEventListener(
"sourceopen",
function() {
Log(token, "sourceopen");
Promise.all(
test.tracks.map(function(track) {
return AppendTrack(test, ms, track, token);
})
)
.then(function() {
Log(token, "Tracks loaded, calling MediaSource.endOfStream()");
if (endOfStream) {
ms.endOfStream();
}
resolve();
})
.catch(reject);
},
{ once: true }
);
});
}
@ -248,7 +284,7 @@ function EMEPromise() {
* or will be rejected with a string that describes the failure.
*/
function CreateMediaKeys(v, test, token) {
let p = new EMEPromise;
let p = new EMEPromise();
function streamType(type) {
var x = test.tracks.find(o => o.name == type);
@ -258,21 +294,24 @@ function CreateMediaKeys(v, test, token) {
function onencrypted(ev) {
var options = { initDataTypes: [ev.initDataType] };
if (streamType("video")) {
options.videoCapabilities = [{contentType: streamType("video")}];
options.videoCapabilities = [{ contentType: streamType("video") }];
}
if (streamType("audio")) {
options.audioCapabilities = [{contentType: streamType("audio")}];
options.audioCapabilities = [{ contentType: streamType("audio") }];
}
navigator.requestMediaKeySystemAccess(CLEARKEY_KEYSYSTEM, [options])
.then(keySystemAccess => {
keySystemAccess.createMediaKeys().then(
p.resolve,
() => p.reject(`${token} Failed to create MediaKeys object.`)
);
}, () => p.reject(`${token} Failed to request key system access.`));
navigator.requestMediaKeySystemAccess(CLEARKEY_KEYSYSTEM, [options]).then(
keySystemAccess => {
keySystemAccess
.createMediaKeys()
.then(p.resolve, () =>
p.reject(`${token} Failed to create MediaKeys object.`)
);
},
() => p.reject(`${token} Failed to request key system access.`)
);
}
v.addEventListener("encrypted", onencrypted, {once: true});
v.addEventListener("encrypted", onencrypted, { once: true });
return p.promise;
}
@ -282,14 +321,13 @@ function CreateMediaKeys(v, test, token) {
* with a string that describes the failure.
*/
function CreateAndSetMediaKeys(v, test, token) {
let p = new EMEPromise;
let p = new EMEPromise();
CreateMediaKeys(v, test, token).then(mediaKeys => {
v.setMediaKeys(mediaKeys).then(
p.resolve,
() => p.reject(`${token} Failed to set MediaKeys on <video> element.`)
v.setMediaKeys(mediaKeys).then(p.resolve, () =>
p.reject(`${token} Failed to set MediaKeys on <video> element.`)
);
}, p.reject)
}, p.reject);
return p.promise;
}
@ -300,18 +338,25 @@ function CreateAndSetMediaKeys(v, test, token) {
* is completed (specified by test.sessionCount).
*/
function LoadInitData(v, test, token) {
let p = new EMEPromise;
let p = new EMEPromise();
let initDataQueue = [];
// Call SimpleTest._originalSetTimeout() to bypass the flaky timeout checker.
let timer = SimpleTest._originalSetTimeout.call(window, () => {
p.reject(`${token} Timed out in waiting for the init data.`);
}, 60000);
let timer = SimpleTest._originalSetTimeout.call(
window,
() => {
p.reject(`${token} Timed out in waiting for the init data.`);
},
60000
);
function onencrypted(ev) {
initDataQueue.push(ev);
Log(token, `got encrypted(${ev.initDataType}, ` +
`${StringToHex(ArrayBufferToString(ev.initData))}) event.`);
Log(
token,
`got encrypted(${ev.initDataType}, ` +
`${StringToHex(ArrayBufferToString(ev.initData))}) event.`
);
if (test.sessionCount == initDataQueue.length) {
p.resolve(initDataQueue);
clearTimeout(timer);
@ -329,16 +374,18 @@ function LoadInitData(v, test, token) {
*/
function MakeRequest(test, token, ev, session, sessionType) {
sessionType = sessionType || "temporary";
let p = new EMEPromise;
let str = `session[${session.sessionId}].generateRequest(` +
let p = new EMEPromise();
let str =
`session[${session.sessionId}].generateRequest(` +
`${ev.initDataType}, ${StringToHex(ArrayBufferToString(ev.initData))})`;
session.addEventListener("message",
UpdateSessionFunc(test, token, sessionType, p.resolve, p.reject));
session.addEventListener(
"message",
UpdateSessionFunc(test, token, sessionType, p.resolve, p.reject)
);
Log(token, str);
session.generateRequest(ev.initDataType, ev.initData)
.catch(reason => {
session.generateRequest(ev.initDataType, ev.initData).catch(reason => {
// Reject the promise if generateRequest() failed.
// Otherwise it will be resolved in UpdateSessionFunc().
p.reject(`${token}: ${str} failed; ${reason}`);
@ -375,8 +422,7 @@ function CleanUpMedia(v) {
* Close all sessions and clean up the |v| element.
*/
function CloseSessions(v, sessions) {
return Promise.all(sessions.map(s => s.close()))
.then(CleanUpMedia(v));
return Promise.all(sessions.map(s => s.close())).then(CleanUpMedia(v));
}
/*
@ -385,38 +431,41 @@ function CloseSessions(v, sessions) {
* if any failure.
*/
function SetupEME(v, test, token) {
let p = new EMEPromise;
let p = new EMEPromise();
v.onerror = function() {
p.reject(`${token} got an error event.`);
}
};
Promise.all([
LoadInitData(v, test, token),
CreateAndSetMediaKeys(v, test, token),
LoadTest(test, v, token)])
.then(values => {
let initData = values[0];
return ProcessInitData(v, test, token, initData);
})
.then(p.resolve, p.reject);
LoadTest(test, v, token),
])
.then(values => {
let initData = values[0];
return ProcessInitData(v, test, token, initData);
})
.then(p.resolve, p.reject);
return p.promise;
}
function SetupEMEPref(callback) {
var prefs = [
[ "media.mediasource.enabled", true ],
[ "media.mediasource.webm.enabled", true ],
["media.mediasource.enabled", true],
["media.mediasource.webm.enabled", true],
];
if (SpecialPowers.Services.appinfo.name == "B2G" ||
!manifestVideo().canPlayType("video/mp4")) {
if (
SpecialPowers.Services.appinfo.name == "B2G" ||
!manifestVideo().canPlayType("video/mp4")
) {
// XXX remove once we have mp4 PlatformDecoderModules on all platforms.
prefs.push([ "media.use-blank-decoder", true ]);
prefs.push(["media.use-blank-decoder", true]);
}
SpecialPowers.pushPrefEnv({ "set" : prefs }, callback);
SpecialPowers.pushPrefEnv({ set: prefs }, callback);
}
function fetchWithXHR(uri, onLoadFunction) {
@ -424,8 +473,12 @@ function fetchWithXHR(uri, onLoadFunction) {
var xhr = new XMLHttpRequest();
xhr.open("GET", uri, true);
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
is(xhr.status, 200, "fetchWithXHR load uri='" + uri + "' status=" + xhr.status);
xhr.addEventListener("load", function() {
is(
xhr.status,
200,
"fetchWithXHR load uri='" + uri + "' status=" + xhr.status
);
resolve(xhr.response);
});
xhr.send();
@ -436,13 +489,17 @@ function fetchWithXHR(uri, onLoadFunction) {
}
return p;
};
}
function once(target, name, cb) {
var p = new Promise(function(resolve, reject) {
target.addEventListener(name, function(arg) {
resolve(arg);
}, {once: true});
target.addEventListener(
name,
function(arg) {
resolve(arg);
},
{ once: true }
);
});
if (cb) {
p.then(cb);

Просмотреть файл

@ -1,14 +1,19 @@
function test_fragment_noplay(v, start, end, is, ok, finish) {
function onLoadedMetadata() {
var s = start == null ? 0 : start;
var e = end == null ? v.duration : end;
var a = s - 0.15;
var b = s + 0.15;
ok(
v.currentTime >= a && v.currentTime <= b,
"loadedmetadata currentTime is " + a + " < " + v.currentTime + " < " + b
);
ok(
v.mozFragmentEnd == e,
"mozFragmentEnd (" + v.mozFragmentEnd + ") == end Time (" + e + ")"
);
finish();
}
function onLoadedMetadata() {
var s = start == null ? 0 : start;
var e = end == null ? v.duration : end;
var a = s - 0.15;
var b = s + 0.15;
ok(v.currentTime >= a && v.currentTime <= b, "loadedmetadata currentTime is " + a + " < " + v.currentTime + " < " + b);
ok(v.mozFragmentEnd == e, "mozFragmentEnd (" + v.mozFragmentEnd + ") == end Time (" + e + ")");
finish();
}
v.addEventListener("loadedmetadata", onLoadedMetadata);
v.addEventListener("loadedmetadata", onLoadedMetadata);
}

Просмотреть файл

@ -1,67 +1,92 @@
function test_fragment_play(v, start, end, is, ok, finish) {
var completed = false;
var loadedMetadataRaised = false;
var seekedRaised = false;
var pausedRaised = false;
var completed = false;
var loadedMetadataRaised = false;
var seekedRaised = false;
var pausedRaised = false;
function onLoadedMetadata() {
var s = start == null ? 0 : start;
var e = end == null ? v.duration : end;
ok(v.currentTime == s, "loadedmetadata currentTime is " + v.currentTime + " != " + s);
ok(v.mozFragmentEnd == e, "mozFragmentEnd (" + v.mozFragmentEnd + ") == end Time (" + e + ")");
loadedMetadataRaised = true;
v.play();
}
function onSeeked() {
if (completed)
return;
var s = start == null ? 0 : start;
ok(v.currentTime - s < 0.1, "seeked currentTime is " + v.currentTime + " != " + s + " (fuzzy compare +-0.1)");
seekedRaised = true;
}
function onTimeUpdate() {
if (completed)
return;
v._lastTimeUpdate = v.currentTime;
}
function onPause() {
if (completed)
return;
var e = end == null ? v.duration : end;
var a = e - 0.05;
var b = e + 0.05;
ok(v.currentTime >= a && v.currentTime <= b, "paused currentTime is " + a + " < " + v.currentTime + " < " + b + " ? " + v._lastTimeUpdate);
pausedRaised = true;
v.play();
}
function onEnded() {
if (completed)
return;
completed = true;
ok(loadedMetadataRaised, "loadedmetadata event");
if (start) {
ok(seekedRaised, "seeked event");
function onLoadedMetadata() {
var s = start == null ? 0 : start;
var e = end == null ? v.duration : end;
ok(
v.currentTime == s,
"loadedmetadata currentTime is " + v.currentTime + " != " + s
);
ok(
v.mozFragmentEnd == e,
"mozFragmentEnd (" + v.mozFragmentEnd + ") == end Time (" + e + ")"
);
loadedMetadataRaised = true;
v.play();
}
if (end) {
ok(pausedRaised, "paused event: " + end + " " + v.duration);
}
finish();
}
v.addEventListener("ended", onEnded);
v.addEventListener("loadedmetadata", onLoadedMetadata);
v.addEventListener("seeked", onSeeked);
v.addEventListener("pause", onPause);
v.addEventListener("timeupdate", onTimeUpdate);
function onSeeked() {
if (completed) {
return;
}
var s = start == null ? 0 : start;
ok(
v.currentTime - s < 0.1,
"seeked currentTime is " +
v.currentTime +
" != " +
s +
" (fuzzy compare +-0.1)"
);
seekedRaised = true;
}
function onTimeUpdate() {
if (completed) {
return;
}
v._lastTimeUpdate = v.currentTime;
}
function onPause() {
if (completed) {
return;
}
var e = end == null ? v.duration : end;
var a = e - 0.05;
var b = e + 0.05;
ok(
v.currentTime >= a && v.currentTime <= b,
"paused currentTime is " +
a +
" < " +
v.currentTime +
" < " +
b +
" ? " +
v._lastTimeUpdate
);
pausedRaised = true;
v.play();
}
function onEnded() {
if (completed) {
return;
}
completed = true;
ok(loadedMetadataRaised, "loadedmetadata event");
if (start) {
ok(seekedRaised, "seeked event");
}
if (end) {
ok(pausedRaised, "paused event: " + end + " " + v.duration);
}
finish();
}
v.addEventListener("ended", onEnded);
v.addEventListener("loadedmetadata", onLoadedMetadata);
v.addEventListener("seeked", onSeeked);
v.addEventListener("pause", onPause);
v.addEventListener("timeupdate", onTimeUpdate);
}

Просмотреть файл

@ -9,17 +9,26 @@ async function pushGetUserMediaTestPrefs({
fakeAudio = false,
fakeVideo = false,
loopbackAudio = false,
loopbackVideo = false}) {
loopbackVideo = false,
}) {
// Make sure we have sensical arguments
if (!fakeAudio && !loopbackAudio) {
throw new Error("pushGetUserMediaTestPrefs: Should have fake or loopback audio!");
throw new Error(
"pushGetUserMediaTestPrefs: Should have fake or loopback audio!"
);
} else if (fakeAudio && loopbackAudio) {
throw new Error("pushGetUserMediaTestPrefs: Should not have both fake and loopback audio!");
throw new Error(
"pushGetUserMediaTestPrefs: Should not have both fake and loopback audio!"
);
}
if (!fakeVideo && !loopbackVideo) {
throw new Error("pushGetUserMediaTestPrefs: Should have fake or loopback video!");
throw new Error(
"pushGetUserMediaTestPrefs: Should have fake or loopback video!"
);
} else if (fakeVideo && loopbackVideo) {
throw new Error("pushGetUserMediaTestPrefs: Should not have both fake and loopback video!");
throw new Error(
"pushGetUserMediaTestPrefs: Should not have both fake and loopback video!"
);
}
let testPrefs = [];
@ -32,10 +41,15 @@ async function pushGetUserMediaTestPrefs({
if (loopbackAudio) {
// If audio loopback is requested we expect the test harness to have set
// the loopback device pref, make sure it's set
let audioLoopDev = SpecialPowers.getCharPref("media.audio_loopback_dev", "");
let audioLoopDev = SpecialPowers.getCharPref(
"media.audio_loopback_dev",
""
);
if (!audioLoopDev) {
throw new Error("pushGetUserMediaTestPrefs: Loopback audio requested but " +
"media.audio_loopback_dev does not appear to be set!");
throw new Error(
"pushGetUserMediaTestPrefs: Loopback audio requested but " +
"media.audio_loopback_dev does not appear to be set!"
);
}
}
if (fakeVideo) {
@ -47,18 +61,23 @@ async function pushGetUserMediaTestPrefs({
if (loopbackVideo) {
// If video loopback is requested we expect the test harness to have set
// the loopback device pref, make sure it's set
let videoLoopDev = SpecialPowers.getCharPref("media.video_loopback_dev", "");
let videoLoopDev = SpecialPowers.getCharPref(
"media.video_loopback_dev",
""
);
if (!videoLoopDev) {
throw new Error("pushGetUserMediaTestPrefs: Loopback video requested but " +
"media.video_loopback_dev does not appear to be set!");
throw new Error(
"pushGetUserMediaTestPrefs: Loopback video requested but " +
"media.video_loopback_dev does not appear to be set!"
);
}
}
if (loopbackAudio || loopbackVideo) {
// Prevent gUM permission prompt. Since loopback devices are considered
// real devices we need to set prefs so the gUM prompt isn't presented.
testPrefs.push(['media.navigator.permission.disabled', true]);
testPrefs.push(["media.navigator.permission.disabled", true]);
}
return SpecialPowers.pushPrefEnv({set: testPrefs});
return SpecialPowers.pushPrefEnv({ set: testPrefs });
}
// Setup preconditions for tests using getUserMedia. This function will

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,15 +1,15 @@
video.mozRequestDebugInfo().then(debugInfo => {
// The parsing won't be necessary once we have bug 1542674
try {
debugInfo = debugInfo.replace(/\t/g, '').split(/\n/g);
debugInfo = debugInfo.replace(/\t/g, "").split(/\n/g);
var JSONDebugInfo = "{";
for(let g =0; g<debugInfo.length-1; g++){
var pair = debugInfo[g].split(": ");
JSONDebugInfo += '"' + pair[0] + '":"' + pair[1] + '",';
}
JSONDebugInfo = JSONDebugInfo.slice(0,JSONDebugInfo.length-1);
JSONDebugInfo += "}";
result["mozRequestDebugInfo"] = JSON.parse(JSONDebugInfo);
for (let g = 0; g < debugInfo.length - 1; g++) {
var pair = debugInfo[g].split(": ");
JSONDebugInfo += '"' + pair[0] + '":"' + pair[1] + '",';
}
JSONDebugInfo = JSONDebugInfo.slice(0, JSONDebugInfo.length - 1);
JSONDebugInfo += "}";
result["mozRequestDebugInfo"] = JSON.parse(JSONDebugInfo);
} catch (err) {
console.log(`Error '${err.toString()} in JSON.parse(${debugInfo})`);
result["mozRequestDebugInfo"] = debugInfo;

Просмотреть файл

@ -2,23 +2,28 @@
// https://addons.mozilla.org/en-US/firefox/addon/youtube-auto-hd-lq/
// licence: MPL 2.0
var config = {
"HD": true,
"LQ": false,
"ID": "auto-hd-lq-for-ytb",
"type": function (t) {
config.HD = t === 'hd';
config.LQ = t === 'lq';
HD: true,
LQ: false,
ID: "auto-hd-lq-for-ytb",
type: function(t) {
config.HD = t === "hd";
config.LQ = t === "lq";
},
"quality": function () {
quality: function() {
if (config.HD || config.LQ) {
var youtubePlayerListener = function (LQ, HD) {
return function (e) {
var youtubePlayerListener = function(LQ, HD) {
return function(e) {
if (e === 1) {
var player = document.getElementById('movie_player');
var player = document.getElementById("movie_player");
if (player) {
var levels = player.getAvailableQualityLevels();
if (levels.length) {
var q = (HD && levels[0]) ? levels[0] : ((LQ && levels[levels.length - 2]) ? levels[levels.length - 2] : null);
var q =
HD && levels[0]
? levels[0]
: LQ && levels[levels.length - 2]
? levels[levels.length - 2]
: null;
if (q) {
player.setPlaybackQuality(q);
player.setPlaybackQualityRange(q, q);
@ -26,15 +31,17 @@ var config = {
}
}
}
}
}
};
};
/* */
var inject = function () {
var action = function () {
var player = document.getElementById('movie_player');
var inject = function() {
var action = function() {
var player = document.getElementById("movie_player");
if (player && player.addEventListener && player.getPlayerState) {
player.addEventListener("onStateChange", "youtubePlayerListener");
} else window.setTimeout(action, 1000);
} else {
window.setTimeout(action, 1000);
}
};
/* */
action();
@ -47,26 +54,37 @@ var config = {
document.documentElement.appendChild(script);
}
/* */
script.textContent = "var youtubePlayerListener = (" + youtubePlayerListener + ')(' + config.LQ + ',' + config.HD + ');(' + inject + ')();';
script.textContent =
"var youtubePlayerListener = (" +
youtubePlayerListener +
")(" +
config.LQ +
"," +
config.HD +
");(" +
inject +
")();";
}
}
},
};
if (/^https?:\/\/www\.youtube.com\/watch\?/.test(document.location.href)) config.quality();
var content = document.getElementById('content');
if (content) {
var observer = new window.MutationObserver(function (e) {
e.forEach(function (m) {
if (m.addedNodes !== null) {
for (var i = 0; i < m.addedNodes.length; i++) {
if (m.addedNodes[i].id === 'movie_player') {
config.quality();
return;
}
if (/^https?:\/\/www\.youtube.com\/watch\?/.test(document.location.href)) {
config.quality();
}
var content = document.getElementById("content");
if (content) {
var observer = new window.MutationObserver(function(e) {
e.forEach(function(m) {
if (m.addedNodes !== null) {
for (var i = 0; i < m.addedNodes.length; i++) {
if (m.addedNodes[i].id === "movie_player") {
config.quality();
return;
}
}
});
}
});
/* */
observer.observe(content, {"childList": true, "subtree": true});
}
});
/* */
observer.observe(content, { childList: true, subtree: true });
}

Просмотреть файл

@ -1 +1 @@
var result = {"getVideoPlaybackQuality": video.getVideoPlaybackQuality()};
var result = { getVideoPlaybackQuality: video.getVideoPlaybackQuality() };

Просмотреть файл

@ -1,3 +1,3 @@
function getNotSupportedFile(name) {
return name + ".bad";
}
}

Просмотреть файл

@ -1,16 +1,16 @@
var manager = new MediaTestManager;
var manager = new MediaTestManager();
function createTestArray() {
var tests = [];
var tmpVid = document.createElement("video");
for (var testNum=0; testNum<gSeekTests.length; testNum++) {
for (var testNum = 0; testNum < gSeekTests.length; testNum++) {
var test = gSeekTests[testNum];
if (!tmpVid.canPlayType(test.type)) {
continue;
}
var t = new Object;
var t = new Object();
t.name = test.name;
t.type = test.type;
t.duration = test.duration;
@ -21,25 +21,37 @@ function createTestArray() {
}
function startTest(test, token) {
var video = document.createElement('video');
var video = document.createElement("video");
video.token = token += "-seek" + test.number + ".js";
manager.started(video.token);
video.src = test.name;
video.preload = "metadata";
document.body.appendChild(video);
var name = test.name + " seek test " + test.number;
var localIs = function(n) { return function(a, b, msg) {
is(a, b, n + ": " + msg);
}}(name);
var localOk = function(n) { return function(a, msg) {
ok(a, n + ": " + msg);
}}(name);
var localFinish = function(v, m) { return function() {
v.onerror = null;
removeNodeAndSource(v);
dump("SEEK-TEST: Finished " + name + " token: " + v.token + "\n");
m.finished(v.token);
}}(video, manager);
var localIs = (function(n) {
return function(a, b, msg) {
is(a, b, n + ": " + msg);
};
})(name);
var localOk = (function(n) {
return function(a, msg) {
ok(a, n + ": " + msg);
};
})(name);
var localFinish = (function(v, m) {
return function() {
v.onerror = null;
removeNodeAndSource(v);
dump("SEEK-TEST: Finished " + name + " token: " + v.token + "\n");
m.finished(v.token);
};
})(video, manager);
dump("SEEK-TEST: Started " + name + "\n");
window['test_seek' + test.number](video, test.duration/2, localIs, localOk, localFinish);
window["test_seek" + test.number](
video,
test.duration / 2,
localIs,
localOk,
localFinish
);
}