zqzhang | 4b8096b | 2017-03-30 11:28:29 | [diff] [blame] | 1 | # Autoplay of HTMLMediaElements |
| 2 | |
| 3 | Autoplay is the concept of playing media elements without user gesture. On |
| 4 | desktop, autoplay is always allowed. On mobile, only muted video elements are |
| 5 | allowed to autoplay. The autoplay logic follows |
| 6 | the |
| 7 | [HTML spec](https://html.spec.whatwg.org/multipage/embedded-content.html#media-elements). |
| 8 | |
| 9 | There 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 | |
zqzhang | 12d76ad | 2017-04-20 21:24:05 | [diff] [blame] | 17 | All the autoplay logic is handled by the AutoplayPolicy class. When the media |
| 18 | element 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 |
| 20 | is approved, the element can autoplay, otherwise it should be paused. Also the |
| 21 | media element should inform the AutoplayPolicy about relevant changes such as |
| 22 | "the element has been moved to a new document". |
| 23 | |
zqzhang | 4b8096b | 2017-03-30 11:28:29 | [diff] [blame] | 24 | ## User gesture lock |
| 25 | |
| 26 | Each media element has a user gesture lock. If the element is allowed to |
| 27 | autoplay, the lock is initialized as `false`, otherwise it's `true`. |
| 28 | |
| 29 | When the element is trying to initate autoplay, we check the gesture lock. If |
| 30 | the lock is `false`, it will be allowed. Otherwise autoplay will be blocked. An |
| 31 | exception is that if the element is a muted video element, the gesture lock |
| 32 | check will be bypassed. |
| 33 | |
| 34 | To unlock the gesture lock (make it `false`). The page needs to call play() or |
| 35 | load() on the element when responding to a user gesture. |
| 36 | |
| 37 | ## Autoplay flowchart |
| 38 | |
| 39 | The treatments of autoplay by different methods are different. For autoplay by |
| 40 | attribute, it is: |
| 41 | |
| 42 |  |
| 43 | |
| 44 | This means if autoplay is initiated by attribute, it enters the autoplaying |
| 45 | phase, we play it as long as the video is visible. When the page explicitly |
| 46 | calls `play()`, `pause()`, we leave the autoplaying phase. When the page tries |
| 47 | to unmute the video, we check the gesture lock and pause the video if it is |
| 48 | still `true`. |
| 49 | |
| 50 | For autoplay by `play()` method, it is: |
| 51 | |
| 52 |  |
| 53 | |
| 54 | This means if autoplay is initiated by `play()` method, we continue playing the |
| 55 | video as normal `play()`. However if the page tries to unmute the video, we check |
| 56 | the gesture lock and pause the video if it is still `true`. |