blob: 3d0594a7b93bfd40cd5ceefc23aa172adabc6913 [file] [log] [blame] [view]
zqzhang4b8096b2017-03-30 11:28:291# Autoplay of HTMLMediaElements
2
3Autoplay is the concept of playing media elements without user gesture. On
4desktop, autoplay is always allowed. On mobile, only muted video elements are
5allowed to autoplay. The autoplay logic follows
6the
7[HTML spec](https://html.spec.whatwg.org/multipage/embedded-content.html#media-elements).
8
9There are two ways of initiating autoplay:
10
11* Autoplay by attribute: Setting the `autoplay` attribute on the media element.
12 The element will try to autoplay when the `readyState` changes to
13 HAVE_ENOUGH_DATA.
14* Autoplay by `play()` method: Explicitly calling the `play()` method without
15 user gesture.
16
zqzhang12d76ad2017-04-20 21:24:0517All the autoplay logic is handled by the AutoplayPolicy class. When the media
18element wants to perform some action (like unmute, autoplay by attribute or
19`play()` method), it will send a request to AutoplayPolicy, and if the request
20is approved, the element can autoplay, otherwise it should be paused. Also the
21media element should inform the AutoplayPolicy about relevant changes such as
22"the element has been moved to a new document".
23
zqzhang4b8096b2017-03-30 11:28:2924## User gesture lock
25
26Each media element has a user gesture lock. If the element is allowed to
27autoplay, the lock is initialized as `false`, otherwise it's `true`.
28
29When the element is trying to initate autoplay, we check the gesture lock. If
30the lock is `false`, it will be allowed. Otherwise autoplay will be blocked. An
31exception is that if the element is a muted video element, the gesture lock
32check will be bypassed.
33
34To unlock the gesture lock (make it `false`). The page needs to call play() or
35load() on the element when responding to a user gesture.
36
37## Autoplay flowchart
38
39The treatments of autoplay by different methods are different. For autoplay by
40attribute, it is:
41
42![Autoplay by attribute](autoplay_by_attribute.png)
43
44This means if autoplay is initiated by attribute, it enters the autoplaying
45phase, we play it as long as the video is visible. When the page explicitly
46calls `play()`, `pause()`, we leave the autoplaying phase. When the page tries
47to unmute the video, we check the gesture lock and pause the video if it is
48still `true`.
49
50For autoplay by `play()` method, it is:
51
52![Autoplay by play() method](autoplay_by_play_method.png)
53
54This means if autoplay is initiated by `play()` method, we continue playing the
55video as normal `play()`. However if the page tries to unmute the video, we check
56the gesture lock and pause the video if it is still `true`.