summaryrefslogtreecommitdiffstats
path: root/dom/media/autoplay/test/browser/browser_autoplay_policy_user_gestures.js
blob: 2b9d8c1158159fdd64a14a111a295b224274184a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/* eslint-disable mozilla/no-arbitrary-setTimeout */

const VIDEO_PAGE = GetTestWebBasedURL("file_video.html");

const UserGestures = {
  MOUSE_CLICK: "mouse-click",
  MOUSE_MOVE: "mouse-move",
  KEYBOARD_PRESS: "keyboard-press",
};

const UserGestureTests = [
  { type: UserGestures.MOUSE_CLICK, isActivationGesture: true },
  { type: UserGestures.MOUSE_MOVE, isActivationGesture: false },
  // test different keycode here. printable key, non-printable key and other
  // special keys.
  {
    type: UserGestures.KEYBOARD_PRESS,
    isActivationGesture: true,
    keyCode: "a",
  },
  {
    type: UserGestures.KEYBOARD_PRESS,
    isActivationGesture: false,
    keyCode: "VK_ESCAPE",
  },
  {
    type: UserGestures.KEYBOARD_PRESS,
    isActivationGesture: true,
    keyCode: "VK_RETURN",
  },
  {
    type: UserGestures.KEYBOARD_PRESS,
    isActivationGesture: true,
    keyCode: "VK_SPACE",
  },
];

/**
 * This test is used to ensure we would stop blocking autoplay after document
 * has been activated by user gestures. We would treat mouse clicking, key board
 * pressing (printable keys or carriage return) as valid user gesture input.
 */
add_task(async function startTestUserGestureInput() {
  info("- setup test preference -");
  await setupTestPreferences();

  info("- test play when page doesn't be activated -");
  await testPlayWithoutUserGesture();

  info("- test play after page got user gesture -");
  for (let idx = 0; idx < UserGestureTests.length; idx++) {
    info("- test play after page got user gesture -");
    await testPlayWithUserGesture(UserGestureTests[idx]);

    info("- test web audio with user gesture -");
    await testWebAudioWithUserGesture(UserGestureTests[idx]);
  }
});

/**
 * testing helper functions
 */
function setupTestPreferences() {
  return SpecialPowers.pushPrefEnv({
    set: [
      ["media.autoplay.default", SpecialPowers.Ci.nsIAutoplay.BLOCKED],
      ["media.autoplay.blocking_policy", 0],
      ["media.autoplay.block-event.enabled", true],
      ["media.autoplay.block-webaudio", true],
    ],
  });
}

function simulateUserGesture(gesture, targetBrowser) {
  info(`- simulate ${gesture.type} event -`);
  switch (gesture.type) {
    case UserGestures.MOUSE_CLICK:
      return BrowserTestUtils.synthesizeMouseAtCenter(
        "body",
        { button: 0 },
        targetBrowser
      );
    case UserGestures.MOUSE_MOVE:
      return BrowserTestUtils.synthesizeMouseAtCenter(
        "body",
        { type: "mousemove" },
        targetBrowser
      );
    case UserGestures.KEYBOARD_PRESS:
      info(`- keycode=${gesture.keyCode} -`);
      return BrowserTestUtils.synthesizeKey(gesture.keyCode, {}, targetBrowser);
    default:
      ok(false, "undefined user gesture");
      return false;
  }
}

async function testPlayWithoutUserGesture() {
  info("- open new tab -");
  let tab = await BrowserTestUtils.openNewForegroundTab(
    window.gBrowser,
    "about:blank"
  );
  BrowserTestUtils.loadURIString(tab.linkedBrowser, VIDEO_PAGE);
  await BrowserTestUtils.browserLoaded(tab.linkedBrowser);

  async function checkAutoplayKeyword() {
    info("- create an new autoplay video -");
    let video = content.document.createElement("video");
    video.src = "gizmo.mp4";
    video.autoplay = true;
    let canplayPromise = new Promise(function (resolve) {
      video.addEventListener(
        "canplaythrough",
        function () {
          resolve();
        },
        { once: true }
      );
    });
    content.document.body.appendChild(video);

    info("- can't autoplay without user activation -");
    await canplayPromise;
    ok(video.paused, "video can't start without user input.");
  }
  await SpecialPowers.spawn(tab.linkedBrowser, [], checkAutoplayKeyword);

  async function playVideo() {
    let video = content.document.getElementById("v");
    info("- call play() without user activation -");
    await video.play().catch(function () {
      ok(video.paused, "video can't start play without user input.");
    });
  }
  await SpecialPowers.spawn(tab.linkedBrowser, [], playVideo);

  info("- remove tab -");
  BrowserTestUtils.removeTab(tab);
}

async function testPlayWithUserGesture(gesture) {
  info("- open new tab -");
  let tab = await BrowserTestUtils.openNewForegroundTab(
    window.gBrowser,
    "about:blank"
  );
  BrowserTestUtils.loadURIString(tab.linkedBrowser, VIDEO_PAGE);
  await BrowserTestUtils.browserLoaded(tab.linkedBrowser);

  info("- simulate user gesture -");
  await simulateUserGesture(gesture, tab.linkedBrowser);

  info("- call play() -");
  async function playVideo(gesture) {
    let video = content.document.getElementById("v");
    try {
      await video.play();
      ok(gesture.isActivationGesture, "user gesture can activate the page");
      ok(!video.paused, "video starts playing.");
    } catch (e) {
      ok(
        !gesture.isActivationGesture,
        "user gesture can not activate the page"
      );
      ok(video.paused, "video can not start playing.");
    }
  }

  await SpecialPowers.spawn(tab.linkedBrowser, [gesture], playVideo);

  info("- remove tab -");
  BrowserTestUtils.removeTab(tab);
}

function createAudioContext() {
  content.ac = new content.AudioContext();
  let ac = content.ac;
  ac.resumePromises = [];
  ac.stateChangePromise = new Promise(resolve => {
    ac.addEventListener(
      "statechange",
      function () {
        resolve();
      },
      { once: true }
    );
  });
  ac.notAllowedToStart = new Promise(resolve => {
    ac.addEventListener(
      "blocked",
      function () {
        resolve();
      },
      { once: true }
    );
  });
}

function resumeWithoutExpectedSuccess() {
  let ac = content.ac;
  let promise = ac.resume();
  ac.resumePromises.push(promise);
  return new Promise((resolve, reject) => {
    content.setTimeout(() => {
      if (ac.state == "suspended") {
        ok(true, "audio context is still suspended");
        resolve();
      } else {
        reject("audio context should not be allowed to start");
      }
    }, 2000);
  });
}

function resumeWithExpectedSuccess() {
  let ac = content.ac;
  ac.resumePromises.push(ac.resume());
  return Promise.all(ac.resumePromises).then(() => {
    ok(ac.state == "running", "audio context starts running");
  });
}

async function testWebAudioWithUserGesture(gesture) {
  info("- open new tab -");
  let tab = await BrowserTestUtils.openNewForegroundTab(
    window.gBrowser,
    "about:blank"
  );
  info("- create audio context -");
  await SpecialPowers.spawn(tab.linkedBrowser, [], () => {
    content.ac = new content.AudioContext();
    let ac = content.ac;
    ac.resumePromises = [];
    return new Promise(resolve => {
      ac.addEventListener(
        "blocked",
        function () {
          Assert.equal(
            ac.state,
            "suspended",
            `AudioContext is not started yet.`
          );
          resolve();
        },
        { once: true }
      );
    });
  });

  info("- calling resume() -");
  try {
    await SpecialPowers.spawn(
      tab.linkedBrowser,
      [],
      resumeWithoutExpectedSuccess
    );
  } catch (error) {
    ok(false, error.toString());
  }

  info("- simulate user gesture -");
  await simulateUserGesture(gesture, tab.linkedBrowser);

  info("- calling resume() again");
  try {
    let resumeFunc = gesture.isActivationGesture
      ? resumeWithExpectedSuccess
      : resumeWithoutExpectedSuccess;
    await SpecialPowers.spawn(tab.linkedBrowser, [], resumeFunc);
  } catch (error) {
    ok(false, error.toString());
  }

  info("- remove tab -");
  await BrowserTestUtils.removeTab(tab);
}