You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30174 lines
955 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /**
  2. * @license
  3. * Video.js 8.21.1 <http://videojs.com/>
  4. * Copyright Brightcove, Inc. <https://www.brightcove.com/>
  5. * Available under Apache License Version 2.0
  6. * <https://github.com/videojs/video.js/blob/main/LICENSE>
  7. *
  8. * Includes vtt.js <https://github.com/mozilla/vtt.js>
  9. * Available under Apache License Version 2.0
  10. * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
  11. */
  12. (function (global, factory) {
  13. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  14. typeof define === 'function' && define.amd ? define(factory) :
  15. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.videojs = factory());
  16. })(this, (function () { 'use strict';
  17. var version = "8.21.1";
  18. /**
  19. * An Object that contains lifecycle hooks as keys which point to an array
  20. * of functions that are run when a lifecycle is triggered
  21. *
  22. * @private
  23. */
  24. const hooks_ = {};
  25. /**
  26. * Get a list of hooks for a specific lifecycle
  27. *
  28. * @param {string} type
  29. * the lifecycle to get hooks from
  30. *
  31. * @param {Function|Function[]} [fn]
  32. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  33. *
  34. * @return {Array}
  35. * an array of hooks, or an empty array if there are none.
  36. */
  37. const hooks = function (type, fn) {
  38. hooks_[type] = hooks_[type] || [];
  39. if (fn) {
  40. hooks_[type] = hooks_[type].concat(fn);
  41. }
  42. return hooks_[type];
  43. };
  44. /**
  45. * Add a function hook to a specific videojs lifecycle.
  46. *
  47. * @param {string} type
  48. * the lifecycle to hook the function to.
  49. *
  50. * @param {Function|Function[]}
  51. * The function or array of functions to attach.
  52. */
  53. const hook = function (type, fn) {
  54. hooks(type, fn);
  55. };
  56. /**
  57. * Remove a hook from a specific videojs lifecycle.
  58. *
  59. * @param {string} type
  60. * the lifecycle that the function hooked to
  61. *
  62. * @param {Function} fn
  63. * The hooked function to remove
  64. *
  65. * @return {boolean}
  66. * The function that was removed or undef
  67. */
  68. const removeHook = function (type, fn) {
  69. const index = hooks(type).indexOf(fn);
  70. if (index <= -1) {
  71. return false;
  72. }
  73. hooks_[type] = hooks_[type].slice();
  74. hooks_[type].splice(index, 1);
  75. return true;
  76. };
  77. /**
  78. * Add a function hook that will only run once to a specific videojs lifecycle.
  79. *
  80. * @param {string} type
  81. * the lifecycle to hook the function to.
  82. *
  83. * @param {Function|Function[]}
  84. * The function or array of functions to attach.
  85. */
  86. const hookOnce = function (type, fn) {
  87. hooks(type, [].concat(fn).map(original => {
  88. const wrapper = (...args) => {
  89. removeHook(type, wrapper);
  90. return original(...args);
  91. };
  92. return wrapper;
  93. }));
  94. };
  95. /**
  96. * @file fullscreen-api.js
  97. * @module fullscreen-api
  98. */
  99. /**
  100. * Store the browser-specific methods for the fullscreen API.
  101. *
  102. * @type {Object}
  103. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  104. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  105. */
  106. const FullscreenApi = {
  107. prefixed: true
  108. };
  109. // browser API methods
  110. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  111. // WebKit
  112. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen']];
  113. const specApi = apiMap[0];
  114. let browserApi;
  115. // determine the supported set of functions
  116. for (let i = 0; i < apiMap.length; i++) {
  117. // check for exitFullscreen function
  118. if (apiMap[i][1] in document) {
  119. browserApi = apiMap[i];
  120. break;
  121. }
  122. }
  123. // map the browser API names to the spec API names
  124. if (browserApi) {
  125. for (let i = 0; i < browserApi.length; i++) {
  126. FullscreenApi[specApi[i]] = browserApi[i];
  127. }
  128. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  129. }
  130. /**
  131. * @file create-logger.js
  132. * @module create-logger
  133. */
  134. // This is the private tracking variable for the logging history.
  135. let history = [];
  136. /**
  137. * Log messages to the console and history based on the type of message
  138. *
  139. * @private
  140. * @param {string} name
  141. * The name of the console method to use.
  142. *
  143. * @param {Object} log
  144. * The arguments to be passed to the matching console method.
  145. *
  146. * @param {string} [styles]
  147. * styles for name
  148. */
  149. const LogByTypeFactory = (name, log, styles) => (type, level, args) => {
  150. const lvl = log.levels[level];
  151. const lvlRegExp = new RegExp(`^(${lvl})$`);
  152. let resultName = name;
  153. if (type !== 'log') {
  154. // Add the type to the front of the message when it's not "log".
  155. args.unshift(type.toUpperCase() + ':');
  156. }
  157. if (styles) {
  158. resultName = `%c${name}`;
  159. args.unshift(styles);
  160. }
  161. // Add console prefix after adding to history.
  162. args.unshift(resultName + ':');
  163. // Add a clone of the args at this point to history.
  164. if (history) {
  165. history.push([].concat(args));
  166. // only store 1000 history entries
  167. const splice = history.length - 1000;
  168. history.splice(0, splice > 0 ? splice : 0);
  169. }
  170. // If there's no console then don't try to output messages, but they will
  171. // still be stored in history.
  172. if (!window.console) {
  173. return;
  174. }
  175. // Was setting these once outside of this function, but containing them
  176. // in the function makes it easier to test cases where console doesn't exist
  177. // when the module is executed.
  178. let fn = window.console[type];
  179. if (!fn && type === 'debug') {
  180. // Certain browsers don't have support for console.debug. For those, we
  181. // should default to the closest comparable log.
  182. fn = window.console.info || window.console.log;
  183. }
  184. // Bail out if there's no console or if this type is not allowed by the
  185. // current logging level.
  186. if (!fn || !lvl || !lvlRegExp.test(type)) {
  187. return;
  188. }
  189. fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
  190. };
  191. function createLogger$1(name, delimiter = ':', styles = '') {
  192. // This is the private tracking variable for logging level.
  193. let level = 'info';
  194. // the curried logByType bound to the specific log and history
  195. let logByType;
  196. /**
  197. * Logs plain debug messages. Similar to `console.log`.
  198. *
  199. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  200. * of our JSDoc template, we cannot properly document this as both a function
  201. * and a namespace, so its function signature is documented here.
  202. *
  203. * #### Arguments
  204. * ##### *args
  205. * *[]
  206. *
  207. * Any combination of values that could be passed to `console.log()`.
  208. *
  209. * #### Return Value
  210. *
  211. * `undefined`
  212. *
  213. * @namespace
  214. * @param {...*} args
  215. * One or more messages or objects that should be logged.
  216. */
  217. function log(...args) {
  218. logByType('log', level, args);
  219. }
  220. // This is the logByType helper that the logging methods below use
  221. logByType = LogByTypeFactory(name, log, styles);
  222. /**
  223. * Create a new subLogger which chains the old name to the new name.
  224. *
  225. * For example, doing `mylogger = videojs.log.createLogger('player')` and then using that logger will log the following:
  226. * ```js
  227. * mylogger('foo');
  228. * // > VIDEOJS: player: foo
  229. * ```
  230. *
  231. * @param {string} subName
  232. * The name to add call the new logger
  233. * @param {string} [subDelimiter]
  234. * Optional delimiter
  235. * @param {string} [subStyles]
  236. * Optional styles
  237. * @return {Object}
  238. */
  239. log.createLogger = (subName, subDelimiter, subStyles) => {
  240. const resultDelimiter = subDelimiter !== undefined ? subDelimiter : delimiter;
  241. const resultStyles = subStyles !== undefined ? subStyles : styles;
  242. const resultName = `${name} ${resultDelimiter} ${subName}`;
  243. return createLogger$1(resultName, resultDelimiter, resultStyles);
  244. };
  245. /**
  246. * Create a new logger.
  247. *
  248. * @param {string} newName
  249. * The name for the new logger
  250. * @param {string} [newDelimiter]
  251. * Optional delimiter
  252. * @param {string} [newStyles]
  253. * Optional styles
  254. * @return {Object}
  255. */
  256. log.createNewLogger = (newName, newDelimiter, newStyles) => {
  257. return createLogger$1(newName, newDelimiter, newStyles);
  258. };
  259. /**
  260. * Enumeration of available logging levels, where the keys are the level names
  261. * and the values are `|`-separated strings containing logging methods allowed
  262. * in that logging level. These strings are used to create a regular expression
  263. * matching the function name being called.
  264. *
  265. * Levels provided by Video.js are:
  266. *
  267. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  268. * this effect. The most restrictive.
  269. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  270. * `log.warn`, and `log.error`).
  271. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  272. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  273. * - `warn`: Matches `log.warn` and `log.error` calls.
  274. * - `error`: Matches only `log.error` calls.
  275. *
  276. * @type {Object}
  277. */
  278. log.levels = {
  279. all: 'debug|log|warn|error',
  280. off: '',
  281. debug: 'debug|log|warn|error',
  282. info: 'log|warn|error',
  283. warn: 'warn|error',
  284. error: 'error',
  285. DEFAULT: level
  286. };
  287. /**
  288. * Get or set the current logging level.
  289. *
  290. * If a string matching a key from {@link module:log.levels} is provided, acts
  291. * as a setter.
  292. *
  293. * @param {'all'|'debug'|'info'|'warn'|'error'|'off'} [lvl]
  294. * Pass a valid level to set a new logging level.
  295. *
  296. * @return {string}
  297. * The current logging level.
  298. */
  299. log.level = lvl => {
  300. if (typeof lvl === 'string') {
  301. if (!log.levels.hasOwnProperty(lvl)) {
  302. throw new Error(`"${lvl}" in not a valid log level`);
  303. }
  304. level = lvl;
  305. }
  306. return level;
  307. };
  308. /**
  309. * Returns an array containing everything that has been logged to the history.
  310. *
  311. * This array is a shallow clone of the internal history record. However, its
  312. * contents are _not_ cloned; so, mutating objects inside this array will
  313. * mutate them in history.
  314. *
  315. * @return {Array}
  316. */
  317. log.history = () => history ? [].concat(history) : [];
  318. /**
  319. * Allows you to filter the history by the given logger name
  320. *
  321. * @param {string} fname
  322. * The name to filter by
  323. *
  324. * @return {Array}
  325. * The filtered list to return
  326. */
  327. log.history.filter = fname => {
  328. return (history || []).filter(historyItem => {
  329. // if the first item in each historyItem includes `fname`, then it's a match
  330. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  331. });
  332. };
  333. /**
  334. * Clears the internal history tracking, but does not prevent further history
  335. * tracking.
  336. */
  337. log.history.clear = () => {
  338. if (history) {
  339. history.length = 0;
  340. }
  341. };
  342. /**
  343. * Disable history tracking if it is currently enabled.
  344. */
  345. log.history.disable = () => {
  346. if (history !== null) {
  347. history.length = 0;
  348. history = null;
  349. }
  350. };
  351. /**
  352. * Enable history tracking if it is currently disabled.
  353. */
  354. log.history.enable = () => {
  355. if (history === null) {
  356. history = [];
  357. }
  358. };
  359. /**
  360. * Logs error messages. Similar to `console.error`.
  361. *
  362. * @param {...*} args
  363. * One or more messages or objects that should be logged as an error
  364. */
  365. log.error = (...args) => logByType('error', level, args);
  366. /**
  367. * Logs warning messages. Similar to `console.warn`.
  368. *
  369. * @param {...*} args
  370. * One or more messages or objects that should be logged as a warning.
  371. */
  372. log.warn = (...args) => logByType('warn', level, args);
  373. /**
  374. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  375. * log if `console.debug` is not available
  376. *
  377. * @param {...*} args
  378. * One or more messages or objects that should be logged as debug.
  379. */
  380. log.debug = (...args) => logByType('debug', level, args);
  381. return log;
  382. }
  383. /**
  384. * @file log.js
  385. * @module log
  386. */
  387. const log = createLogger$1('VIDEOJS');
  388. const createLogger = log.createLogger;
  389. /**
  390. * @file obj.js
  391. * @module obj
  392. */
  393. /**
  394. * @callback obj:EachCallback
  395. *
  396. * @param {*} value
  397. * The current key for the object that is being iterated over.
  398. *
  399. * @param {string} key
  400. * The current key-value for object that is being iterated over
  401. */
  402. /**
  403. * @callback obj:ReduceCallback
  404. *
  405. * @param {*} accum
  406. * The value that is accumulating over the reduce loop.
  407. *
  408. * @param {*} value
  409. * The current key for the object that is being iterated over.
  410. *
  411. * @param {string} key
  412. * The current key-value for object that is being iterated over
  413. *
  414. * @return {*}
  415. * The new accumulated value.
  416. */
  417. const toString$1 = Object.prototype.toString;
  418. /**
  419. * Get the keys of an Object
  420. *
  421. * @param {Object}
  422. * The Object to get the keys from
  423. *
  424. * @return {string[]}
  425. * An array of the keys from the object. Returns an empty array if the
  426. * object passed in was invalid or had no keys.
  427. *
  428. * @private
  429. */
  430. const keys = function (object) {
  431. return isObject(object) ? Object.keys(object) : [];
  432. };
  433. /**
  434. * Array-like iteration for objects.
  435. *
  436. * @param {Object} object
  437. * The object to iterate over
  438. *
  439. * @param {obj:EachCallback} fn
  440. * The callback function which is called for each key in the object.
  441. */
  442. function each(object, fn) {
  443. keys(object).forEach(key => fn(object[key], key));
  444. }
  445. /**
  446. * Array-like reduce for objects.
  447. *
  448. * @param {Object} object
  449. * The Object that you want to reduce.
  450. *
  451. * @param {Function} fn
  452. * A callback function which is called for each key in the object. It
  453. * receives the accumulated value and the per-iteration value and key
  454. * as arguments.
  455. *
  456. * @param {*} [initial = 0]
  457. * Starting value
  458. *
  459. * @return {*}
  460. * The final accumulated value.
  461. */
  462. function reduce(object, fn, initial = 0) {
  463. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  464. }
  465. /**
  466. * Returns whether a value is an object of any kind - including DOM nodes,
  467. * arrays, regular expressions, etc. Not functions, though.
  468. *
  469. * This avoids the gotcha where using `typeof` on a `null` value
  470. * results in `'object'`.
  471. *
  472. * @param {Object} value
  473. * @return {boolean}
  474. */
  475. function isObject(value) {
  476. return !!value && typeof value === 'object';
  477. }
  478. /**
  479. * Returns whether an object appears to be a "plain" object - that is, a
  480. * direct instance of `Object`.
  481. *
  482. * @param {Object} value
  483. * @return {boolean}
  484. */
  485. function isPlain(value) {
  486. return isObject(value) && toString$1.call(value) === '[object Object]' && value.constructor === Object;
  487. }
  488. /**
  489. * Merge two objects recursively.
  490. *
  491. * Performs a deep merge like
  492. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  493. * plain objects (not arrays, elements, or anything else).
  494. *
  495. * Non-plain object values will be copied directly from the right-most
  496. * argument.
  497. *
  498. * @param {Object[]} sources
  499. * One or more objects to merge into a new object.
  500. *
  501. * @return {Object}
  502. * A new object that is the merged result of all sources.
  503. */
  504. function merge(...sources) {
  505. const result = {};
  506. sources.forEach(source => {
  507. if (!source) {
  508. return;
  509. }
  510. each(source, (value, key) => {
  511. if (!isPlain(value)) {
  512. result[key] = value;
  513. return;
  514. }
  515. if (!isPlain(result[key])) {
  516. result[key] = {};
  517. }
  518. result[key] = merge(result[key], value);
  519. });
  520. });
  521. return result;
  522. }
  523. /**
  524. * Returns an array of values for a given object
  525. *
  526. * @param {Object} source - target object
  527. * @return {Array<unknown>} - object values
  528. */
  529. function values(source = {}) {
  530. const result = [];
  531. for (const key in source) {
  532. if (source.hasOwnProperty(key)) {
  533. const value = source[key];
  534. result.push(value);
  535. }
  536. }
  537. return result;
  538. }
  539. /**
  540. * Object.defineProperty but "lazy", which means that the value is only set after
  541. * it is retrieved the first time, rather than being set right away.
  542. *
  543. * @param {Object} obj the object to set the property on
  544. * @param {string} key the key for the property to set
  545. * @param {Function} getValue the function used to get the value when it is needed.
  546. * @param {boolean} setter whether a setter should be allowed or not
  547. */
  548. function defineLazyProperty(obj, key, getValue, setter = true) {
  549. const set = value => Object.defineProperty(obj, key, {
  550. value,
  551. enumerable: true,
  552. writable: true
  553. });
  554. const options = {
  555. configurable: true,
  556. enumerable: true,
  557. get() {
  558. const value = getValue();
  559. set(value);
  560. return value;
  561. }
  562. };
  563. if (setter) {
  564. options.set = set;
  565. }
  566. return Object.defineProperty(obj, key, options);
  567. }
  568. var Obj = /*#__PURE__*/Object.freeze({
  569. __proto__: null,
  570. each: each,
  571. reduce: reduce,
  572. isObject: isObject,
  573. isPlain: isPlain,
  574. merge: merge,
  575. values: values,
  576. defineLazyProperty: defineLazyProperty
  577. });
  578. /**
  579. * @file browser.js
  580. * @module browser
  581. */
  582. /**
  583. * Whether or not this device is an iPod.
  584. *
  585. * @static
  586. * @type {Boolean}
  587. */
  588. let IS_IPOD = false;
  589. /**
  590. * The detected iOS version - or `null`.
  591. *
  592. * @static
  593. * @type {string|null}
  594. */
  595. let IOS_VERSION = null;
  596. /**
  597. * Whether or not this is an Android device.
  598. *
  599. * @static
  600. * @type {Boolean}
  601. */
  602. let IS_ANDROID = false;
  603. /**
  604. * The detected Android version - or `null` if not Android or indeterminable.
  605. *
  606. * @static
  607. * @type {number|string|null}
  608. */
  609. let ANDROID_VERSION;
  610. /**
  611. * Whether or not this is Mozilla Firefox.
  612. *
  613. * @static
  614. * @type {Boolean}
  615. */
  616. let IS_FIREFOX = false;
  617. /**
  618. * Whether or not this is Microsoft Edge.
  619. *
  620. * @static
  621. * @type {Boolean}
  622. */
  623. let IS_EDGE = false;
  624. /**
  625. * Whether or not this is any Chromium Browser
  626. *
  627. * @static
  628. * @type {Boolean}
  629. */
  630. let IS_CHROMIUM = false;
  631. /**
  632. * Whether or not this is any Chromium browser that is not Edge.
  633. *
  634. * This will also be `true` for Chrome on iOS, which will have different support
  635. * as it is actually Safari under the hood.
  636. *
  637. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  638. * IS_CHROMIUM should be used instead.
  639. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  640. *
  641. * @static
  642. * @deprecated
  643. * @type {Boolean}
  644. */
  645. let IS_CHROME = false;
  646. /**
  647. * The detected Chromium version - or `null`.
  648. *
  649. * @static
  650. * @type {number|null}
  651. */
  652. let CHROMIUM_VERSION = null;
  653. /**
  654. * The detected Google Chrome version - or `null`.
  655. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  656. * Deprecated, use CHROMIUM_VERSION instead.
  657. *
  658. * @static
  659. * @deprecated
  660. * @type {number|null}
  661. */
  662. let CHROME_VERSION = null;
  663. /**
  664. * Whether or not this is a Chromecast receiver application.
  665. *
  666. * @static
  667. * @type {Boolean}
  668. */
  669. const IS_CHROMECAST_RECEIVER = Boolean(window.cast && window.cast.framework && window.cast.framework.CastReceiverContext);
  670. /**
  671. * The detected Internet Explorer version - or `null`.
  672. *
  673. * @static
  674. * @deprecated
  675. * @type {number|null}
  676. */
  677. let IE_VERSION = null;
  678. /**
  679. * Whether or not this is desktop Safari.
  680. *
  681. * @static
  682. * @type {Boolean}
  683. */
  684. let IS_SAFARI = false;
  685. /**
  686. * Whether or not this is a Windows machine.
  687. *
  688. * @static
  689. * @type {Boolean}
  690. */
  691. let IS_WINDOWS = false;
  692. /**
  693. * Whether or not this device is an iPad.
  694. *
  695. * @static
  696. * @type {Boolean}
  697. */
  698. let IS_IPAD = false;
  699. /**
  700. * Whether or not this device is an iPhone.
  701. *
  702. * @static
  703. * @type {Boolean}
  704. */
  705. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  706. // to identify iPhones, we need to exclude iPads.
  707. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  708. let IS_IPHONE = false;
  709. /**
  710. * Whether or not this is a Tizen device.
  711. *
  712. * @static
  713. * @type {Boolean}
  714. */
  715. let IS_TIZEN = false;
  716. /**
  717. * Whether or not this is a WebOS device.
  718. *
  719. * @static
  720. * @type {Boolean}
  721. */
  722. let IS_WEBOS = false;
  723. /**
  724. * Whether or not this is a Smart TV (Tizen or WebOS) device.
  725. *
  726. * @static
  727. * @type {Boolean}
  728. */
  729. let IS_SMART_TV = false;
  730. /**
  731. * Whether or not this device is touch-enabled.
  732. *
  733. * @static
  734. * @const
  735. * @type {Boolean}
  736. */
  737. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch));
  738. const UAD = window.navigator && window.navigator.userAgentData;
  739. if (UAD && UAD.platform && UAD.brands) {
  740. // If userAgentData is present, use it instead of userAgent to avoid warnings
  741. // Currently only implemented on Chromium
  742. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  743. IS_ANDROID = UAD.platform === 'Android';
  744. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  745. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  746. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  747. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  748. IS_WINDOWS = UAD.platform === 'Windows';
  749. }
  750. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  751. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  752. // the checks need to be made agiainst the regular userAgent string.
  753. if (!IS_CHROMIUM) {
  754. const USER_AGENT = window.navigator && window.navigator.userAgent || '';
  755. IS_IPOD = /iPod/i.test(USER_AGENT);
  756. IOS_VERSION = function () {
  757. const match = USER_AGENT.match(/OS (\d+)_/i);
  758. if (match && match[1]) {
  759. return match[1];
  760. }
  761. return null;
  762. }();
  763. IS_ANDROID = /Android/i.test(USER_AGENT);
  764. ANDROID_VERSION = function () {
  765. // This matches Android Major.Minor.Patch versions
  766. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  767. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  768. if (!match) {
  769. return null;
  770. }
  771. const major = match[1] && parseFloat(match[1]);
  772. const minor = match[2] && parseFloat(match[2]);
  773. if (major && minor) {
  774. return parseFloat(match[1] + '.' + match[2]);
  775. } else if (major) {
  776. return major;
  777. }
  778. return null;
  779. }();
  780. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  781. IS_EDGE = /Edg/i.test(USER_AGENT);
  782. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  783. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  784. CHROMIUM_VERSION = CHROME_VERSION = function () {
  785. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  786. if (match && match[2]) {
  787. return parseFloat(match[2]);
  788. }
  789. return null;
  790. }();
  791. IE_VERSION = function () {
  792. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  793. let version = result && parseFloat(result[1]);
  794. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  795. // IE 11 has a different user agent string than other IE versions
  796. version = 11.0;
  797. }
  798. return version;
  799. }();
  800. IS_TIZEN = /Tizen/i.test(USER_AGENT);
  801. IS_WEBOS = /Web0S/i.test(USER_AGENT);
  802. IS_SMART_TV = IS_TIZEN || IS_WEBOS;
  803. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE && !IS_SMART_TV;
  804. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  805. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  806. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  807. }
  808. /**
  809. * Whether or not this is an iOS device.
  810. *
  811. * @static
  812. * @const
  813. * @type {Boolean}
  814. */
  815. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  816. /**
  817. * Whether or not this is any flavor of Safari - including iOS.
  818. *
  819. * @static
  820. * @const
  821. * @type {Boolean}
  822. */
  823. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  824. var browser = /*#__PURE__*/Object.freeze({
  825. __proto__: null,
  826. get IS_IPOD () { return IS_IPOD; },
  827. get IOS_VERSION () { return IOS_VERSION; },
  828. get IS_ANDROID () { return IS_ANDROID; },
  829. get ANDROID_VERSION () { return ANDROID_VERSION; },
  830. get IS_FIREFOX () { return IS_FIREFOX; },
  831. get IS_EDGE () { return IS_EDGE; },
  832. get IS_CHROMIUM () { return IS_CHROMIUM; },
  833. get IS_CHROME () { return IS_CHROME; },
  834. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  835. get CHROME_VERSION () { return CHROME_VERSION; },
  836. IS_CHROMECAST_RECEIVER: IS_CHROMECAST_RECEIVER,
  837. get IE_VERSION () { return IE_VERSION; },
  838. get IS_SAFARI () { return IS_SAFARI; },
  839. get IS_WINDOWS () { return IS_WINDOWS; },
  840. get IS_IPAD () { return IS_IPAD; },
  841. get IS_IPHONE () { return IS_IPHONE; },
  842. get IS_TIZEN () { return IS_TIZEN; },
  843. get IS_WEBOS () { return IS_WEBOS; },
  844. get IS_SMART_TV () { return IS_SMART_TV; },
  845. TOUCH_ENABLED: TOUCH_ENABLED,
  846. IS_IOS: IS_IOS,
  847. IS_ANY_SAFARI: IS_ANY_SAFARI
  848. });
  849. /**
  850. * @file dom.js
  851. * @module dom
  852. */
  853. /**
  854. * Detect if a value is a string with any non-whitespace characters.
  855. *
  856. * @private
  857. * @param {string} str
  858. * The string to check
  859. *
  860. * @return {boolean}
  861. * Will be `true` if the string is non-blank, `false` otherwise.
  862. *
  863. */
  864. function isNonBlankString(str) {
  865. // we use str.trim as it will trim any whitespace characters
  866. // from the front or back of non-whitespace characters. aka
  867. // Any string that contains non-whitespace characters will
  868. // still contain them after `trim` but whitespace only strings
  869. // will have a length of 0, failing this check.
  870. return typeof str === 'string' && Boolean(str.trim());
  871. }
  872. /**
  873. * Throws an error if the passed string has whitespace. This is used by
  874. * class methods to be relatively consistent with the classList API.
  875. *
  876. * @private
  877. * @param {string} str
  878. * The string to check for whitespace.
  879. *
  880. * @throws {Error}
  881. * Throws an error if there is whitespace in the string.
  882. */
  883. function throwIfWhitespace(str) {
  884. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  885. if (str.indexOf(' ') >= 0) {
  886. throw new Error('class has illegal whitespace characters');
  887. }
  888. }
  889. /**
  890. * Whether the current DOM interface appears to be real (i.e. not simulated).
  891. *
  892. * @return {boolean}
  893. * Will be `true` if the DOM appears to be real, `false` otherwise.
  894. */
  895. function isReal() {
  896. // Both document and window will never be undefined thanks to `global`.
  897. return document === window.document;
  898. }
  899. /**
  900. * Determines, via duck typing, whether or not a value is a DOM element.
  901. *
  902. * @param {*} value
  903. * The value to check.
  904. *
  905. * @return {boolean}
  906. * Will be `true` if the value is a DOM element, `false` otherwise.
  907. */
  908. function isEl(value) {
  909. return isObject(value) && value.nodeType === 1;
  910. }
  911. /**
  912. * Determines if the current DOM is embedded in an iframe.
  913. *
  914. * @return {boolean}
  915. * Will be `true` if the DOM is embedded in an iframe, `false`
  916. * otherwise.
  917. */
  918. function isInFrame() {
  919. // We need a try/catch here because Safari will throw errors when attempting
  920. // to get either `parent` or `self`
  921. try {
  922. return window.parent !== window.self;
  923. } catch (x) {
  924. return true;
  925. }
  926. }
  927. /**
  928. * Creates functions to query the DOM using a given method.
  929. *
  930. * @private
  931. * @param {string} method
  932. * The method to create the query with.
  933. *
  934. * @return {Function}
  935. * The query method
  936. */
  937. function createQuerier(method) {
  938. return function (selector, context) {
  939. if (!isNonBlankString(selector)) {
  940. return document[method](null);
  941. }
  942. if (isNonBlankString(context)) {
  943. context = document.querySelector(context);
  944. }
  945. const ctx = isEl(context) ? context : document;
  946. return ctx[method] && ctx[method](selector);
  947. };
  948. }
  949. /**
  950. * Creates an element and applies properties, attributes, and inserts content.
  951. *
  952. * @param {string} [tagName='div']
  953. * Name of tag to be created.
  954. *
  955. * @param {Object} [properties={}]
  956. * Element properties to be applied.
  957. *
  958. * @param {Object} [attributes={}]
  959. * Element attributes to be applied.
  960. *
  961. * @param {ContentDescriptor} [content]
  962. * A content descriptor object.
  963. *
  964. * @return {Element}
  965. * The element that was created.
  966. */
  967. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  968. const el = document.createElement(tagName);
  969. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  970. const val = properties[propName];
  971. // Handle textContent since it's not supported everywhere and we have a
  972. // method for it.
  973. if (propName === 'textContent') {
  974. textContent(el, val);
  975. } else if (el[propName] !== val || propName === 'tabIndex') {
  976. el[propName] = val;
  977. }
  978. });
  979. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  980. el.setAttribute(attrName, attributes[attrName]);
  981. });
  982. if (content) {
  983. appendContent(el, content);
  984. }
  985. return el;
  986. }
  987. /**
  988. * Injects text into an element, replacing any existing contents entirely.
  989. *
  990. * @param {HTMLElement} el
  991. * The element to add text content into
  992. *
  993. * @param {string} text
  994. * The text content to add.
  995. *
  996. * @return {Element}
  997. * The element with added text content.
  998. */
  999. function textContent(el, text) {
  1000. if (typeof el.textContent === 'undefined') {
  1001. el.innerText = text;
  1002. } else {
  1003. el.textContent = text;
  1004. }
  1005. return el;
  1006. }
  1007. /**
  1008. * Insert an element as the first child node of another
  1009. *
  1010. * @param {Element} child
  1011. * Element to insert
  1012. *
  1013. * @param {Element} parent
  1014. * Element to insert child into
  1015. */
  1016. function prependTo(child, parent) {
  1017. if (parent.firstChild) {
  1018. parent.insertBefore(child, parent.firstChild);
  1019. } else {
  1020. parent.appendChild(child);
  1021. }
  1022. }
  1023. /**
  1024. * Check if an element has a class name.
  1025. *
  1026. * @param {Element} element
  1027. * Element to check
  1028. *
  1029. * @param {string} classToCheck
  1030. * Class name to check for
  1031. *
  1032. * @return {boolean}
  1033. * Will be `true` if the element has a class, `false` otherwise.
  1034. *
  1035. * @throws {Error}
  1036. * Throws an error if `classToCheck` has white space.
  1037. */
  1038. function hasClass(element, classToCheck) {
  1039. throwIfWhitespace(classToCheck);
  1040. return element.classList.contains(classToCheck);
  1041. }
  1042. /**
  1043. * Add a class name to an element.
  1044. *
  1045. * @param {Element} element
  1046. * Element to add class name to.
  1047. *
  1048. * @param {...string} classesToAdd
  1049. * One or more class name to add.
  1050. *
  1051. * @return {Element}
  1052. * The DOM element with the added class name.
  1053. */
  1054. function addClass(element, ...classesToAdd) {
  1055. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  1056. return element;
  1057. }
  1058. /**
  1059. * Remove a class name from an element.
  1060. *
  1061. * @param {Element} element
  1062. * Element to remove a class name from.
  1063. *
  1064. * @param {...string} classesToRemove
  1065. * One or more class name to remove.
  1066. *
  1067. * @return {Element}
  1068. * The DOM element with class name removed.
  1069. */
  1070. function removeClass(element, ...classesToRemove) {
  1071. // Protect in case the player gets disposed
  1072. if (!element) {
  1073. log.warn("removeClass was called with an element that doesn't exist");
  1074. return null;
  1075. }
  1076. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  1077. return element;
  1078. }
  1079. /**
  1080. * The callback definition for toggleClass.
  1081. *
  1082. * @callback PredicateCallback
  1083. * @param {Element} element
  1084. * The DOM element of the Component.
  1085. *
  1086. * @param {string} classToToggle
  1087. * The `className` that wants to be toggled
  1088. *
  1089. * @return {boolean|undefined}
  1090. * If `true` is returned, the `classToToggle` will be added to the
  1091. * `element`, but not removed. If `false`, the `classToToggle` will be removed from
  1092. * the `element`, but not added. If `undefined`, the callback will be ignored.
  1093. *
  1094. */
  1095. /**
  1096. * Adds or removes a class name to/from an element depending on an optional
  1097. * condition or the presence/absence of the class name.
  1098. *
  1099. * @param {Element} element
  1100. * The element to toggle a class name on.
  1101. *
  1102. * @param {string} classToToggle
  1103. * The class that should be toggled.
  1104. *
  1105. * @param {boolean|PredicateCallback} [predicate]
  1106. * See the return value for {@link module:dom~PredicateCallback}
  1107. *
  1108. * @return {Element}
  1109. * The element with a class that has been toggled.
  1110. */
  1111. function toggleClass(element, classToToggle, predicate) {
  1112. if (typeof predicate === 'function') {
  1113. predicate = predicate(element, classToToggle);
  1114. }
  1115. if (typeof predicate !== 'boolean') {
  1116. predicate = undefined;
  1117. }
  1118. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1119. return element;
  1120. }
  1121. /**
  1122. * Apply attributes to an HTML element.
  1123. *
  1124. * @param {Element} el
  1125. * Element to add attributes to.
  1126. *
  1127. * @param {Object} [attributes]
  1128. * Attributes to be applied.
  1129. */
  1130. function setAttributes(el, attributes) {
  1131. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1132. const attrValue = attributes[attrName];
  1133. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1134. el.removeAttribute(attrName);
  1135. } else {
  1136. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1137. }
  1138. });
  1139. }
  1140. /**
  1141. * Get an element's attribute values, as defined on the HTML tag.
  1142. *
  1143. * Attributes are not the same as properties. They're defined on the tag
  1144. * or with setAttribute.
  1145. *
  1146. * @param {Element} tag
  1147. * Element from which to get tag attributes.
  1148. *
  1149. * @return {Object}
  1150. * All attributes of the element. Boolean attributes will be `true` or
  1151. * `false`, others will be strings.
  1152. */
  1153. function getAttributes(tag) {
  1154. const obj = {};
  1155. // known boolean attributes
  1156. // we can check for matching boolean properties, but not all browsers
  1157. // and not all tags know about these attributes, so, we still want to check them manually
  1158. const knownBooleans = ['autoplay', 'controls', 'playsinline', 'loop', 'muted', 'default', 'defaultMuted'];
  1159. if (tag && tag.attributes && tag.attributes.length > 0) {
  1160. const attrs = tag.attributes;
  1161. for (let i = attrs.length - 1; i >= 0; i--) {
  1162. const attrName = attrs[i].name;
  1163. /** @type {boolean|string} */
  1164. let attrVal = attrs[i].value;
  1165. // check for known booleans
  1166. // the matching element property will return a value for typeof
  1167. if (knownBooleans.includes(attrName)) {
  1168. // the value of an included boolean attribute is typically an empty
  1169. // string ('') which would equal false if we just check for a false value.
  1170. // we also don't want support bad code like autoplay='false'
  1171. attrVal = attrVal !== null ? true : false;
  1172. }
  1173. obj[attrName] = attrVal;
  1174. }
  1175. }
  1176. return obj;
  1177. }
  1178. /**
  1179. * Get the value of an element's attribute.
  1180. *
  1181. * @param {Element} el
  1182. * A DOM element.
  1183. *
  1184. * @param {string} attribute
  1185. * Attribute to get the value of.
  1186. *
  1187. * @return {string}
  1188. * The value of the attribute.
  1189. */
  1190. function getAttribute(el, attribute) {
  1191. return el.getAttribute(attribute);
  1192. }
  1193. /**
  1194. * Set the value of an element's attribute.
  1195. *
  1196. * @param {Element} el
  1197. * A DOM element.
  1198. *
  1199. * @param {string} attribute
  1200. * Attribute to set.
  1201. *
  1202. * @param {string} value
  1203. * Value to set the attribute to.
  1204. */
  1205. function setAttribute(el, attribute, value) {
  1206. el.setAttribute(attribute, value);
  1207. }
  1208. /**
  1209. * Remove an element's attribute.
  1210. *
  1211. * @param {Element} el
  1212. * A DOM element.
  1213. *
  1214. * @param {string} attribute
  1215. * Attribute to remove.
  1216. */
  1217. function removeAttribute(el, attribute) {
  1218. el.removeAttribute(attribute);
  1219. }
  1220. /**
  1221. * Attempt to block the ability to select text.
  1222. */
  1223. function blockTextSelection() {
  1224. document.body.focus();
  1225. document.onselectstart = function () {
  1226. return false;
  1227. };
  1228. }
  1229. /**
  1230. * Turn off text selection blocking.
  1231. */
  1232. function unblockTextSelection() {
  1233. document.onselectstart = function () {
  1234. return true;
  1235. };
  1236. }
  1237. /**
  1238. * Identical to the native `getBoundingClientRect` function, but ensures that
  1239. * the method is supported at all (it is in all browsers we claim to support)
  1240. * and that the element is in the DOM before continuing.
  1241. *
  1242. * This wrapper function also shims properties which are not provided by some
  1243. * older browsers (namely, IE8).
  1244. *
  1245. * Additionally, some browsers do not support adding properties to a
  1246. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1247. * properties (except `x` and `y` which are not widely supported). This helps
  1248. * avoid implementations where keys are non-enumerable.
  1249. *
  1250. * @param {Element} el
  1251. * Element whose `ClientRect` we want to calculate.
  1252. *
  1253. * @return {Object|undefined}
  1254. * Always returns a plain object - or `undefined` if it cannot.
  1255. */
  1256. function getBoundingClientRect(el) {
  1257. if (el && el.getBoundingClientRect && el.parentNode) {
  1258. const rect = el.getBoundingClientRect();
  1259. const result = {};
  1260. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1261. if (rect[k] !== undefined) {
  1262. result[k] = rect[k];
  1263. }
  1264. });
  1265. if (!result.height) {
  1266. result.height = parseFloat(computedStyle(el, 'height'));
  1267. }
  1268. if (!result.width) {
  1269. result.width = parseFloat(computedStyle(el, 'width'));
  1270. }
  1271. return result;
  1272. }
  1273. }
  1274. /**
  1275. * Represents the position of a DOM element on the page.
  1276. *
  1277. * @typedef {Object} module:dom~Position
  1278. *
  1279. * @property {number} left
  1280. * Pixels to the left.
  1281. *
  1282. * @property {number} top
  1283. * Pixels from the top.
  1284. */
  1285. /**
  1286. * Get the position of an element in the DOM.
  1287. *
  1288. * Uses `getBoundingClientRect` technique from John Resig.
  1289. *
  1290. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1291. *
  1292. * @param {Element} el
  1293. * Element from which to get offset.
  1294. *
  1295. * @return {module:dom~Position}
  1296. * The position of the element that was passed in.
  1297. */
  1298. function findPosition(el) {
  1299. if (!el || el && !el.offsetParent) {
  1300. return {
  1301. left: 0,
  1302. top: 0,
  1303. width: 0,
  1304. height: 0
  1305. };
  1306. }
  1307. const width = el.offsetWidth;
  1308. const height = el.offsetHeight;
  1309. let left = 0;
  1310. let top = 0;
  1311. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1312. left += el.offsetLeft;
  1313. top += el.offsetTop;
  1314. el = el.offsetParent;
  1315. }
  1316. return {
  1317. left,
  1318. top,
  1319. width,
  1320. height
  1321. };
  1322. }
  1323. /**
  1324. * Represents x and y coordinates for a DOM element or mouse pointer.
  1325. *
  1326. * @typedef {Object} module:dom~Coordinates
  1327. *
  1328. * @property {number} x
  1329. * x coordinate in pixels
  1330. *
  1331. * @property {number} y
  1332. * y coordinate in pixels
  1333. */
  1334. /**
  1335. * Get the pointer position within an element.
  1336. *
  1337. * The base on the coordinates are the bottom left of the element.
  1338. *
  1339. * @param {Element} el
  1340. * Element on which to get the pointer position on.
  1341. *
  1342. * @param {Event} event
  1343. * Event object.
  1344. *
  1345. * @return {module:dom~Coordinates}
  1346. * A coordinates object corresponding to the mouse position.
  1347. *
  1348. */
  1349. function getPointerPosition(el, event) {
  1350. const translated = {
  1351. x: 0,
  1352. y: 0
  1353. };
  1354. if (IS_IOS) {
  1355. let item = el;
  1356. while (item && item.nodeName.toLowerCase() !== 'html') {
  1357. const transform = computedStyle(item, 'transform');
  1358. if (/^matrix/.test(transform)) {
  1359. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1360. translated.x += values[4];
  1361. translated.y += values[5];
  1362. } else if (/^matrix3d/.test(transform)) {
  1363. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1364. translated.x += values[12];
  1365. translated.y += values[13];
  1366. }
  1367. if (item.assignedSlot && item.assignedSlot.parentElement && window.WebKitCSSMatrix) {
  1368. const transformValue = window.getComputedStyle(item.assignedSlot.parentElement).transform;
  1369. const matrix = new window.WebKitCSSMatrix(transformValue);
  1370. translated.x += matrix.m41;
  1371. translated.y += matrix.m42;
  1372. }
  1373. item = item.parentNode || item.host;
  1374. }
  1375. }
  1376. const position = {};
  1377. const boxTarget = findPosition(event.target);
  1378. const box = findPosition(el);
  1379. const boxW = box.width;
  1380. const boxH = box.height;
  1381. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1382. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1383. if (event.changedTouches) {
  1384. offsetX = event.changedTouches[0].pageX - box.left;
  1385. offsetY = event.changedTouches[0].pageY + box.top;
  1386. if (IS_IOS) {
  1387. offsetX -= translated.x;
  1388. offsetY -= translated.y;
  1389. }
  1390. }
  1391. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1392. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1393. return position;
  1394. }
  1395. /**
  1396. * Determines, via duck typing, whether or not a value is a text node.
  1397. *
  1398. * @param {*} value
  1399. * Check if this value is a text node.
  1400. *
  1401. * @return {boolean}
  1402. * Will be `true` if the value is a text node, `false` otherwise.
  1403. */
  1404. function isTextNode(value) {
  1405. return isObject(value) && value.nodeType === 3;
  1406. }
  1407. /**
  1408. * Empties the contents of an element.
  1409. *
  1410. * @param {Element} el
  1411. * The element to empty children from
  1412. *
  1413. * @return {Element}
  1414. * The element with no children
  1415. */
  1416. function emptyEl(el) {
  1417. while (el.firstChild) {
  1418. el.removeChild(el.firstChild);
  1419. }
  1420. return el;
  1421. }
  1422. /**
  1423. * This is a mixed value that describes content to be injected into the DOM
  1424. * via some method. It can be of the following types:
  1425. *
  1426. * Type | Description
  1427. * -----------|-------------
  1428. * `string` | The value will be normalized into a text node.
  1429. * `Element` | The value will be accepted as-is.
  1430. * `Text` | A TextNode. The value will be accepted as-is.
  1431. * `Array` | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored).
  1432. * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.
  1433. *
  1434. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1435. */
  1436. /**
  1437. * Normalizes content for eventual insertion into the DOM.
  1438. *
  1439. * This allows a wide range of content definition methods, but helps protect
  1440. * from falling into the trap of simply writing to `innerHTML`, which could
  1441. * be an XSS concern.
  1442. *
  1443. * The content for an element can be passed in multiple types and
  1444. * combinations, whose behavior is as follows:
  1445. *
  1446. * @param {ContentDescriptor} content
  1447. * A content descriptor value.
  1448. *
  1449. * @return {Array}
  1450. * All of the content that was passed in, normalized to an array of
  1451. * elements or text nodes.
  1452. */
  1453. function normalizeContent(content) {
  1454. // First, invoke content if it is a function. If it produces an array,
  1455. // that needs to happen before normalization.
  1456. if (typeof content === 'function') {
  1457. content = content();
  1458. }
  1459. // Next up, normalize to an array, so one or many items can be normalized,
  1460. // filtered, and returned.
  1461. return (Array.isArray(content) ? content : [content]).map(value => {
  1462. // First, invoke value if it is a function to produce a new value,
  1463. // which will be subsequently normalized to a Node of some kind.
  1464. if (typeof value === 'function') {
  1465. value = value();
  1466. }
  1467. if (isEl(value) || isTextNode(value)) {
  1468. return value;
  1469. }
  1470. if (typeof value === 'string' && /\S/.test(value)) {
  1471. return document.createTextNode(value);
  1472. }
  1473. }).filter(value => value);
  1474. }
  1475. /**
  1476. * Normalizes and appends content to an element.
  1477. *
  1478. * @param {Element} el
  1479. * Element to append normalized content to.
  1480. *
  1481. * @param {ContentDescriptor} content
  1482. * A content descriptor value.
  1483. *
  1484. * @return {Element}
  1485. * The element with appended normalized content.
  1486. */
  1487. function appendContent(el, content) {
  1488. normalizeContent(content).forEach(node => el.appendChild(node));
  1489. return el;
  1490. }
  1491. /**
  1492. * Normalizes and inserts content into an element; this is identical to
  1493. * `appendContent()`, except it empties the element first.
  1494. *
  1495. * @param {Element} el
  1496. * Element to insert normalized content into.
  1497. *
  1498. * @param {ContentDescriptor} content
  1499. * A content descriptor value.
  1500. *
  1501. * @return {Element}
  1502. * The element with inserted normalized content.
  1503. */
  1504. function insertContent(el, content) {
  1505. return appendContent(emptyEl(el), content);
  1506. }
  1507. /**
  1508. * Check if an event was a single left click.
  1509. *
  1510. * @param {MouseEvent} event
  1511. * Event object.
  1512. *
  1513. * @return {boolean}
  1514. * Will be `true` if a single left click, `false` otherwise.
  1515. */
  1516. function isSingleLeftClick(event) {
  1517. // Note: if you create something draggable, be sure to
  1518. // call it on both `mousedown` and `mousemove` event,
  1519. // otherwise `mousedown` should be enough for a button
  1520. if (event.button === undefined && event.buttons === undefined) {
  1521. // Why do we need `buttons` ?
  1522. // Because, middle mouse sometimes have this:
  1523. // e.button === 0 and e.buttons === 4
  1524. // Furthermore, we want to prevent combination click, something like
  1525. // HOLD middlemouse then left click, that would be
  1526. // e.button === 0, e.buttons === 5
  1527. // just `button` is not gonna work
  1528. // Alright, then what this block does ?
  1529. // this is for chrome `simulate mobile devices`
  1530. // I want to support this as well
  1531. return true;
  1532. }
  1533. if (event.button === 0 && event.buttons === undefined) {
  1534. // Touch screen, sometimes on some specific device, `buttons`
  1535. // doesn't have anything (safari on ios, blackberry...)
  1536. return true;
  1537. }
  1538. // `mouseup` event on a single left click has
  1539. // `button` and `buttons` equal to 0
  1540. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1541. return true;
  1542. }
  1543. // MacOS Sonoma trackpad when "tap to click enabled"
  1544. if (event.type === 'mousedown' && event.button === 0 && event.buttons === 0) {
  1545. return true;
  1546. }
  1547. if (event.button !== 0 || event.buttons !== 1) {
  1548. // This is the reason we have those if else block above
  1549. // if any special case we can catch and let it slide
  1550. // we do it above, when get to here, this definitely
  1551. // is-not-left-click
  1552. return false;
  1553. }
  1554. return true;
  1555. }
  1556. /**
  1557. * Finds a single DOM element matching `selector` within the optional
  1558. * `context` of another DOM element (defaulting to `document`).
  1559. *
  1560. * @param {string} selector
  1561. * A valid CSS selector, which will be passed to `querySelector`.
  1562. *
  1563. * @param {Element|String} [context=document]
  1564. * A DOM element within which to query. Can also be a selector
  1565. * string in which case the first matching element will be used
  1566. * as context. If missing (or no element matches selector), falls
  1567. * back to `document`.
  1568. *
  1569. * @return {Element|null}
  1570. * The element that was found or null.
  1571. */
  1572. const $ = createQuerier('querySelector');
  1573. /**
  1574. * Finds a all DOM elements matching `selector` within the optional
  1575. * `context` of another DOM element (defaulting to `document`).
  1576. *
  1577. * @param {string} selector
  1578. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1579. *
  1580. * @param {Element|String} [context=document]
  1581. * A DOM element within which to query. Can also be a selector
  1582. * string in which case the first matching element will be used
  1583. * as context. If missing (or no element matches selector), falls
  1584. * back to `document`.
  1585. *
  1586. * @return {NodeList}
  1587. * A element list of elements that were found. Will be empty if none
  1588. * were found.
  1589. *
  1590. */
  1591. const $$ = createQuerier('querySelectorAll');
  1592. /**
  1593. * A safe getComputedStyle.
  1594. *
  1595. * This is needed because in Firefox, if the player is loaded in an iframe with
  1596. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1597. * null-check to make sure that the player doesn't break in these cases.
  1598. *
  1599. * @param {Element} el
  1600. * The element you want the computed style of
  1601. *
  1602. * @param {string} prop
  1603. * The property name you want
  1604. *
  1605. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1606. */
  1607. function computedStyle(el, prop) {
  1608. if (!el || !prop) {
  1609. return '';
  1610. }
  1611. if (typeof window.getComputedStyle === 'function') {
  1612. let computedStyleValue;
  1613. try {
  1614. computedStyleValue = window.getComputedStyle(el);
  1615. } catch (e) {
  1616. return '';
  1617. }
  1618. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1619. }
  1620. return '';
  1621. }
  1622. /**
  1623. * Copy document style sheets to another window.
  1624. *
  1625. * @param {Window} win
  1626. * The window element you want to copy the document style sheets to.
  1627. *
  1628. */
  1629. function copyStyleSheetsToWindow(win) {
  1630. [...document.styleSheets].forEach(styleSheet => {
  1631. try {
  1632. const cssRules = [...styleSheet.cssRules].map(rule => rule.cssText).join('');
  1633. const style = document.createElement('style');
  1634. style.textContent = cssRules;
  1635. win.document.head.appendChild(style);
  1636. } catch (e) {
  1637. const link = document.createElement('link');
  1638. link.rel = 'stylesheet';
  1639. link.type = styleSheet.type;
  1640. // For older Safari this has to be the string; on other browsers setting the MediaList works
  1641. link.media = styleSheet.media.mediaText;
  1642. link.href = styleSheet.href;
  1643. win.document.head.appendChild(link);
  1644. }
  1645. });
  1646. }
  1647. var Dom = /*#__PURE__*/Object.freeze({
  1648. __proto__: null,
  1649. isReal: isReal,
  1650. isEl: isEl,
  1651. isInFrame: isInFrame,
  1652. createEl: createEl,
  1653. textContent: textContent,
  1654. prependTo: prependTo,
  1655. hasClass: hasClass,
  1656. addClass: addClass,
  1657. removeClass: removeClass,
  1658. toggleClass: toggleClass,
  1659. setAttributes: setAttributes,
  1660. getAttributes: getAttributes,
  1661. getAttribute: getAttribute,
  1662. setAttribute: setAttribute,
  1663. removeAttribute: removeAttribute,
  1664. blockTextSelection: blockTextSelection,
  1665. unblockTextSelection: unblockTextSelection,
  1666. getBoundingClientRect: getBoundingClientRect,
  1667. findPosition: findPosition,
  1668. getPointerPosition: getPointerPosition,
  1669. isTextNode: isTextNode,
  1670. emptyEl: emptyEl,
  1671. normalizeContent: normalizeContent,
  1672. appendContent: appendContent,
  1673. insertContent: insertContent,
  1674. isSingleLeftClick: isSingleLeftClick,
  1675. $: $,
  1676. $$: $$,
  1677. computedStyle: computedStyle,
  1678. copyStyleSheetsToWindow: copyStyleSheetsToWindow
  1679. });
  1680. /**
  1681. * @file setup.js - Functions for setting up a player without
  1682. * user interaction based on the data-setup `attribute` of the video tag.
  1683. *
  1684. * @module setup
  1685. */
  1686. let _windowLoaded = false;
  1687. let videojs$1;
  1688. /**
  1689. * Set up any tags that have a data-setup `attribute` when the player is started.
  1690. */
  1691. const autoSetup = function () {
  1692. if (videojs$1.options.autoSetup === false) {
  1693. return;
  1694. }
  1695. const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1696. const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1697. const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1698. const mediaEls = vids.concat(audios, divs);
  1699. // Check if any media elements exist
  1700. if (mediaEls && mediaEls.length > 0) {
  1701. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1702. const mediaEl = mediaEls[i];
  1703. // Check if element exists, has getAttribute func.
  1704. if (mediaEl && mediaEl.getAttribute) {
  1705. // Make sure this player hasn't already been set up.
  1706. if (mediaEl.player === undefined) {
  1707. const options = mediaEl.getAttribute('data-setup');
  1708. // Check if data-setup attr exists.
  1709. // We only auto-setup if they've added the data-setup attr.
  1710. if (options !== null) {
  1711. // Create new video.js instance.
  1712. videojs$1(mediaEl);
  1713. }
  1714. }
  1715. // If getAttribute isn't defined, we need to wait for the DOM.
  1716. } else {
  1717. autoSetupTimeout(1);
  1718. break;
  1719. }
  1720. }
  1721. // No videos were found, so keep looping unless page is finished loading.
  1722. } else if (!_windowLoaded) {
  1723. autoSetupTimeout(1);
  1724. }
  1725. };
  1726. /**
  1727. * Wait until the page is loaded before running autoSetup. This will be called in
  1728. * autoSetup if `hasLoaded` returns false.
  1729. *
  1730. * @param {number} wait
  1731. * How long to wait in ms
  1732. *
  1733. * @param {module:videojs} [vjs]
  1734. * The videojs library function
  1735. */
  1736. function autoSetupTimeout(wait, vjs) {
  1737. // Protect against breakage in non-browser environments
  1738. if (!isReal()) {
  1739. return;
  1740. }
  1741. if (vjs) {
  1742. videojs$1 = vjs;
  1743. }
  1744. window.setTimeout(autoSetup, wait);
  1745. }
  1746. /**
  1747. * Used to set the internal tracking of window loaded state to true.
  1748. *
  1749. * @private
  1750. */
  1751. function setWindowLoaded() {
  1752. _windowLoaded = true;
  1753. window.removeEventListener('load', setWindowLoaded);
  1754. }
  1755. if (isReal()) {
  1756. if (document.readyState === 'complete') {
  1757. setWindowLoaded();
  1758. } else {
  1759. /**
  1760. * Listen for the load event on window, and set _windowLoaded to true.
  1761. *
  1762. * We use a standard event listener here to avoid incrementing the GUID
  1763. * before any players are created.
  1764. *
  1765. * @listens load
  1766. */
  1767. window.addEventListener('load', setWindowLoaded);
  1768. }
  1769. }
  1770. /**
  1771. * @file stylesheet.js
  1772. * @module stylesheet
  1773. */
  1774. /**
  1775. * Create a DOM style element given a className for it.
  1776. *
  1777. * @param {string} className
  1778. * The className to add to the created style element.
  1779. *
  1780. * @return {Element}
  1781. * The element that was created.
  1782. */
  1783. const createStyleElement = function (className) {
  1784. const style = document.createElement('style');
  1785. style.className = className;
  1786. return style;
  1787. };
  1788. /**
  1789. * Add text to a DOM element.
  1790. *
  1791. * @param {Element} el
  1792. * The Element to add text content to.
  1793. *
  1794. * @param {string} content
  1795. * The text to add to the element.
  1796. */
  1797. const setTextContent = function (el, content) {
  1798. if (el.styleSheet) {
  1799. el.styleSheet.cssText = content;
  1800. } else {
  1801. el.textContent = content;
  1802. }
  1803. };
  1804. /**
  1805. * @file dom-data.js
  1806. * @module dom-data
  1807. */
  1808. /**
  1809. * Element Data Store.
  1810. *
  1811. * Allows for binding data to an element without putting it directly on the
  1812. * element. Ex. Event listeners are stored here.
  1813. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1814. *
  1815. * @type {Object}
  1816. * @private
  1817. */
  1818. var DomData = new WeakMap();
  1819. /**
  1820. * @file guid.js
  1821. * @module guid
  1822. */
  1823. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1824. //
  1825. // The initial GUID is 3 because some users have come to rely on the first
  1826. // default player ID ending up as `vjs_video_3`.
  1827. //
  1828. // See: https://github.com/videojs/video.js/pull/6216
  1829. const _initialGuid = 3;
  1830. /**
  1831. * Unique ID for an element or function
  1832. *
  1833. * @type {Number}
  1834. */
  1835. let _guid = _initialGuid;
  1836. /**
  1837. * Get a unique auto-incrementing ID by number that has not been returned before.
  1838. *
  1839. * @return {number}
  1840. * A new unique ID.
  1841. */
  1842. function newGUID() {
  1843. return _guid++;
  1844. }
  1845. /**
  1846. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1847. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1848. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1849. * robust as jquery's, so there's probably some differences.
  1850. *
  1851. * @file events.js
  1852. * @module events
  1853. */
  1854. /**
  1855. * Clean up the listener cache and dispatchers
  1856. *
  1857. * @param {Element|Object} elem
  1858. * Element to clean up
  1859. *
  1860. * @param {string} type
  1861. * Type of event to clean up
  1862. */
  1863. function _cleanUpEvents(elem, type) {
  1864. if (!DomData.has(elem)) {
  1865. return;
  1866. }
  1867. const data = DomData.get(elem);
  1868. // Remove the events of a particular type if there are none left
  1869. if (data.handlers[type].length === 0) {
  1870. delete data.handlers[type];
  1871. // data.handlers[type] = null;
  1872. // Setting to null was causing an error with data.handlers
  1873. // Remove the meta-handler from the element
  1874. if (elem.removeEventListener) {
  1875. elem.removeEventListener(type, data.dispatcher, false);
  1876. } else if (elem.detachEvent) {
  1877. elem.detachEvent('on' + type, data.dispatcher);
  1878. }
  1879. }
  1880. // Remove the events object if there are no types left
  1881. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1882. delete data.handlers;
  1883. delete data.dispatcher;
  1884. delete data.disabled;
  1885. }
  1886. // Finally remove the element data if there is no data left
  1887. if (Object.getOwnPropertyNames(data).length === 0) {
  1888. DomData.delete(elem);
  1889. }
  1890. }
  1891. /**
  1892. * Loops through an array of event types and calls the requested method for each type.
  1893. *
  1894. * @param {Function} fn
  1895. * The event method we want to use.
  1896. *
  1897. * @param {Element|Object} elem
  1898. * Element or object to bind listeners to
  1899. *
  1900. * @param {string[]} types
  1901. * Type of event to bind to.
  1902. *
  1903. * @param {Function} callback
  1904. * Event listener.
  1905. */
  1906. function _handleMultipleEvents(fn, elem, types, callback) {
  1907. types.forEach(function (type) {
  1908. // Call the event method for each one of the types
  1909. fn(elem, type, callback);
  1910. });
  1911. }
  1912. /**
  1913. * Fix a native event to have standard property values
  1914. *
  1915. * @param {Object} event
  1916. * Event object to fix.
  1917. *
  1918. * @return {Object}
  1919. * Fixed event object.
  1920. */
  1921. function fixEvent(event) {
  1922. if (event.fixed_) {
  1923. return event;
  1924. }
  1925. function returnTrue() {
  1926. return true;
  1927. }
  1928. function returnFalse() {
  1929. return false;
  1930. }
  1931. // Test if fixing up is needed
  1932. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1933. // But native events return true for stopPropagation, but don't have
  1934. // other expected methods like isPropagationStopped. Seems to be a problem
  1935. // with the Javascript Ninja code. So we're just overriding all events now.
  1936. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1937. const old = event || window.event;
  1938. event = {};
  1939. // Clone the old object so that we can modify the values event = {};
  1940. // IE8 Doesn't like when you mess with native event properties
  1941. // Firefox returns false for event.hasOwnProperty('type') and other props
  1942. // which makes copying more difficult.
  1943. // TODO: Probably best to create an allowlist of event props
  1944. const deprecatedProps = ['layerX', 'layerY', 'keyLocation', 'path', 'webkitMovementX', 'webkitMovementY', 'mozPressure', 'mozInputSource'];
  1945. for (const key in old) {
  1946. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1947. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1948. // and webkitMovementX/Y
  1949. // Lighthouse complains if Event.path is copied
  1950. if (!deprecatedProps.includes(key)) {
  1951. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1952. // we still want to if preventDefault isn't supported (IE8).
  1953. if (!(key === 'returnValue' && old.preventDefault)) {
  1954. event[key] = old[key];
  1955. }
  1956. }
  1957. }
  1958. // The event occurred on this element
  1959. if (!event.target) {
  1960. event.target = event.srcElement || document;
  1961. }
  1962. // Handle which other element the event is related to
  1963. if (!event.relatedTarget) {
  1964. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1965. }
  1966. // Stop the default browser action
  1967. event.preventDefault = function () {
  1968. if (old.preventDefault) {
  1969. old.preventDefault();
  1970. }
  1971. event.returnValue = false;
  1972. old.returnValue = false;
  1973. event.defaultPrevented = true;
  1974. };
  1975. event.defaultPrevented = false;
  1976. // Stop the event from bubbling
  1977. event.stopPropagation = function () {
  1978. if (old.stopPropagation) {
  1979. old.stopPropagation();
  1980. }
  1981. event.cancelBubble = true;
  1982. old.cancelBubble = true;
  1983. event.isPropagationStopped = returnTrue;
  1984. };
  1985. event.isPropagationStopped = returnFalse;
  1986. // Stop the event from bubbling and executing other handlers
  1987. event.stopImmediatePropagation = function () {
  1988. if (old.stopImmediatePropagation) {
  1989. old.stopImmediatePropagation();
  1990. }
  1991. event.isImmediatePropagationStopped = returnTrue;
  1992. event.stopPropagation();
  1993. };
  1994. event.isImmediatePropagationStopped = returnFalse;
  1995. // Handle mouse position
  1996. if (event.clientX !== null && event.clientX !== undefined) {
  1997. const doc = document.documentElement;
  1998. const body = document.body;
  1999. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  2000. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  2001. }
  2002. // Handle key presses
  2003. event.which = event.charCode || event.keyCode;
  2004. // Fix button for mouse clicks:
  2005. // 0 == left; 1 == middle; 2 == right
  2006. if (event.button !== null && event.button !== undefined) {
  2007. // The following is disabled because it does not pass videojs-standard
  2008. // and... yikes.
  2009. /* eslint-disable */
  2010. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  2011. /* eslint-enable */
  2012. }
  2013. }
  2014. event.fixed_ = true;
  2015. // Returns fixed-up instance
  2016. return event;
  2017. }
  2018. /**
  2019. * Whether passive event listeners are supported
  2020. */
  2021. let _supportsPassive;
  2022. const supportsPassive = function () {
  2023. if (typeof _supportsPassive !== 'boolean') {
  2024. _supportsPassive = false;
  2025. try {
  2026. const opts = Object.defineProperty({}, 'passive', {
  2027. get() {
  2028. _supportsPassive = true;
  2029. }
  2030. });
  2031. window.addEventListener('test', null, opts);
  2032. window.removeEventListener('test', null, opts);
  2033. } catch (e) {
  2034. // disregard
  2035. }
  2036. }
  2037. return _supportsPassive;
  2038. };
  2039. /**
  2040. * Touch events Chrome expects to be passive
  2041. */
  2042. const passiveEvents = ['touchstart', 'touchmove'];
  2043. /**
  2044. * Add an event listener to element
  2045. * It stores the handler function in a separate cache object
  2046. * and adds a generic handler to the element's event,
  2047. * along with a unique id (guid) to the element.
  2048. *
  2049. * @param {Element|Object} elem
  2050. * Element or object to bind listeners to
  2051. *
  2052. * @param {string|string[]} type
  2053. * Type of event to bind to.
  2054. *
  2055. * @param {Function} fn
  2056. * Event listener.
  2057. */
  2058. function on(elem, type, fn) {
  2059. if (Array.isArray(type)) {
  2060. return _handleMultipleEvents(on, elem, type, fn);
  2061. }
  2062. if (!DomData.has(elem)) {
  2063. DomData.set(elem, {});
  2064. }
  2065. const data = DomData.get(elem);
  2066. // We need a place to store all our handler data
  2067. if (!data.handlers) {
  2068. data.handlers = {};
  2069. }
  2070. if (!data.handlers[type]) {
  2071. data.handlers[type] = [];
  2072. }
  2073. if (!fn.guid) {
  2074. fn.guid = newGUID();
  2075. }
  2076. data.handlers[type].push(fn);
  2077. if (!data.dispatcher) {
  2078. data.disabled = false;
  2079. data.dispatcher = function (event, hash) {
  2080. if (data.disabled) {
  2081. return;
  2082. }
  2083. event = fixEvent(event);
  2084. const handlers = data.handlers[event.type];
  2085. if (handlers) {
  2086. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  2087. const handlersCopy = handlers.slice(0);
  2088. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  2089. if (event.isImmediatePropagationStopped()) {
  2090. break;
  2091. } else {
  2092. try {
  2093. handlersCopy[m].call(elem, event, hash);
  2094. } catch (e) {
  2095. log.error(e);
  2096. }
  2097. }
  2098. }
  2099. }
  2100. };
  2101. }
  2102. if (data.handlers[type].length === 1) {
  2103. if (elem.addEventListener) {
  2104. let options = false;
  2105. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  2106. options = {
  2107. passive: true
  2108. };
  2109. }
  2110. elem.addEventListener(type, data.dispatcher, options);
  2111. } else if (elem.attachEvent) {
  2112. elem.attachEvent('on' + type, data.dispatcher);
  2113. }
  2114. }
  2115. }
  2116. /**
  2117. * Removes event listeners from an element
  2118. *
  2119. * @param {Element|Object} elem
  2120. * Object to remove listeners from.
  2121. *
  2122. * @param {string|string[]} [type]
  2123. * Type of listener to remove. Don't include to remove all events from element.
  2124. *
  2125. * @param {Function} [fn]
  2126. * Specific listener to remove. Don't include to remove listeners for an event
  2127. * type.
  2128. */
  2129. function off(elem, type, fn) {
  2130. // Don't want to add a cache object through getElData if not needed
  2131. if (!DomData.has(elem)) {
  2132. return;
  2133. }
  2134. const data = DomData.get(elem);
  2135. // If no events exist, nothing to unbind
  2136. if (!data.handlers) {
  2137. return;
  2138. }
  2139. if (Array.isArray(type)) {
  2140. return _handleMultipleEvents(off, elem, type, fn);
  2141. }
  2142. // Utility function
  2143. const removeType = function (el, t) {
  2144. data.handlers[t] = [];
  2145. _cleanUpEvents(el, t);
  2146. };
  2147. // Are we removing all bound events?
  2148. if (type === undefined) {
  2149. for (const t in data.handlers) {
  2150. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2151. removeType(elem, t);
  2152. }
  2153. }
  2154. return;
  2155. }
  2156. const handlers = data.handlers[type];
  2157. // If no handlers exist, nothing to unbind
  2158. if (!handlers) {
  2159. return;
  2160. }
  2161. // If no listener was provided, remove all listeners for type
  2162. if (!fn) {
  2163. removeType(elem, type);
  2164. return;
  2165. }
  2166. // We're only removing a single handler
  2167. if (fn.guid) {
  2168. for (let n = 0; n < handlers.length; n++) {
  2169. if (handlers[n].guid === fn.guid) {
  2170. handlers.splice(n--, 1);
  2171. }
  2172. }
  2173. }
  2174. _cleanUpEvents(elem, type);
  2175. }
  2176. /**
  2177. * Trigger an event for an element
  2178. *
  2179. * @param {Element|Object} elem
  2180. * Element to trigger an event on
  2181. *
  2182. * @param {EventTarget~Event|string} event
  2183. * A string (the type) or an event object with a type attribute
  2184. *
  2185. * @param {Object} [hash]
  2186. * data hash to pass along with the event
  2187. *
  2188. * @return {boolean|undefined}
  2189. * Returns the opposite of `defaultPrevented` if default was
  2190. * prevented. Otherwise, returns `undefined`
  2191. */
  2192. function trigger(elem, event, hash) {
  2193. // Fetches element data and a reference to the parent (for bubbling).
  2194. // Don't want to add a data object to cache for every parent,
  2195. // so checking hasElData first.
  2196. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2197. const parent = elem.parentNode || elem.ownerDocument;
  2198. // type = event.type || event,
  2199. // handler;
  2200. // If an event name was passed as a string, creates an event out of it
  2201. if (typeof event === 'string') {
  2202. event = {
  2203. type: event,
  2204. target: elem
  2205. };
  2206. } else if (!event.target) {
  2207. event.target = elem;
  2208. }
  2209. // Normalizes the event properties.
  2210. event = fixEvent(event);
  2211. // If the passed element has a dispatcher, executes the established handlers.
  2212. if (elemData.dispatcher) {
  2213. elemData.dispatcher.call(elem, event, hash);
  2214. }
  2215. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2216. // recursively calls this function to bubble the event up the DOM.
  2217. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2218. trigger.call(null, parent, event, hash);
  2219. // If at the top of the DOM, triggers the default action unless disabled.
  2220. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2221. if (!DomData.has(event.target)) {
  2222. DomData.set(event.target, {});
  2223. }
  2224. const targetData = DomData.get(event.target);
  2225. // Checks if the target has a default action for this event.
  2226. if (event.target[event.type]) {
  2227. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2228. targetData.disabled = true;
  2229. // Executes the default action.
  2230. if (typeof event.target[event.type] === 'function') {
  2231. event.target[event.type]();
  2232. }
  2233. // Re-enables event dispatching.
  2234. targetData.disabled = false;
  2235. }
  2236. }
  2237. // Inform the triggerer if the default was prevented by returning false
  2238. return !event.defaultPrevented;
  2239. }
  2240. /**
  2241. * Trigger a listener only once for an event.
  2242. *
  2243. * @param {Element|Object} elem
  2244. * Element or object to bind to.
  2245. *
  2246. * @param {string|string[]} type
  2247. * Name/type of event
  2248. *
  2249. * @param {Event~EventListener} fn
  2250. * Event listener function
  2251. */
  2252. function one(elem, type, fn) {
  2253. if (Array.isArray(type)) {
  2254. return _handleMultipleEvents(one, elem, type, fn);
  2255. }
  2256. const func = function () {
  2257. off(elem, type, func);
  2258. fn.apply(this, arguments);
  2259. };
  2260. // copy the guid to the new function so it can removed using the original function's ID
  2261. func.guid = fn.guid = fn.guid || newGUID();
  2262. on(elem, type, func);
  2263. }
  2264. /**
  2265. * Trigger a listener only once and then turn if off for all
  2266. * configured events
  2267. *
  2268. * @param {Element|Object} elem
  2269. * Element or object to bind to.
  2270. *
  2271. * @param {string|string[]} type
  2272. * Name/type of event
  2273. *
  2274. * @param {Event~EventListener} fn
  2275. * Event listener function
  2276. */
  2277. function any(elem, type, fn) {
  2278. const func = function () {
  2279. off(elem, type, func);
  2280. fn.apply(this, arguments);
  2281. };
  2282. // copy the guid to the new function so it can removed using the original function's ID
  2283. func.guid = fn.guid = fn.guid || newGUID();
  2284. // multiple ons, but one off for everything
  2285. on(elem, type, func);
  2286. }
  2287. var Events = /*#__PURE__*/Object.freeze({
  2288. __proto__: null,
  2289. fixEvent: fixEvent,
  2290. on: on,
  2291. off: off,
  2292. trigger: trigger,
  2293. one: one,
  2294. any: any
  2295. });
  2296. /**
  2297. * @file fn.js
  2298. * @module fn
  2299. */
  2300. const UPDATE_REFRESH_INTERVAL = 30;
  2301. /**
  2302. * A private, internal-only function for changing the context of a function.
  2303. *
  2304. * It also stores a unique id on the function so it can be easily removed from
  2305. * events.
  2306. *
  2307. * @private
  2308. * @function
  2309. * @param {*} context
  2310. * The object to bind as scope.
  2311. *
  2312. * @param {Function} fn
  2313. * The function to be bound to a scope.
  2314. *
  2315. * @param {number} [uid]
  2316. * An optional unique ID for the function to be set
  2317. *
  2318. * @return {Function}
  2319. * The new function that will be bound into the context given
  2320. */
  2321. const bind_ = function (context, fn, uid) {
  2322. // Make sure the function has a unique ID
  2323. if (!fn.guid) {
  2324. fn.guid = newGUID();
  2325. }
  2326. // Create the new function that changes the context
  2327. const bound = fn.bind(context);
  2328. // Allow for the ability to individualize this function
  2329. // Needed in the case where multiple objects might share the same prototype
  2330. // IF both items add an event listener with the same function, then you try to remove just one
  2331. // it will remove both because they both have the same guid.
  2332. // when using this, you need to use the bind method when you remove the listener as well.
  2333. // currently used in text tracks
  2334. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2335. return bound;
  2336. };
  2337. /**
  2338. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2339. * at most once per every `wait` milliseconds.
  2340. *
  2341. * @function
  2342. * @param {Function} fn
  2343. * The function to be throttled.
  2344. *
  2345. * @param {number} wait
  2346. * The number of milliseconds by which to throttle.
  2347. *
  2348. * @return {Function}
  2349. */
  2350. const throttle = function (fn, wait) {
  2351. let last = window.performance.now();
  2352. const throttled = function (...args) {
  2353. const now = window.performance.now();
  2354. if (now - last >= wait) {
  2355. fn(...args);
  2356. last = now;
  2357. }
  2358. };
  2359. return throttled;
  2360. };
  2361. /**
  2362. * Creates a debounced function that delays invoking `func` until after `wait`
  2363. * milliseconds have elapsed since the last time the debounced function was
  2364. * invoked.
  2365. *
  2366. * Inspired by lodash and underscore implementations.
  2367. *
  2368. * @function
  2369. * @param {Function} func
  2370. * The function to wrap with debounce behavior.
  2371. *
  2372. * @param {number} wait
  2373. * The number of milliseconds to wait after the last invocation.
  2374. *
  2375. * @param {boolean} [immediate]
  2376. * Whether or not to invoke the function immediately upon creation.
  2377. *
  2378. * @param {Object} [context=window]
  2379. * The "context" in which the debounced function should debounce. For
  2380. * example, if this function should be tied to a Video.js player,
  2381. * the player can be passed here. Alternatively, defaults to the
  2382. * global `window` object.
  2383. *
  2384. * @return {Function}
  2385. * A debounced function.
  2386. */
  2387. const debounce = function (func, wait, immediate, context = window) {
  2388. let timeout;
  2389. const cancel = () => {
  2390. context.clearTimeout(timeout);
  2391. timeout = null;
  2392. };
  2393. /* eslint-disable consistent-this */
  2394. const debounced = function () {
  2395. const self = this;
  2396. const args = arguments;
  2397. let later = function () {
  2398. timeout = null;
  2399. later = null;
  2400. if (!immediate) {
  2401. func.apply(self, args);
  2402. }
  2403. };
  2404. if (!timeout && immediate) {
  2405. func.apply(self, args);
  2406. }
  2407. context.clearTimeout(timeout);
  2408. timeout = context.setTimeout(later, wait);
  2409. };
  2410. /* eslint-enable consistent-this */
  2411. debounced.cancel = cancel;
  2412. return debounced;
  2413. };
  2414. var Fn = /*#__PURE__*/Object.freeze({
  2415. __proto__: null,
  2416. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2417. bind_: bind_,
  2418. throttle: throttle,
  2419. debounce: debounce
  2420. });
  2421. /**
  2422. * @file src/js/event-target.js
  2423. */
  2424. let EVENT_MAP;
  2425. /**
  2426. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2427. * adds shorthand functions that wrap around lengthy functions. For example:
  2428. * the `on` function is a wrapper around `addEventListener`.
  2429. *
  2430. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2431. * @class EventTarget
  2432. */
  2433. class EventTarget {
  2434. /**
  2435. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2436. * function that will get called when an event with a certain name gets triggered.
  2437. *
  2438. * @param {string|string[]} type
  2439. * An event name or an array of event names.
  2440. *
  2441. * @param {Function} fn
  2442. * The function to call with `EventTarget`s
  2443. */
  2444. on(type, fn) {
  2445. // Remove the addEventListener alias before calling Events.on
  2446. // so we don't get into an infinite type loop
  2447. const ael = this.addEventListener;
  2448. this.addEventListener = () => {};
  2449. on(this, type, fn);
  2450. this.addEventListener = ael;
  2451. }
  2452. /**
  2453. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2454. * This makes it so that the `event listener` will no longer get called when the
  2455. * named event happens.
  2456. *
  2457. * @param {string|string[]} type
  2458. * An event name or an array of event names.
  2459. *
  2460. * @param {Function} fn
  2461. * The function to remove.
  2462. */
  2463. off(type, fn) {
  2464. off(this, type, fn);
  2465. }
  2466. /**
  2467. * This function will add an `event listener` that gets triggered only once. After the
  2468. * first trigger it will get removed. This is like adding an `event listener`
  2469. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2470. *
  2471. * @param {string|string[]} type
  2472. * An event name or an array of event names.
  2473. *
  2474. * @param {Function} fn
  2475. * The function to be called once for each event name.
  2476. */
  2477. one(type, fn) {
  2478. // Remove the addEventListener aliasing Events.on
  2479. // so we don't get into an infinite type loop
  2480. const ael = this.addEventListener;
  2481. this.addEventListener = () => {};
  2482. one(this, type, fn);
  2483. this.addEventListener = ael;
  2484. }
  2485. /**
  2486. * This function will add an `event listener` that gets triggered only once and is
  2487. * removed from all events. This is like adding an array of `event listener`s
  2488. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2489. * first time it is triggered.
  2490. *
  2491. * @param {string|string[]} type
  2492. * An event name or an array of event names.
  2493. *
  2494. * @param {Function} fn
  2495. * The function to be called once for each event name.
  2496. */
  2497. any(type, fn) {
  2498. // Remove the addEventListener aliasing Events.on
  2499. // so we don't get into an infinite type loop
  2500. const ael = this.addEventListener;
  2501. this.addEventListener = () => {};
  2502. any(this, type, fn);
  2503. this.addEventListener = ael;
  2504. }
  2505. /**
  2506. * This function causes an event to happen. This will then cause any `event listeners`
  2507. * that are waiting for that event, to get called. If there are no `event listeners`
  2508. * for an event then nothing will happen.
  2509. *
  2510. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2511. * Trigger will also call the `on` + `uppercaseEventName` function.
  2512. *
  2513. * Example:
  2514. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2515. * `onClick` if it exists.
  2516. *
  2517. * @param {string|EventTarget~Event|Object} event
  2518. * The name of the event, an `Event`, or an object with a key of type set to
  2519. * an event name.
  2520. */
  2521. trigger(event) {
  2522. const type = event.type || event;
  2523. // deprecation
  2524. // In a future version we should default target to `this`
  2525. // similar to how we default the target to `elem` in
  2526. // `Events.trigger`. Right now the default `target` will be
  2527. // `document` due to the `Event.fixEvent` call.
  2528. if (typeof event === 'string') {
  2529. event = {
  2530. type
  2531. };
  2532. }
  2533. event = fixEvent(event);
  2534. if (this.allowedEvents_[type] && this['on' + type]) {
  2535. this['on' + type](event);
  2536. }
  2537. trigger(this, event);
  2538. }
  2539. queueTrigger(event) {
  2540. // only set up EVENT_MAP if it'll be used
  2541. if (!EVENT_MAP) {
  2542. EVENT_MAP = new Map();
  2543. }
  2544. const type = event.type || event;
  2545. let map = EVENT_MAP.get(this);
  2546. if (!map) {
  2547. map = new Map();
  2548. EVENT_MAP.set(this, map);
  2549. }
  2550. const oldTimeout = map.get(type);
  2551. map.delete(type);
  2552. window.clearTimeout(oldTimeout);
  2553. const timeout = window.setTimeout(() => {
  2554. map.delete(type);
  2555. // if we cleared out all timeouts for the current target, delete its map
  2556. if (map.size === 0) {
  2557. map = null;
  2558. EVENT_MAP.delete(this);
  2559. }
  2560. this.trigger(event);
  2561. }, 0);
  2562. map.set(type, timeout);
  2563. }
  2564. }
  2565. /**
  2566. * A Custom DOM event.
  2567. *
  2568. * @typedef {CustomEvent} Event
  2569. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2570. */
  2571. /**
  2572. * All event listeners should follow the following format.
  2573. *
  2574. * @callback EventListener
  2575. * @this {EventTarget}
  2576. *
  2577. * @param {Event} event
  2578. * the event that triggered this function
  2579. *
  2580. * @param {Object} [hash]
  2581. * hash of data sent during the event
  2582. */
  2583. /**
  2584. * An object containing event names as keys and booleans as values.
  2585. *
  2586. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2587. * will have extra functionality. See that function for more information.
  2588. *
  2589. * @property EventTarget.prototype.allowedEvents_
  2590. * @protected
  2591. */
  2592. EventTarget.prototype.allowedEvents_ = {};
  2593. /**
  2594. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2595. * the standard DOM API.
  2596. *
  2597. * @function
  2598. * @see {@link EventTarget#on}
  2599. */
  2600. EventTarget.prototype.addEventListener = EventTarget.prototype.on;
  2601. /**
  2602. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2603. * the standard DOM API.
  2604. *
  2605. * @function
  2606. * @see {@link EventTarget#off}
  2607. */
  2608. EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
  2609. /**
  2610. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2611. * the standard DOM API.
  2612. *
  2613. * @function
  2614. * @see {@link EventTarget#trigger}
  2615. */
  2616. EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
  2617. /**
  2618. * @file mixins/evented.js
  2619. * @module evented
  2620. */
  2621. const objName = obj => {
  2622. if (typeof obj.name === 'function') {
  2623. return obj.name();
  2624. }
  2625. if (typeof obj.name === 'string') {
  2626. return obj.name;
  2627. }
  2628. if (obj.name_) {
  2629. return obj.name_;
  2630. }
  2631. if (obj.constructor && obj.constructor.name) {
  2632. return obj.constructor.name;
  2633. }
  2634. return typeof obj;
  2635. };
  2636. /**
  2637. * Returns whether or not an object has had the evented mixin applied.
  2638. *
  2639. * @param {Object} object
  2640. * An object to test.
  2641. *
  2642. * @return {boolean}
  2643. * Whether or not the object appears to be evented.
  2644. */
  2645. const isEvented = object => object instanceof EventTarget || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2646. /**
  2647. * Adds a callback to run after the evented mixin applied.
  2648. *
  2649. * @param {Object} target
  2650. * An object to Add
  2651. * @param {Function} callback
  2652. * The callback to run.
  2653. */
  2654. const addEventedCallback = (target, callback) => {
  2655. if (isEvented(target)) {
  2656. callback();
  2657. } else {
  2658. if (!target.eventedCallbacks) {
  2659. target.eventedCallbacks = [];
  2660. }
  2661. target.eventedCallbacks.push(callback);
  2662. }
  2663. };
  2664. /**
  2665. * Whether a value is a valid event type - non-empty string or array.
  2666. *
  2667. * @private
  2668. * @param {string|Array} type
  2669. * The type value to test.
  2670. *
  2671. * @return {boolean}
  2672. * Whether or not the type is a valid event type.
  2673. */
  2674. const isValidEventType = type =>
  2675. // The regex here verifies that the `type` contains at least one non-
  2676. // whitespace character.
  2677. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2678. /**
  2679. * Validates a value to determine if it is a valid event target. Throws if not.
  2680. *
  2681. * @private
  2682. * @throws {Error}
  2683. * If the target does not appear to be a valid event target.
  2684. *
  2685. * @param {Object} target
  2686. * The object to test.
  2687. *
  2688. * @param {Object} obj
  2689. * The evented object we are validating for
  2690. *
  2691. * @param {string} fnName
  2692. * The name of the evented mixin function that called this.
  2693. */
  2694. const validateTarget = (target, obj, fnName) => {
  2695. if (!target || !target.nodeName && !isEvented(target)) {
  2696. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2697. }
  2698. };
  2699. /**
  2700. * Validates a value to determine if it is a valid event target. Throws if not.
  2701. *
  2702. * @private
  2703. * @throws {Error}
  2704. * If the type does not appear to be a valid event type.
  2705. *
  2706. * @param {string|Array} type
  2707. * The type to test.
  2708. *
  2709. * @param {Object} obj
  2710. * The evented object we are validating for
  2711. *
  2712. * @param {string} fnName
  2713. * The name of the evented mixin function that called this.
  2714. */
  2715. const validateEventType = (type, obj, fnName) => {
  2716. if (!isValidEventType(type)) {
  2717. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2718. }
  2719. };
  2720. /**
  2721. * Validates a value to determine if it is a valid listener. Throws if not.
  2722. *
  2723. * @private
  2724. * @throws {Error}
  2725. * If the listener is not a function.
  2726. *
  2727. * @param {Function} listener
  2728. * The listener to test.
  2729. *
  2730. * @param {Object} obj
  2731. * The evented object we are validating for
  2732. *
  2733. * @param {string} fnName
  2734. * The name of the evented mixin function that called this.
  2735. */
  2736. const validateListener = (listener, obj, fnName) => {
  2737. if (typeof listener !== 'function') {
  2738. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2739. }
  2740. };
  2741. /**
  2742. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2743. * normalizes them into an object.
  2744. *
  2745. * @private
  2746. * @param {Object} self
  2747. * The evented object on which `on()` or `one()` was called. This
  2748. * object will be bound as the `this` value for the listener.
  2749. *
  2750. * @param {Array} args
  2751. * An array of arguments passed to `on()` or `one()`.
  2752. *
  2753. * @param {string} fnName
  2754. * The name of the evented mixin function that called this.
  2755. *
  2756. * @return {Object}
  2757. * An object containing useful values for `on()` or `one()` calls.
  2758. */
  2759. const normalizeListenArgs = (self, args, fnName) => {
  2760. // If the number of arguments is less than 3, the target is always the
  2761. // evented object itself.
  2762. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2763. let target;
  2764. let type;
  2765. let listener;
  2766. if (isTargetingSelf) {
  2767. target = self.eventBusEl_;
  2768. // Deal with cases where we got 3 arguments, but we are still listening to
  2769. // the evented object itself.
  2770. if (args.length >= 3) {
  2771. args.shift();
  2772. }
  2773. [type, listener] = args;
  2774. } else {
  2775. // This was `[target, type, listener] = args;` but this block needs more than
  2776. // one statement to produce minified output compatible with Chrome 53.
  2777. // See https://github.com/videojs/video.js/pull/8810
  2778. target = args[0];
  2779. type = args[1];
  2780. listener = args[2];
  2781. }
  2782. validateTarget(target, self, fnName);
  2783. validateEventType(type, self, fnName);
  2784. validateListener(listener, self, fnName);
  2785. listener = bind_(self, listener);
  2786. return {
  2787. isTargetingSelf,
  2788. target,
  2789. type,
  2790. listener
  2791. };
  2792. };
  2793. /**
  2794. * Adds the listener to the event type(s) on the target, normalizing for
  2795. * the type of target.
  2796. *
  2797. * @private
  2798. * @param {Element|Object} target
  2799. * A DOM node or evented object.
  2800. *
  2801. * @param {string} method
  2802. * The event binding method to use ("on" or "one").
  2803. *
  2804. * @param {string|Array} type
  2805. * One or more event type(s).
  2806. *
  2807. * @param {Function} listener
  2808. * A listener function.
  2809. */
  2810. const listen = (target, method, type, listener) => {
  2811. validateTarget(target, target, method);
  2812. if (target.nodeName) {
  2813. Events[method](target, type, listener);
  2814. } else {
  2815. target[method](type, listener);
  2816. }
  2817. };
  2818. /**
  2819. * Contains methods that provide event capabilities to an object which is passed
  2820. * to {@link module:evented|evented}.
  2821. *
  2822. * @mixin EventedMixin
  2823. */
  2824. const EventedMixin = {
  2825. /**
  2826. * Add a listener to an event (or events) on this object or another evented
  2827. * object.
  2828. *
  2829. * @param {string|Array|Element|Object} targetOrType
  2830. * If this is a string or array, it represents the event type(s)
  2831. * that will trigger the listener.
  2832. *
  2833. * Another evented object can be passed here instead, which will
  2834. * cause the listener to listen for events on _that_ object.
  2835. *
  2836. * In either case, the listener's `this` value will be bound to
  2837. * this object.
  2838. *
  2839. * @param {string|Array|Function} typeOrListener
  2840. * If the first argument was a string or array, this should be the
  2841. * listener function. Otherwise, this is a string or array of event
  2842. * type(s).
  2843. *
  2844. * @param {Function} [listener]
  2845. * If the first argument was another evented object, this will be
  2846. * the listener function.
  2847. */
  2848. on(...args) {
  2849. const {
  2850. isTargetingSelf,
  2851. target,
  2852. type,
  2853. listener
  2854. } = normalizeListenArgs(this, args, 'on');
  2855. listen(target, 'on', type, listener);
  2856. // If this object is listening to another evented object.
  2857. if (!isTargetingSelf) {
  2858. // If this object is disposed, remove the listener.
  2859. const removeListenerOnDispose = () => this.off(target, type, listener);
  2860. // Use the same function ID as the listener so we can remove it later it
  2861. // using the ID of the original listener.
  2862. removeListenerOnDispose.guid = listener.guid;
  2863. // Add a listener to the target's dispose event as well. This ensures
  2864. // that if the target is disposed BEFORE this object, we remove the
  2865. // removal listener that was just added. Otherwise, we create a memory leak.
  2866. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2867. // Use the same function ID as the listener so we can remove it later
  2868. // it using the ID of the original listener.
  2869. removeRemoverOnTargetDispose.guid = listener.guid;
  2870. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2871. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2872. }
  2873. },
  2874. /**
  2875. * Add a listener to an event (or events) on this object or another evented
  2876. * object. The listener will be called once per event and then removed.
  2877. *
  2878. * @param {string|Array|Element|Object} targetOrType
  2879. * If this is a string or array, it represents the event type(s)
  2880. * that will trigger the listener.
  2881. *
  2882. * Another evented object can be passed here instead, which will
  2883. * cause the listener to listen for events on _that_ object.
  2884. *
  2885. * In either case, the listener's `this` value will be bound to
  2886. * this object.
  2887. *
  2888. * @param {string|Array|Function} typeOrListener
  2889. * If the first argument was a string or array, this should be the
  2890. * listener function. Otherwise, this is a string or array of event
  2891. * type(s).
  2892. *
  2893. * @param {Function} [listener]
  2894. * If the first argument was another evented object, this will be
  2895. * the listener function.
  2896. */
  2897. one(...args) {
  2898. const {
  2899. isTargetingSelf,
  2900. target,
  2901. type,
  2902. listener
  2903. } = normalizeListenArgs(this, args, 'one');
  2904. // Targeting this evented object.
  2905. if (isTargetingSelf) {
  2906. listen(target, 'one', type, listener);
  2907. // Targeting another evented object.
  2908. } else {
  2909. // TODO: This wrapper is incorrect! It should only
  2910. // remove the wrapper for the event type that called it.
  2911. // Instead all listeners are removed on the first trigger!
  2912. // see https://github.com/videojs/video.js/issues/5962
  2913. const wrapper = (...largs) => {
  2914. this.off(target, type, wrapper);
  2915. listener.apply(null, largs);
  2916. };
  2917. // Use the same function ID as the listener so we can remove it later
  2918. // it using the ID of the original listener.
  2919. wrapper.guid = listener.guid;
  2920. listen(target, 'one', type, wrapper);
  2921. }
  2922. },
  2923. /**
  2924. * Add a listener to an event (or events) on this object or another evented
  2925. * object. The listener will only be called once for the first event that is triggered
  2926. * then removed.
  2927. *
  2928. * @param {string|Array|Element|Object} targetOrType
  2929. * If this is a string or array, it represents the event type(s)
  2930. * that will trigger the listener.
  2931. *
  2932. * Another evented object can be passed here instead, which will
  2933. * cause the listener to listen for events on _that_ object.
  2934. *
  2935. * In either case, the listener's `this` value will be bound to
  2936. * this object.
  2937. *
  2938. * @param {string|Array|Function} typeOrListener
  2939. * If the first argument was a string or array, this should be the
  2940. * listener function. Otherwise, this is a string or array of event
  2941. * type(s).
  2942. *
  2943. * @param {Function} [listener]
  2944. * If the first argument was another evented object, this will be
  2945. * the listener function.
  2946. */
  2947. any(...args) {
  2948. const {
  2949. isTargetingSelf,
  2950. target,
  2951. type,
  2952. listener
  2953. } = normalizeListenArgs(this, args, 'any');
  2954. // Targeting this evented object.
  2955. if (isTargetingSelf) {
  2956. listen(target, 'any', type, listener);
  2957. // Targeting another evented object.
  2958. } else {
  2959. const wrapper = (...largs) => {
  2960. this.off(target, type, wrapper);
  2961. listener.apply(null, largs);
  2962. };
  2963. // Use the same function ID as the listener so we can remove it later
  2964. // it using the ID of the original listener.
  2965. wrapper.guid = listener.guid;
  2966. listen(target, 'any', type, wrapper);
  2967. }
  2968. },
  2969. /**
  2970. * Removes listener(s) from event(s) on an evented object.
  2971. *
  2972. * @param {string|Array|Element|Object} [targetOrType]
  2973. * If this is a string or array, it represents the event type(s).
  2974. *
  2975. * Another evented object can be passed here instead, in which case
  2976. * ALL 3 arguments are _required_.
  2977. *
  2978. * @param {string|Array|Function} [typeOrListener]
  2979. * If the first argument was a string or array, this may be the
  2980. * listener function. Otherwise, this is a string or array of event
  2981. * type(s).
  2982. *
  2983. * @param {Function} [listener]
  2984. * If the first argument was another evented object, this will be
  2985. * the listener function; otherwise, _all_ listeners bound to the
  2986. * event type(s) will be removed.
  2987. */
  2988. off(targetOrType, typeOrListener, listener) {
  2989. // Targeting this evented object.
  2990. if (!targetOrType || isValidEventType(targetOrType)) {
  2991. off(this.eventBusEl_, targetOrType, typeOrListener);
  2992. // Targeting another evented object.
  2993. } else {
  2994. const target = targetOrType;
  2995. const type = typeOrListener;
  2996. // Fail fast and in a meaningful way!
  2997. validateTarget(target, this, 'off');
  2998. validateEventType(type, this, 'off');
  2999. validateListener(listener, this, 'off');
  3000. // Ensure there's at least a guid, even if the function hasn't been used
  3001. listener = bind_(this, listener);
  3002. // Remove the dispose listener on this evented object, which was given
  3003. // the same guid as the event listener in on().
  3004. this.off('dispose', listener);
  3005. if (target.nodeName) {
  3006. off(target, type, listener);
  3007. off(target, 'dispose', listener);
  3008. } else if (isEvented(target)) {
  3009. target.off(type, listener);
  3010. target.off('dispose', listener);
  3011. }
  3012. }
  3013. },
  3014. /**
  3015. * Fire an event on this evented object, causing its listeners to be called.
  3016. *
  3017. * @param {string|Object} event
  3018. * An event type or an object with a type property.
  3019. *
  3020. * @param {Object} [hash]
  3021. * An additional object to pass along to listeners.
  3022. *
  3023. * @return {boolean}
  3024. * Whether or not the default behavior was prevented.
  3025. */
  3026. trigger(event, hash) {
  3027. validateTarget(this.eventBusEl_, this, 'trigger');
  3028. const type = event && typeof event !== 'string' ? event.type : event;
  3029. if (!isValidEventType(type)) {
  3030. throw new Error(`Invalid event type for ${objName(this)}#trigger; ` + 'must be a non-empty string or object with a type key that has a non-empty value.');
  3031. }
  3032. return trigger(this.eventBusEl_, event, hash);
  3033. }
  3034. };
  3035. /**
  3036. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  3037. *
  3038. * @param {Object} target
  3039. * The object to which to add event methods.
  3040. *
  3041. * @param {Object} [options={}]
  3042. * Options for customizing the mixin behavior.
  3043. *
  3044. * @param {string} [options.eventBusKey]
  3045. * By default, adds a `eventBusEl_` DOM element to the target object,
  3046. * which is used as an event bus. If the target object already has a
  3047. * DOM element that should be used, pass its key here.
  3048. *
  3049. * @return {Object}
  3050. * The target object.
  3051. */
  3052. function evented(target, options = {}) {
  3053. const {
  3054. eventBusKey
  3055. } = options;
  3056. // Set or create the eventBusEl_.
  3057. if (eventBusKey) {
  3058. if (!target[eventBusKey].nodeName) {
  3059. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  3060. }
  3061. target.eventBusEl_ = target[eventBusKey];
  3062. } else {
  3063. target.eventBusEl_ = createEl('span', {
  3064. className: 'vjs-event-bus'
  3065. });
  3066. }
  3067. Object.assign(target, EventedMixin);
  3068. if (target.eventedCallbacks) {
  3069. target.eventedCallbacks.forEach(callback => {
  3070. callback();
  3071. });
  3072. }
  3073. // When any evented object is disposed, it removes all its listeners.
  3074. target.on('dispose', () => {
  3075. target.off();
  3076. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  3077. if (val && DomData.has(val)) {
  3078. DomData.delete(val);
  3079. }
  3080. });
  3081. window.setTimeout(() => {
  3082. target.eventBusEl_ = null;
  3083. }, 0);
  3084. });
  3085. return target;
  3086. }
  3087. /**
  3088. * @file mixins/stateful.js
  3089. * @module stateful
  3090. */
  3091. /**
  3092. * Contains methods that provide statefulness to an object which is passed
  3093. * to {@link module:stateful}.
  3094. *
  3095. * @mixin StatefulMixin
  3096. */
  3097. const StatefulMixin = {
  3098. /**
  3099. * A hash containing arbitrary keys and values representing the state of
  3100. * the object.
  3101. *
  3102. * @type {Object}
  3103. */
  3104. state: {},
  3105. /**
  3106. * Set the state of an object by mutating its
  3107. * {@link module:stateful~StatefulMixin.state|state} object in place.
  3108. *
  3109. * @fires module:stateful~StatefulMixin#statechanged
  3110. * @param {Object|Function} stateUpdates
  3111. * A new set of properties to shallow-merge into the plugin state.
  3112. * Can be a plain object or a function returning a plain object.
  3113. *
  3114. * @return {Object|undefined}
  3115. * An object containing changes that occurred. If no changes
  3116. * occurred, returns `undefined`.
  3117. */
  3118. setState(stateUpdates) {
  3119. // Support providing the `stateUpdates` state as a function.
  3120. if (typeof stateUpdates === 'function') {
  3121. stateUpdates = stateUpdates();
  3122. }
  3123. let changes;
  3124. each(stateUpdates, (value, key) => {
  3125. // Record the change if the value is different from what's in the
  3126. // current state.
  3127. if (this.state[key] !== value) {
  3128. changes = changes || {};
  3129. changes[key] = {
  3130. from: this.state[key],
  3131. to: value
  3132. };
  3133. }
  3134. this.state[key] = value;
  3135. });
  3136. // Only trigger "statechange" if there were changes AND we have a trigger
  3137. // function. This allows us to not require that the target object be an
  3138. // evented object.
  3139. if (changes && isEvented(this)) {
  3140. /**
  3141. * An event triggered on an object that is both
  3142. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3143. * indicating that its state has changed.
  3144. *
  3145. * @event module:stateful~StatefulMixin#statechanged
  3146. * @type {Object}
  3147. * @property {Object} changes
  3148. * A hash containing the properties that were changed and
  3149. * the values they were changed `from` and `to`.
  3150. */
  3151. this.trigger({
  3152. changes,
  3153. type: 'statechanged'
  3154. });
  3155. }
  3156. return changes;
  3157. }
  3158. };
  3159. /**
  3160. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3161. * object.
  3162. *
  3163. * If the target object is {@link module:evented|evented} and has a
  3164. * `handleStateChanged` method, that method will be automatically bound to the
  3165. * `statechanged` event on itself.
  3166. *
  3167. * @param {Object} target
  3168. * The object to be made stateful.
  3169. *
  3170. * @param {Object} [defaultState]
  3171. * A default set of properties to populate the newly-stateful object's
  3172. * `state` property.
  3173. *
  3174. * @return {Object}
  3175. * Returns the `target`.
  3176. */
  3177. function stateful(target, defaultState) {
  3178. Object.assign(target, StatefulMixin);
  3179. // This happens after the mixing-in because we need to replace the `state`
  3180. // added in that step.
  3181. target.state = Object.assign({}, target.state, defaultState);
  3182. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3183. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3184. target.on('statechanged', target.handleStateChanged);
  3185. }
  3186. return target;
  3187. }
  3188. /**
  3189. * @file str.js
  3190. * @module to-lower-case
  3191. */
  3192. /**
  3193. * Lowercase the first letter of a string.
  3194. *
  3195. * @param {string} string
  3196. * String to be lowercased
  3197. *
  3198. * @return {string}
  3199. * The string with a lowercased first letter
  3200. */
  3201. const toLowerCase = function (string) {
  3202. if (typeof string !== 'string') {
  3203. return string;
  3204. }
  3205. return string.replace(/./, w => w.toLowerCase());
  3206. };
  3207. /**
  3208. * Uppercase the first letter of a string.
  3209. *
  3210. * @param {string} string
  3211. * String to be uppercased
  3212. *
  3213. * @return {string}
  3214. * The string with an uppercased first letter
  3215. */
  3216. const toTitleCase = function (string) {
  3217. if (typeof string !== 'string') {
  3218. return string;
  3219. }
  3220. return string.replace(/./, w => w.toUpperCase());
  3221. };
  3222. /**
  3223. * Compares the TitleCase versions of the two strings for equality.
  3224. *
  3225. * @param {string} str1
  3226. * The first string to compare
  3227. *
  3228. * @param {string} str2
  3229. * The second string to compare
  3230. *
  3231. * @return {boolean}
  3232. * Whether the TitleCase versions of the strings are equal
  3233. */
  3234. const titleCaseEquals = function (str1, str2) {
  3235. return toTitleCase(str1) === toTitleCase(str2);
  3236. };
  3237. var Str = /*#__PURE__*/Object.freeze({
  3238. __proto__: null,
  3239. toLowerCase: toLowerCase,
  3240. toTitleCase: toTitleCase,
  3241. titleCaseEquals: titleCaseEquals
  3242. });
  3243. /**
  3244. * Player Component - Base class for all UI objects
  3245. *
  3246. * @file component.js
  3247. */
  3248. /** @import Player from './player' */
  3249. /**
  3250. * A callback to be called if and when the component is ready.
  3251. * `this` will be the Component instance.
  3252. *
  3253. * @callback ReadyCallback
  3254. * @returns {void}
  3255. */
  3256. /**
  3257. * Base class for all UI Components.
  3258. * Components are UI objects which represent both a javascript object and an element
  3259. * in the DOM. They can be children of other components, and can have
  3260. * children themselves.
  3261. *
  3262. * Components can also use methods from {@link EventTarget}
  3263. */
  3264. class Component {
  3265. /**
  3266. * Creates an instance of this class.
  3267. *
  3268. * @param {Player} player
  3269. * The `Player` that this class should be attached to.
  3270. *
  3271. * @param {Object} [options]
  3272. * The key/value store of component options.
  3273. *
  3274. * @param {Object[]} [options.children]
  3275. * An array of children objects to initialize this component with. Children objects have
  3276. * a name property that will be used if more than one component of the same type needs to be
  3277. * added.
  3278. *
  3279. * @param {string} [options.className]
  3280. * A class or space separated list of classes to add the component
  3281. *
  3282. * @param {ReadyCallback} [ready]
  3283. * Function that gets called when the `Component` is ready.
  3284. */
  3285. constructor(player, options, ready) {
  3286. // The component might be the player itself and we can't pass `this` to super
  3287. if (!player && this.play) {
  3288. this.player_ = player = this; // eslint-disable-line
  3289. } else {
  3290. this.player_ = player;
  3291. }
  3292. this.isDisposed_ = false;
  3293. // Hold the reference to the parent component via `addChild` method
  3294. this.parentComponent_ = null;
  3295. // Make a copy of prototype.options_ to protect against overriding defaults
  3296. this.options_ = merge({}, this.options_);
  3297. // Updated options with supplied options
  3298. options = this.options_ = merge(this.options_, options);
  3299. // Get ID from options or options element if one is supplied
  3300. this.id_ = options.id || options.el && options.el.id;
  3301. // If there was no ID from the options, generate one
  3302. if (!this.id_) {
  3303. // Don't require the player ID function in the case of mock players
  3304. const id = player && player.id && player.id() || 'no_player';
  3305. this.id_ = `${id}_component_${newGUID()}`;
  3306. }
  3307. this.name_ = options.name || null;
  3308. // Create element if one wasn't provided in options
  3309. if (options.el) {
  3310. this.el_ = options.el;
  3311. } else if (options.createEl !== false) {
  3312. this.el_ = this.createEl();
  3313. }
  3314. if (options.className && this.el_) {
  3315. options.className.split(' ').forEach(c => this.addClass(c));
  3316. }
  3317. // Remove the placeholder event methods. If the component is evented, the
  3318. // real methods are added next
  3319. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3320. this[fn] = undefined;
  3321. });
  3322. // if evented is anything except false, we want to mixin in evented
  3323. if (options.evented !== false) {
  3324. // Make this an evented object and use `el_`, if available, as its event bus
  3325. evented(this, {
  3326. eventBusKey: this.el_ ? 'el_' : null
  3327. });
  3328. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3329. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3330. }
  3331. stateful(this, this.constructor.defaultState);
  3332. this.children_ = [];
  3333. this.childIndex_ = {};
  3334. this.childNameIndex_ = {};
  3335. this.setTimeoutIds_ = new Set();
  3336. this.setIntervalIds_ = new Set();
  3337. this.rafIds_ = new Set();
  3338. this.namedRafs_ = new Map();
  3339. this.clearingTimersOnDispose_ = false;
  3340. // Add any child components in options
  3341. if (options.initChildren !== false) {
  3342. this.initChildren();
  3343. }
  3344. // Don't want to trigger ready here or it will go before init is actually
  3345. // finished for all children that run this constructor
  3346. this.ready(ready);
  3347. if (options.reportTouchActivity !== false) {
  3348. this.enableTouchActivity();
  3349. }
  3350. }
  3351. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3352. // They are replaced or removed in the constructor
  3353. /**
  3354. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3355. * function that will get called when an event with a certain name gets triggered.
  3356. *
  3357. * @param {string|string[]} type
  3358. * An event name or an array of event names.
  3359. *
  3360. * @param {Function} fn
  3361. * The function to call with `EventTarget`s
  3362. */
  3363. /**
  3364. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3365. * This makes it so that the `event listener` will no longer get called when the
  3366. * named event happens.
  3367. *
  3368. * @param {string|string[]} type
  3369. * An event name or an array of event names.
  3370. *
  3371. * @param {Function} [fn]
  3372. * The function to remove. If not specified, all listeners managed by Video.js will be removed.
  3373. */
  3374. /**
  3375. * This function will add an `event listener` that gets triggered only once. After the
  3376. * first trigger it will get removed. This is like adding an `event listener`
  3377. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3378. *
  3379. * @param {string|string[]} type
  3380. * An event name or an array of event names.
  3381. *
  3382. * @param {Function} fn
  3383. * The function to be called once for each event name.
  3384. */
  3385. /**
  3386. * This function will add an `event listener` that gets triggered only once and is
  3387. * removed from all events. This is like adding an array of `event listener`s
  3388. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3389. * first time it is triggered.
  3390. *
  3391. * @param {string|string[]} type
  3392. * An event name or an array of event names.
  3393. *
  3394. * @param {Function} fn
  3395. * The function to be called once for each event name.
  3396. */
  3397. /**
  3398. * This function causes an event to happen. This will then cause any `event listeners`
  3399. * that are waiting for that event, to get called. If there are no `event listeners`
  3400. * for an event then nothing will happen.
  3401. *
  3402. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3403. * Trigger will also call the `on` + `uppercaseEventName` function.
  3404. *
  3405. * Example:
  3406. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3407. * `onClick` if it exists.
  3408. *
  3409. * @param {string|Event|Object} event
  3410. * The name of the event, an `Event`, or an object with a key of type set to
  3411. * an event name.
  3412. *
  3413. * @param {Object} [hash]
  3414. * Optionally extra argument to pass through to an event listener
  3415. */
  3416. /**
  3417. * Dispose of the `Component` and all child components.
  3418. *
  3419. * @fires Component#dispose
  3420. *
  3421. * @param {Object} options
  3422. * @param {Element} options.originalEl element with which to replace player element
  3423. */
  3424. dispose(options = {}) {
  3425. // Bail out if the component has already been disposed.
  3426. if (this.isDisposed_) {
  3427. return;
  3428. }
  3429. if (this.readyQueue_) {
  3430. this.readyQueue_.length = 0;
  3431. }
  3432. /**
  3433. * Triggered when a `Component` is disposed.
  3434. *
  3435. * @event Component#dispose
  3436. * @type {Event}
  3437. *
  3438. * @property {boolean} [bubbles=false]
  3439. * set to false so that the dispose event does not
  3440. * bubble up
  3441. */
  3442. this.trigger({
  3443. type: 'dispose',
  3444. bubbles: false
  3445. });
  3446. this.isDisposed_ = true;
  3447. // Dispose all children.
  3448. if (this.children_) {
  3449. for (let i = this.children_.length - 1; i >= 0; i--) {
  3450. if (this.children_[i].dispose) {
  3451. this.children_[i].dispose();
  3452. }
  3453. }
  3454. }
  3455. // Delete child references
  3456. this.children_ = null;
  3457. this.childIndex_ = null;
  3458. this.childNameIndex_ = null;
  3459. this.parentComponent_ = null;
  3460. if (this.el_) {
  3461. // Remove element from DOM
  3462. if (this.el_.parentNode) {
  3463. if (options.restoreEl) {
  3464. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3465. } else {
  3466. this.el_.parentNode.removeChild(this.el_);
  3467. }
  3468. }
  3469. this.el_ = null;
  3470. }
  3471. // remove reference to the player after disposing of the element
  3472. this.player_ = null;
  3473. }
  3474. /**
  3475. * Determine whether or not this component has been disposed.
  3476. *
  3477. * @return {boolean}
  3478. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3479. */
  3480. isDisposed() {
  3481. return Boolean(this.isDisposed_);
  3482. }
  3483. /**
  3484. * Return the {@link Player} that the `Component` has attached to.
  3485. *
  3486. * @return {Player}
  3487. * The player that this `Component` has attached to.
  3488. */
  3489. player() {
  3490. return this.player_;
  3491. }
  3492. /**
  3493. * Deep merge of options objects with new options.
  3494. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3495. * The two properties get merged using {@link module:obj.merge}
  3496. *
  3497. * @param {Object} obj
  3498. * The object that contains new options.
  3499. *
  3500. * @return {Object}
  3501. * A new object of `this.options_` and `obj` merged together.
  3502. */
  3503. options(obj) {
  3504. if (!obj) {
  3505. return this.options_;
  3506. }
  3507. this.options_ = merge(this.options_, obj);
  3508. return this.options_;
  3509. }
  3510. /**
  3511. * Get the `Component`s DOM element
  3512. *
  3513. * @return {Element}
  3514. * The DOM element for this `Component`.
  3515. */
  3516. el() {
  3517. return this.el_;
  3518. }
  3519. /**
  3520. * Create the `Component`s DOM element.
  3521. *
  3522. * @param {string} [tagName]
  3523. * Element's DOM node type. e.g. 'div'
  3524. *
  3525. * @param {Object} [properties]
  3526. * An object of properties that should be set.
  3527. *
  3528. * @param {Object} [attributes]
  3529. * An object of attributes that should be set.
  3530. *
  3531. * @return {Element}
  3532. * The element that gets created.
  3533. */
  3534. createEl(tagName, properties, attributes) {
  3535. return createEl(tagName, properties, attributes);
  3536. }
  3537. /**
  3538. * Localize a string given the string in english.
  3539. *
  3540. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3541. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3542. *
  3543. * If a `defaultValue` is provided, it'll use that over `string`,
  3544. * if a value isn't found in provided language files.
  3545. * This is useful if you want to have a descriptive key for token replacement
  3546. * but have a succinct localized string and not require `en.json` to be included.
  3547. *
  3548. * Currently, it is used for the progress bar timing.
  3549. * ```js
  3550. * {
  3551. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3552. * }
  3553. * ```
  3554. * It is then used like so:
  3555. * ```js
  3556. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3557. * [this.player_.currentTime(), this.player_.duration()],
  3558. * '{1} of {2}');
  3559. * ```
  3560. *
  3561. * Which outputs something like: `01:23 of 24:56`.
  3562. *
  3563. *
  3564. * @param {string} string
  3565. * The string to localize and the key to lookup in the language files.
  3566. * @param {string[]} [tokens]
  3567. * If the current item has token replacements, provide the tokens here.
  3568. * @param {string} [defaultValue]
  3569. * Defaults to `string`. Can be a default value to use for token replacement
  3570. * if the lookup key is needed to be separate.
  3571. *
  3572. * @return {string}
  3573. * The localized string or if no localization exists the english string.
  3574. */
  3575. localize(string, tokens, defaultValue = string) {
  3576. const code = this.player_.language && this.player_.language();
  3577. const languages = this.player_.languages && this.player_.languages();
  3578. const language = languages && languages[code];
  3579. const primaryCode = code && code.split('-')[0];
  3580. const primaryLang = languages && languages[primaryCode];
  3581. let localizedString = defaultValue;
  3582. if (language && language[string]) {
  3583. localizedString = language[string];
  3584. } else if (primaryLang && primaryLang[string]) {
  3585. localizedString = primaryLang[string];
  3586. }
  3587. if (tokens) {
  3588. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3589. const value = tokens[index - 1];
  3590. let ret = value;
  3591. if (typeof value === 'undefined') {
  3592. ret = match;
  3593. }
  3594. return ret;
  3595. });
  3596. }
  3597. return localizedString;
  3598. }
  3599. /**
  3600. * Handles language change for the player in components. Should be overridden by sub-components.
  3601. *
  3602. * @abstract
  3603. */
  3604. handleLanguagechange() {}
  3605. /**
  3606. * Return the `Component`s DOM element. This is where children get inserted.
  3607. * This will usually be the the same as the element returned in {@link Component#el}.
  3608. *
  3609. * @return {Element}
  3610. * The content element for this `Component`.
  3611. */
  3612. contentEl() {
  3613. return this.contentEl_ || this.el_;
  3614. }
  3615. /**
  3616. * Get this `Component`s ID
  3617. *
  3618. * @return {string}
  3619. * The id of this `Component`
  3620. */
  3621. id() {
  3622. return this.id_;
  3623. }
  3624. /**
  3625. * Get the `Component`s name. The name gets used to reference the `Component`
  3626. * and is set during registration.
  3627. *
  3628. * @return {string}
  3629. * The name of this `Component`.
  3630. */
  3631. name() {
  3632. return this.name_;
  3633. }
  3634. /**
  3635. * Get an array of all child components
  3636. *
  3637. * @return {Array}
  3638. * The children
  3639. */
  3640. children() {
  3641. return this.children_;
  3642. }
  3643. /**
  3644. * Returns the child `Component` with the given `id`.
  3645. *
  3646. * @param {string} id
  3647. * The id of the child `Component` to get.
  3648. *
  3649. * @return {Component|undefined}
  3650. * The child `Component` with the given `id` or undefined.
  3651. */
  3652. getChildById(id) {
  3653. return this.childIndex_[id];
  3654. }
  3655. /**
  3656. * Returns the child `Component` with the given `name`.
  3657. *
  3658. * @param {string} name
  3659. * The name of the child `Component` to get.
  3660. *
  3661. * @return {Component|undefined}
  3662. * The child `Component` with the given `name` or undefined.
  3663. */
  3664. getChild(name) {
  3665. if (!name) {
  3666. return;
  3667. }
  3668. return this.childNameIndex_[name];
  3669. }
  3670. /**
  3671. * Returns the descendant `Component` following the givent
  3672. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3673. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3674. * component and 'baz' on the 'bar' component and return undefined
  3675. * if any of those don't exist.
  3676. *
  3677. * @param {...string[]|...string} names
  3678. * The name of the child `Component` to get.
  3679. *
  3680. * @return {Component|undefined}
  3681. * The descendant `Component` following the given descendant
  3682. * `names` or undefined.
  3683. */
  3684. getDescendant(...names) {
  3685. // flatten array argument into the main array
  3686. names = names.reduce((acc, n) => acc.concat(n), []);
  3687. let currentChild = this;
  3688. for (let i = 0; i < names.length; i++) {
  3689. currentChild = currentChild.getChild(names[i]);
  3690. if (!currentChild || !currentChild.getChild) {
  3691. return;
  3692. }
  3693. }
  3694. return currentChild;
  3695. }
  3696. /**
  3697. * Adds an SVG icon element to another element or component.
  3698. *
  3699. * @param {string} iconName
  3700. * The name of icon. A list of all the icon names can be found at 'sandbox/svg-icons.html'
  3701. *
  3702. * @param {Element} [el=this.el()]
  3703. * Element to set the title on. Defaults to the current Component's element.
  3704. *
  3705. * @return {Element}
  3706. * The newly created icon element.
  3707. */
  3708. setIcon(iconName, el = this.el()) {
  3709. // TODO: In v9 of video.js, we will want to remove font icons entirely.
  3710. // This means this check, as well as the others throughout the code, and
  3711. // the unecessary CSS for font icons, will need to be removed.
  3712. // See https://github.com/videojs/video.js/pull/8260 as to which components
  3713. // need updating.
  3714. if (!this.player_.options_.experimentalSvgIcons) {
  3715. return;
  3716. }
  3717. const xmlnsURL = 'http://www.w3.org/2000/svg';
  3718. // The below creates an element in the format of:
  3719. // <span><svg><use>....</use></svg></span>
  3720. const iconContainer = createEl('span', {
  3721. className: 'vjs-icon-placeholder vjs-svg-icon'
  3722. }, {
  3723. 'aria-hidden': 'true'
  3724. });
  3725. const svgEl = document.createElementNS(xmlnsURL, 'svg');
  3726. svgEl.setAttributeNS(null, 'viewBox', '0 0 512 512');
  3727. const useEl = document.createElementNS(xmlnsURL, 'use');
  3728. svgEl.appendChild(useEl);
  3729. useEl.setAttributeNS(null, 'href', `#vjs-icon-${iconName}`);
  3730. iconContainer.appendChild(svgEl);
  3731. // Replace a pre-existing icon if one exists.
  3732. if (this.iconIsSet_) {
  3733. el.replaceChild(iconContainer, el.querySelector('.vjs-icon-placeholder'));
  3734. } else {
  3735. el.appendChild(iconContainer);
  3736. }
  3737. this.iconIsSet_ = true;
  3738. return iconContainer;
  3739. }
  3740. /**
  3741. * Add a child `Component` inside the current `Component`.
  3742. *
  3743. * @param {string|Component} child
  3744. * The name or instance of a child to add.
  3745. *
  3746. * @param {Object} [options={}]
  3747. * The key/value store of options that will get passed to children of
  3748. * the child.
  3749. *
  3750. * @param {number} [index=this.children_.length]
  3751. * The index to attempt to add a child into.
  3752. *
  3753. *
  3754. * @return {Component}
  3755. * The `Component` that gets added as a child. When using a string the
  3756. * `Component` will get created by this process.
  3757. */
  3758. addChild(child, options = {}, index = this.children_.length) {
  3759. let component;
  3760. let componentName;
  3761. // If child is a string, create component with options
  3762. if (typeof child === 'string') {
  3763. componentName = toTitleCase(child);
  3764. const componentClassName = options.componentClass || componentName;
  3765. // Set name through options
  3766. options.name = componentName;
  3767. // Create a new object & element for this controls set
  3768. // If there's no .player_, this is a player
  3769. const ComponentClass = Component.getComponent(componentClassName);
  3770. if (!ComponentClass) {
  3771. throw new Error(`Component ${componentClassName} does not exist`);
  3772. }
  3773. // data stored directly on the videojs object may be
  3774. // misidentified as a component to retain
  3775. // backwards-compatibility with 4.x. check to make sure the
  3776. // component class can be instantiated.
  3777. if (typeof ComponentClass !== 'function') {
  3778. return null;
  3779. }
  3780. component = new ComponentClass(this.player_ || this, options);
  3781. // child is a component instance
  3782. } else {
  3783. component = child;
  3784. }
  3785. if (component.parentComponent_) {
  3786. component.parentComponent_.removeChild(component);
  3787. }
  3788. this.children_.splice(index, 0, component);
  3789. component.parentComponent_ = this;
  3790. if (typeof component.id === 'function') {
  3791. this.childIndex_[component.id()] = component;
  3792. }
  3793. // If a name wasn't used to create the component, check if we can use the
  3794. // name function of the component
  3795. componentName = componentName || component.name && toTitleCase(component.name());
  3796. if (componentName) {
  3797. this.childNameIndex_[componentName] = component;
  3798. this.childNameIndex_[toLowerCase(componentName)] = component;
  3799. }
  3800. // Add the UI object's element to the container div (box)
  3801. // Having an element is not required
  3802. if (typeof component.el === 'function' && component.el()) {
  3803. // If inserting before a component, insert before that component's element
  3804. let refNode = null;
  3805. if (this.children_[index + 1]) {
  3806. // Most children are components, but the video tech is an HTML element
  3807. if (this.children_[index + 1].el_) {
  3808. refNode = this.children_[index + 1].el_;
  3809. } else if (isEl(this.children_[index + 1])) {
  3810. refNode = this.children_[index + 1];
  3811. }
  3812. }
  3813. this.contentEl().insertBefore(component.el(), refNode);
  3814. }
  3815. // Return so it can stored on parent object if desired.
  3816. return component;
  3817. }
  3818. /**
  3819. * Remove a child `Component` from this `Component`s list of children. Also removes
  3820. * the child `Component`s element from this `Component`s element.
  3821. *
  3822. * @param {Component} component
  3823. * The child `Component` to remove.
  3824. */
  3825. removeChild(component) {
  3826. if (typeof component === 'string') {
  3827. component = this.getChild(component);
  3828. }
  3829. if (!component || !this.children_) {
  3830. return;
  3831. }
  3832. let childFound = false;
  3833. for (let i = this.children_.length - 1; i >= 0; i--) {
  3834. if (this.children_[i] === component) {
  3835. childFound = true;
  3836. this.children_.splice(i, 1);
  3837. break;
  3838. }
  3839. }
  3840. if (!childFound) {
  3841. return;
  3842. }
  3843. component.parentComponent_ = null;
  3844. this.childIndex_[component.id()] = null;
  3845. this.childNameIndex_[toTitleCase(component.name())] = null;
  3846. this.childNameIndex_[toLowerCase(component.name())] = null;
  3847. const compEl = component.el();
  3848. if (compEl && compEl.parentNode === this.contentEl()) {
  3849. this.contentEl().removeChild(component.el());
  3850. }
  3851. }
  3852. /**
  3853. * Add and initialize default child `Component`s based upon options.
  3854. */
  3855. initChildren() {
  3856. const children = this.options_.children;
  3857. if (children) {
  3858. // `this` is `parent`
  3859. const parentOptions = this.options_;
  3860. const handleAdd = child => {
  3861. const name = child.name;
  3862. let opts = child.opts;
  3863. // Allow options for children to be set at the parent options
  3864. // e.g. videojs(id, { controlBar: false });
  3865. // instead of videojs(id, { children: { controlBar: false });
  3866. if (parentOptions[name] !== undefined) {
  3867. opts = parentOptions[name];
  3868. }
  3869. // Allow for disabling default components
  3870. // e.g. options['children']['posterImage'] = false
  3871. if (opts === false) {
  3872. return;
  3873. }
  3874. // Allow options to be passed as a simple boolean if no configuration
  3875. // is necessary.
  3876. if (opts === true) {
  3877. opts = {};
  3878. }
  3879. // We also want to pass the original player options
  3880. // to each component as well so they don't need to
  3881. // reach back into the player for options later.
  3882. opts.playerOptions = this.options_.playerOptions;
  3883. // Create and add the child component.
  3884. // Add a direct reference to the child by name on the parent instance.
  3885. // If two of the same component are used, different names should be supplied
  3886. // for each
  3887. const newChild = this.addChild(name, opts);
  3888. if (newChild) {
  3889. this[name] = newChild;
  3890. }
  3891. };
  3892. // Allow for an array of children details to passed in the options
  3893. let workingChildren;
  3894. const Tech = Component.getComponent('Tech');
  3895. if (Array.isArray(children)) {
  3896. workingChildren = children;
  3897. } else {
  3898. workingChildren = Object.keys(children);
  3899. }
  3900. workingChildren
  3901. // children that are in this.options_ but also in workingChildren would
  3902. // give us extra children we do not want. So, we want to filter them out.
  3903. .concat(Object.keys(this.options_).filter(function (child) {
  3904. return !workingChildren.some(function (wchild) {
  3905. if (typeof wchild === 'string') {
  3906. return child === wchild;
  3907. }
  3908. return child === wchild.name;
  3909. });
  3910. })).map(child => {
  3911. let name;
  3912. let opts;
  3913. if (typeof child === 'string') {
  3914. name = child;
  3915. opts = children[name] || this.options_[name] || {};
  3916. } else {
  3917. name = child.name;
  3918. opts = child;
  3919. }
  3920. return {
  3921. name,
  3922. opts
  3923. };
  3924. }).filter(child => {
  3925. // we have to make sure that child.name isn't in the techOrder since
  3926. // techs are registered as Components but can't aren't compatible
  3927. // See https://github.com/videojs/video.js/issues/2772
  3928. const c = Component.getComponent(child.opts.componentClass || toTitleCase(child.name));
  3929. return c && !Tech.isTech(c);
  3930. }).forEach(handleAdd);
  3931. }
  3932. }
  3933. /**
  3934. * Builds the default DOM class name. Should be overridden by sub-components.
  3935. *
  3936. * @return {string}
  3937. * The DOM class name for this object.
  3938. *
  3939. * @abstract
  3940. */
  3941. buildCSSClass() {
  3942. // Child classes can include a function that does:
  3943. // return 'CLASS NAME' + this._super();
  3944. return '';
  3945. }
  3946. /**
  3947. * Bind a listener to the component's ready state.
  3948. * Different from event listeners in that if the ready event has already happened
  3949. * it will trigger the function immediately.
  3950. *
  3951. * @param {ReadyCallback} fn
  3952. * Function that gets called when the `Component` is ready.
  3953. */
  3954. ready(fn, sync = false) {
  3955. if (!fn) {
  3956. return;
  3957. }
  3958. if (!this.isReady_) {
  3959. this.readyQueue_ = this.readyQueue_ || [];
  3960. this.readyQueue_.push(fn);
  3961. return;
  3962. }
  3963. if (sync) {
  3964. fn.call(this);
  3965. } else {
  3966. // Call the function asynchronously by default for consistency
  3967. this.setTimeout(fn, 1);
  3968. }
  3969. }
  3970. /**
  3971. * Trigger all the ready listeners for this `Component`.
  3972. *
  3973. * @fires Component#ready
  3974. */
  3975. triggerReady() {
  3976. this.isReady_ = true;
  3977. // Ensure ready is triggered asynchronously
  3978. this.setTimeout(function () {
  3979. const readyQueue = this.readyQueue_;
  3980. // Reset Ready Queue
  3981. this.readyQueue_ = [];
  3982. if (readyQueue && readyQueue.length > 0) {
  3983. readyQueue.forEach(function (fn) {
  3984. fn.call(this);
  3985. }, this);
  3986. }
  3987. // Allow for using event listeners also
  3988. /**
  3989. * Triggered when a `Component` is ready.
  3990. *
  3991. * @event Component#ready
  3992. * @type {Event}
  3993. */
  3994. this.trigger('ready');
  3995. }, 1);
  3996. }
  3997. /**
  3998. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  3999. * `contentEl()` or another custom context.
  4000. *
  4001. * @param {string} selector
  4002. * A valid CSS selector, which will be passed to `querySelector`.
  4003. *
  4004. * @param {Element|string} [context=this.contentEl()]
  4005. * A DOM element within which to query. Can also be a selector string in
  4006. * which case the first matching element will get used as context. If
  4007. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4008. * nothing it falls back to `document`.
  4009. *
  4010. * @return {Element|null}
  4011. * the dom element that was found, or null
  4012. *
  4013. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4014. */
  4015. $(selector, context) {
  4016. return $(selector, context || this.contentEl());
  4017. }
  4018. /**
  4019. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  4020. * `contentEl()` or another custom context.
  4021. *
  4022. * @param {string} selector
  4023. * A valid CSS selector, which will be passed to `querySelectorAll`.
  4024. *
  4025. * @param {Element|string} [context=this.contentEl()]
  4026. * A DOM element within which to query. Can also be a selector string in
  4027. * which case the first matching element will get used as context. If
  4028. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4029. * nothing it falls back to `document`.
  4030. *
  4031. * @return {NodeList}
  4032. * a list of dom elements that were found
  4033. *
  4034. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4035. */
  4036. $$(selector, context) {
  4037. return $$(selector, context || this.contentEl());
  4038. }
  4039. /**
  4040. * Check if a component's element has a CSS class name.
  4041. *
  4042. * @param {string} classToCheck
  4043. * CSS class name to check.
  4044. *
  4045. * @return {boolean}
  4046. * - True if the `Component` has the class.
  4047. * - False if the `Component` does not have the class`
  4048. */
  4049. hasClass(classToCheck) {
  4050. return hasClass(this.el_, classToCheck);
  4051. }
  4052. /**
  4053. * Add a CSS class name to the `Component`s element.
  4054. *
  4055. * @param {...string} classesToAdd
  4056. * One or more CSS class name to add.
  4057. */
  4058. addClass(...classesToAdd) {
  4059. addClass(this.el_, ...classesToAdd);
  4060. }
  4061. /**
  4062. * Remove a CSS class name from the `Component`s element.
  4063. *
  4064. * @param {...string} classesToRemove
  4065. * One or more CSS class name to remove.
  4066. */
  4067. removeClass(...classesToRemove) {
  4068. removeClass(this.el_, ...classesToRemove);
  4069. }
  4070. /**
  4071. * Add or remove a CSS class name from the component's element.
  4072. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  4073. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  4074. *
  4075. * @param {string} classToToggle
  4076. * The class to add or remove. Passed to DOMTokenList's toggle()
  4077. *
  4078. * @param {boolean|Dom.PredicateCallback} [predicate]
  4079. * A boolean or function that returns a boolean. Passed to DOMTokenList's toggle().
  4080. */
  4081. toggleClass(classToToggle, predicate) {
  4082. toggleClass(this.el_, classToToggle, predicate);
  4083. }
  4084. /**
  4085. * Show the `Component`s element if it is hidden by removing the
  4086. * 'vjs-hidden' class name from it.
  4087. */
  4088. show() {
  4089. this.removeClass('vjs-hidden');
  4090. }
  4091. /**
  4092. * Hide the `Component`s element if it is currently showing by adding the
  4093. * 'vjs-hidden` class name to it.
  4094. */
  4095. hide() {
  4096. this.addClass('vjs-hidden');
  4097. }
  4098. /**
  4099. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  4100. * class name to it. Used during fadeIn/fadeOut.
  4101. *
  4102. * @private
  4103. */
  4104. lockShowing() {
  4105. this.addClass('vjs-lock-showing');
  4106. }
  4107. /**
  4108. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  4109. * class name from it. Used during fadeIn/fadeOut.
  4110. *
  4111. * @private
  4112. */
  4113. unlockShowing() {
  4114. this.removeClass('vjs-lock-showing');
  4115. }
  4116. /**
  4117. * Get the value of an attribute on the `Component`s element.
  4118. *
  4119. * @param {string} attribute
  4120. * Name of the attribute to get the value from.
  4121. *
  4122. * @return {string|null}
  4123. * - The value of the attribute that was asked for.
  4124. * - Can be an empty string on some browsers if the attribute does not exist
  4125. * or has no value
  4126. * - Most browsers will return null if the attribute does not exist or has
  4127. * no value.
  4128. *
  4129. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  4130. */
  4131. getAttribute(attribute) {
  4132. return getAttribute(this.el_, attribute);
  4133. }
  4134. /**
  4135. * Set the value of an attribute on the `Component`'s element
  4136. *
  4137. * @param {string} attribute
  4138. * Name of the attribute to set.
  4139. *
  4140. * @param {string} value
  4141. * Value to set the attribute to.
  4142. *
  4143. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4144. */
  4145. setAttribute(attribute, value) {
  4146. setAttribute(this.el_, attribute, value);
  4147. }
  4148. /**
  4149. * Remove an attribute from the `Component`s element.
  4150. *
  4151. * @param {string} attribute
  4152. * Name of the attribute to remove.
  4153. *
  4154. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4155. */
  4156. removeAttribute(attribute) {
  4157. removeAttribute(this.el_, attribute);
  4158. }
  4159. /**
  4160. * Get or set the width of the component based upon the CSS styles.
  4161. * See {@link Component#dimension} for more detailed information.
  4162. *
  4163. * @param {number|string} [num]
  4164. * The width that you want to set postfixed with '%', 'px' or nothing.
  4165. *
  4166. * @param {boolean} [skipListeners]
  4167. * Skip the componentresize event trigger
  4168. *
  4169. * @return {number|undefined}
  4170. * The width when getting, zero if there is no width
  4171. */
  4172. width(num, skipListeners) {
  4173. return this.dimension('width', num, skipListeners);
  4174. }
  4175. /**
  4176. * Get or set the height of the component based upon the CSS styles.
  4177. * See {@link Component#dimension} for more detailed information.
  4178. *
  4179. * @param {number|string} [num]
  4180. * The height that you want to set postfixed with '%', 'px' or nothing.
  4181. *
  4182. * @param {boolean} [skipListeners]
  4183. * Skip the componentresize event trigger
  4184. *
  4185. * @return {number|undefined}
  4186. * The height when getting, zero if there is no height
  4187. */
  4188. height(num, skipListeners) {
  4189. return this.dimension('height', num, skipListeners);
  4190. }
  4191. /**
  4192. * Set both the width and height of the `Component` element at the same time.
  4193. *
  4194. * @param {number|string} width
  4195. * Width to set the `Component`s element to.
  4196. *
  4197. * @param {number|string} height
  4198. * Height to set the `Component`s element to.
  4199. */
  4200. dimensions(width, height) {
  4201. // Skip componentresize listeners on width for optimization
  4202. this.width(width, true);
  4203. this.height(height);
  4204. }
  4205. /**
  4206. * Get or set width or height of the `Component` element. This is the shared code
  4207. * for the {@link Component#width} and {@link Component#height}.
  4208. *
  4209. * Things to know:
  4210. * - If the width or height in an number this will return the number postfixed with 'px'.
  4211. * - If the width/height is a percent this will return the percent postfixed with '%'
  4212. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4213. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4214. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4215. * for more information
  4216. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4217. * and {@link {Component#currentHeight}
  4218. *
  4219. * @fires Component#componentresize
  4220. *
  4221. * @param {string} widthOrHeight
  4222. 8 'width' or 'height'
  4223. *
  4224. * @param {number|string} [num]
  4225. 8 New dimension
  4226. *
  4227. * @param {boolean} [skipListeners]
  4228. * Skip componentresize event trigger
  4229. *
  4230. * @return {number|undefined}
  4231. * The dimension when getting or 0 if unset
  4232. */
  4233. dimension(widthOrHeight, num, skipListeners) {
  4234. if (num !== undefined) {
  4235. // Set to zero if null or literally NaN (NaN !== NaN)
  4236. if (num === null || num !== num) {
  4237. num = 0;
  4238. }
  4239. // Check if using css width/height (% or px) and adjust
  4240. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4241. this.el_.style[widthOrHeight] = num;
  4242. } else if (num === 'auto') {
  4243. this.el_.style[widthOrHeight] = '';
  4244. } else {
  4245. this.el_.style[widthOrHeight] = num + 'px';
  4246. }
  4247. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4248. if (!skipListeners) {
  4249. /**
  4250. * Triggered when a component is resized.
  4251. *
  4252. * @event Component#componentresize
  4253. * @type {Event}
  4254. */
  4255. this.trigger('componentresize');
  4256. }
  4257. return;
  4258. }
  4259. // Not setting a value, so getting it
  4260. // Make sure element exists
  4261. if (!this.el_) {
  4262. return 0;
  4263. }
  4264. // Get dimension value from style
  4265. const val = this.el_.style[widthOrHeight];
  4266. const pxIndex = val.indexOf('px');
  4267. if (pxIndex !== -1) {
  4268. // Return the pixel value with no 'px'
  4269. return parseInt(val.slice(0, pxIndex), 10);
  4270. }
  4271. // No px so using % or no style was set, so falling back to offsetWidth/height
  4272. // If component has display:none, offset will return 0
  4273. // TODO: handle display:none and no dimension style using px
  4274. return parseInt(this.el_['offset' + toTitleCase(widthOrHeight)], 10);
  4275. }
  4276. /**
  4277. * Get the computed width or the height of the component's element.
  4278. *
  4279. * Uses `window.getComputedStyle`.
  4280. *
  4281. * @param {string} widthOrHeight
  4282. * A string containing 'width' or 'height'. Whichever one you want to get.
  4283. *
  4284. * @return {number}
  4285. * The dimension that gets asked for or 0 if nothing was set
  4286. * for that dimension.
  4287. */
  4288. currentDimension(widthOrHeight) {
  4289. let computedWidthOrHeight = 0;
  4290. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4291. throw new Error('currentDimension only accepts width or height value');
  4292. }
  4293. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4294. // remove 'px' from variable and parse as integer
  4295. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4296. // if the computed value is still 0, it's possible that the browser is lying
  4297. // and we want to check the offset values.
  4298. // This code also runs wherever getComputedStyle doesn't exist.
  4299. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4300. const rule = `offset${toTitleCase(widthOrHeight)}`;
  4301. computedWidthOrHeight = this.el_[rule];
  4302. }
  4303. return computedWidthOrHeight;
  4304. }
  4305. /**
  4306. * An object that contains width and height values of the `Component`s
  4307. * computed style. Uses `window.getComputedStyle`.
  4308. *
  4309. * @typedef {Object} Component~DimensionObject
  4310. *
  4311. * @property {number} width
  4312. * The width of the `Component`s computed style.
  4313. *
  4314. * @property {number} height
  4315. * The height of the `Component`s computed style.
  4316. */
  4317. /**
  4318. * Get an object that contains computed width and height values of the
  4319. * component's element.
  4320. *
  4321. * Uses `window.getComputedStyle`.
  4322. *
  4323. * @return {Component~DimensionObject}
  4324. * The computed dimensions of the component's element.
  4325. */
  4326. currentDimensions() {
  4327. return {
  4328. width: this.currentDimension('width'),
  4329. height: this.currentDimension('height')
  4330. };
  4331. }
  4332. /**
  4333. * Get the computed width of the component's element.
  4334. *
  4335. * Uses `window.getComputedStyle`.
  4336. *
  4337. * @return {number}
  4338. * The computed width of the component's element.
  4339. */
  4340. currentWidth() {
  4341. return this.currentDimension('width');
  4342. }
  4343. /**
  4344. * Get the computed height of the component's element.
  4345. *
  4346. * Uses `window.getComputedStyle`.
  4347. *
  4348. * @return {number}
  4349. * The computed height of the component's element.
  4350. */
  4351. currentHeight() {
  4352. return this.currentDimension('height');
  4353. }
  4354. /**
  4355. * Retrieves the position and size information of the component's element.
  4356. *
  4357. * @return {Object} An object with `boundingClientRect` and `center` properties.
  4358. * - `boundingClientRect`: An object with properties `x`, `y`, `width`,
  4359. * `height`, `top`, `right`, `bottom`, and `left`, representing
  4360. * the bounding rectangle of the element.
  4361. * - `center`: An object with properties `x` and `y`, representing
  4362. * the center point of the element. `width` and `height` are set to 0.
  4363. */
  4364. getPositions() {
  4365. const rect = this.el_.getBoundingClientRect();
  4366. // Creating objects that mirror DOMRectReadOnly for boundingClientRect and center
  4367. const boundingClientRect = {
  4368. x: rect.x,
  4369. y: rect.y,
  4370. width: rect.width,
  4371. height: rect.height,
  4372. top: rect.top,
  4373. right: rect.right,
  4374. bottom: rect.bottom,
  4375. left: rect.left
  4376. };
  4377. // Calculating the center position
  4378. const center = {
  4379. x: rect.left + rect.width / 2,
  4380. y: rect.top + rect.height / 2,
  4381. width: 0,
  4382. height: 0,
  4383. top: rect.top + rect.height / 2,
  4384. right: rect.left + rect.width / 2,
  4385. bottom: rect.top + rect.height / 2,
  4386. left: rect.left + rect.width / 2
  4387. };
  4388. return {
  4389. boundingClientRect,
  4390. center
  4391. };
  4392. }
  4393. /**
  4394. * Set the focus to this component
  4395. */
  4396. focus() {
  4397. this.el_.focus();
  4398. }
  4399. /**
  4400. * Remove the focus from this component
  4401. */
  4402. blur() {
  4403. this.el_.blur();
  4404. }
  4405. /**
  4406. * When this Component receives a `keydown` event which it does not process,
  4407. * it passes the event to the Player for handling.
  4408. *
  4409. * @param {KeyboardEvent} event
  4410. * The `keydown` event that caused this function to be called.
  4411. */
  4412. handleKeyDown(event) {
  4413. if (this.player_) {
  4414. // We only stop propagation here because we want unhandled events to fall
  4415. // back to the browser. Exclude Tab for focus trapping, exclude also when spatialNavigation is enabled.
  4416. if (event.key !== 'Tab' && !(this.player_.options_.playerOptions.spatialNavigation && this.player_.options_.playerOptions.spatialNavigation.enabled)) {
  4417. event.stopPropagation();
  4418. }
  4419. this.player_.handleKeyDown(event);
  4420. }
  4421. }
  4422. /**
  4423. * Many components used to have a `handleKeyPress` method, which was poorly
  4424. * named because it listened to a `keydown` event. This method name now
  4425. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4426. * will not see their method calls stop working.
  4427. *
  4428. * @param {KeyboardEvent} event
  4429. * The event that caused this function to be called.
  4430. */
  4431. handleKeyPress(event) {
  4432. this.handleKeyDown(event);
  4433. }
  4434. /**
  4435. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4436. * support toggling the controls through a tap on the video. They get enabled
  4437. * because every sub-component would have extra overhead otherwise.
  4438. *
  4439. * @protected
  4440. * @fires Component#tap
  4441. * @listens Component#touchstart
  4442. * @listens Component#touchmove
  4443. * @listens Component#touchleave
  4444. * @listens Component#touchcancel
  4445. * @listens Component#touchend
  4446. */
  4447. emitTapEvents() {
  4448. // Track the start time so we can determine how long the touch lasted
  4449. let touchStart = 0;
  4450. let firstTouch = null;
  4451. // Maximum movement allowed during a touch event to still be considered a tap
  4452. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4453. // so 10 seems like a nice, round number.
  4454. const tapMovementThreshold = 10;
  4455. // The maximum length a touch can be while still being considered a tap
  4456. const touchTimeThreshold = 200;
  4457. let couldBeTap;
  4458. this.on('touchstart', function (event) {
  4459. // If more than one finger, don't consider treating this as a click
  4460. if (event.touches.length === 1) {
  4461. // Copy pageX/pageY from the object
  4462. firstTouch = {
  4463. pageX: event.touches[0].pageX,
  4464. pageY: event.touches[0].pageY
  4465. };
  4466. // Record start time so we can detect a tap vs. "touch and hold"
  4467. touchStart = window.performance.now();
  4468. // Reset couldBeTap tracking
  4469. couldBeTap = true;
  4470. }
  4471. });
  4472. this.on('touchmove', function (event) {
  4473. // If more than one finger, don't consider treating this as a click
  4474. if (event.touches.length > 1) {
  4475. couldBeTap = false;
  4476. } else if (firstTouch) {
  4477. // Some devices will throw touchmoves for all but the slightest of taps.
  4478. // So, if we moved only a small distance, this could still be a tap
  4479. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4480. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4481. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4482. if (touchDistance > tapMovementThreshold) {
  4483. couldBeTap = false;
  4484. }
  4485. }
  4486. });
  4487. const noTap = function () {
  4488. couldBeTap = false;
  4489. };
  4490. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4491. this.on('touchleave', noTap);
  4492. this.on('touchcancel', noTap);
  4493. // When the touch ends, measure how long it took and trigger the appropriate
  4494. // event
  4495. this.on('touchend', function (event) {
  4496. firstTouch = null;
  4497. // Proceed only if the touchmove/leave/cancel event didn't happen
  4498. if (couldBeTap === true) {
  4499. // Measure how long the touch lasted
  4500. const touchTime = window.performance.now() - touchStart;
  4501. // Make sure the touch was less than the threshold to be considered a tap
  4502. if (touchTime < touchTimeThreshold) {
  4503. // Don't let browser turn this into a click
  4504. event.preventDefault();
  4505. /**
  4506. * Triggered when a `Component` is tapped.
  4507. *
  4508. * @event Component#tap
  4509. * @type {MouseEvent}
  4510. */
  4511. this.trigger('tap');
  4512. // It may be good to copy the touchend event object and change the
  4513. // type to tap, if the other event properties aren't exact after
  4514. // Events.fixEvent runs (e.g. event.target)
  4515. }
  4516. }
  4517. });
  4518. }
  4519. /**
  4520. * This function reports user activity whenever touch events happen. This can get
  4521. * turned off by any sub-components that wants touch events to act another way.
  4522. *
  4523. * Report user touch activity when touch events occur. User activity gets used to
  4524. * determine when controls should show/hide. It is simple when it comes to mouse
  4525. * events, because any mouse event should show the controls. So we capture mouse
  4526. * events that bubble up to the player and report activity when that happens.
  4527. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4528. * controls. So touch events can't help us at the player level either.
  4529. *
  4530. * User activity gets checked asynchronously. So what could happen is a tap event
  4531. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4532. * the player. Which, if it reported user activity, would turn the controls right
  4533. * back on. We also don't want to completely block touch events from bubbling up.
  4534. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4535. * controls back on.
  4536. *
  4537. * @listens Component#touchstart
  4538. * @listens Component#touchmove
  4539. * @listens Component#touchend
  4540. * @listens Component#touchcancel
  4541. */
  4542. enableTouchActivity() {
  4543. // Don't continue if the root player doesn't support reporting user activity
  4544. if (!this.player() || !this.player().reportUserActivity) {
  4545. return;
  4546. }
  4547. // listener for reporting that the user is active
  4548. const report = bind_(this.player(), this.player().reportUserActivity);
  4549. let touchHolding;
  4550. this.on('touchstart', function () {
  4551. report();
  4552. // For as long as the they are touching the device or have their mouse down,
  4553. // we consider them active even if they're not moving their finger or mouse.
  4554. // So we want to continue to update that they are active
  4555. this.clearInterval(touchHolding);
  4556. // report at the same interval as activityCheck
  4557. touchHolding = this.setInterval(report, 250);
  4558. });
  4559. const touchEnd = function (event) {
  4560. report();
  4561. // stop the interval that maintains activity if the touch is holding
  4562. this.clearInterval(touchHolding);
  4563. };
  4564. this.on('touchmove', report);
  4565. this.on('touchend', touchEnd);
  4566. this.on('touchcancel', touchEnd);
  4567. }
  4568. /**
  4569. * A callback that has no parameters and is bound into `Component`s context.
  4570. *
  4571. * @callback Component~GenericCallback
  4572. * @this Component
  4573. */
  4574. /**
  4575. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4576. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4577. * instead though:
  4578. * 1. It gets cleared via {@link Component#clearTimeout} when
  4579. * {@link Component#dispose} gets called.
  4580. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4581. *
  4582. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4583. * will cause its dispose listener not to get cleaned up! Please use
  4584. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4585. *
  4586. * @param {Component~GenericCallback} fn
  4587. * The function that will be run after `timeout`.
  4588. *
  4589. * @param {number} timeout
  4590. * Timeout in milliseconds to delay before executing the specified function.
  4591. *
  4592. * @return {number}
  4593. * Returns a timeout ID that gets used to identify the timeout. It can also
  4594. * get used in {@link Component#clearTimeout} to clear the timeout that
  4595. * was set.
  4596. *
  4597. * @listens Component#dispose
  4598. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4599. */
  4600. setTimeout(fn, timeout) {
  4601. // declare as variables so they are properly available in timeout function
  4602. // eslint-disable-next-line
  4603. var timeoutId;
  4604. fn = bind_(this, fn);
  4605. this.clearTimersOnDispose_();
  4606. timeoutId = window.setTimeout(() => {
  4607. if (this.setTimeoutIds_.has(timeoutId)) {
  4608. this.setTimeoutIds_.delete(timeoutId);
  4609. }
  4610. fn();
  4611. }, timeout);
  4612. this.setTimeoutIds_.add(timeoutId);
  4613. return timeoutId;
  4614. }
  4615. /**
  4616. * Clears a timeout that gets created via `window.setTimeout` or
  4617. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4618. * use this function instead of `window.clearTimout`. If you don't your dispose
  4619. * listener will not get cleaned up until {@link Component#dispose}!
  4620. *
  4621. * @param {number} timeoutId
  4622. * The id of the timeout to clear. The return value of
  4623. * {@link Component#setTimeout} or `window.setTimeout`.
  4624. *
  4625. * @return {number}
  4626. * Returns the timeout id that was cleared.
  4627. *
  4628. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4629. */
  4630. clearTimeout(timeoutId) {
  4631. if (this.setTimeoutIds_.has(timeoutId)) {
  4632. this.setTimeoutIds_.delete(timeoutId);
  4633. window.clearTimeout(timeoutId);
  4634. }
  4635. return timeoutId;
  4636. }
  4637. /**
  4638. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4639. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4640. * 1. It gets cleared via {@link Component#clearInterval} when
  4641. * {@link Component#dispose} gets called.
  4642. * 2. The function callback will be a {@link Component~GenericCallback}
  4643. *
  4644. * @param {Component~GenericCallback} fn
  4645. * The function to run every `x` seconds.
  4646. *
  4647. * @param {number} interval
  4648. * Execute the specified function every `x` milliseconds.
  4649. *
  4650. * @return {number}
  4651. * Returns an id that can be used to identify the interval. It can also be be used in
  4652. * {@link Component#clearInterval} to clear the interval.
  4653. *
  4654. * @listens Component#dispose
  4655. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4656. */
  4657. setInterval(fn, interval) {
  4658. fn = bind_(this, fn);
  4659. this.clearTimersOnDispose_();
  4660. const intervalId = window.setInterval(fn, interval);
  4661. this.setIntervalIds_.add(intervalId);
  4662. return intervalId;
  4663. }
  4664. /**
  4665. * Clears an interval that gets created via `window.setInterval` or
  4666. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4667. * use this function instead of `window.clearInterval`. If you don't your dispose
  4668. * listener will not get cleaned up until {@link Component#dispose}!
  4669. *
  4670. * @param {number} intervalId
  4671. * The id of the interval to clear. The return value of
  4672. * {@link Component#setInterval} or `window.setInterval`.
  4673. *
  4674. * @return {number}
  4675. * Returns the interval id that was cleared.
  4676. *
  4677. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4678. */
  4679. clearInterval(intervalId) {
  4680. if (this.setIntervalIds_.has(intervalId)) {
  4681. this.setIntervalIds_.delete(intervalId);
  4682. window.clearInterval(intervalId);
  4683. }
  4684. return intervalId;
  4685. }
  4686. /**
  4687. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4688. * with a few extra bonuses:
  4689. *
  4690. * - Supports browsers that do not support rAF by falling back to
  4691. * {@link Component#setTimeout}.
  4692. *
  4693. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4694. * bound to the component).
  4695. *
  4696. * - Automatic cancellation of the rAF callback is handled if the component
  4697. * is disposed before it is called.
  4698. *
  4699. * @param {Component~GenericCallback} fn
  4700. * A function that will be bound to this component and executed just
  4701. * before the browser's next repaint.
  4702. *
  4703. * @return {number}
  4704. * Returns an rAF ID that gets used to identify the timeout. It can
  4705. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4706. * the animation frame callback.
  4707. *
  4708. * @listens Component#dispose
  4709. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4710. */
  4711. requestAnimationFrame(fn) {
  4712. this.clearTimersOnDispose_();
  4713. // declare as variables so they are properly available in rAF function
  4714. // eslint-disable-next-line
  4715. var id;
  4716. fn = bind_(this, fn);
  4717. id = window.requestAnimationFrame(() => {
  4718. if (this.rafIds_.has(id)) {
  4719. this.rafIds_.delete(id);
  4720. }
  4721. fn();
  4722. });
  4723. this.rafIds_.add(id);
  4724. return id;
  4725. }
  4726. /**
  4727. * Request an animation frame, but only one named animation
  4728. * frame will be queued. Another will never be added until
  4729. * the previous one finishes.
  4730. *
  4731. * @param {string} name
  4732. * The name to give this requestAnimationFrame
  4733. *
  4734. * @param {Component~GenericCallback} fn
  4735. * A function that will be bound to this component and executed just
  4736. * before the browser's next repaint.
  4737. */
  4738. requestNamedAnimationFrame(name, fn) {
  4739. if (this.namedRafs_.has(name)) {
  4740. this.cancelNamedAnimationFrame(name);
  4741. }
  4742. this.clearTimersOnDispose_();
  4743. fn = bind_(this, fn);
  4744. const id = this.requestAnimationFrame(() => {
  4745. fn();
  4746. if (this.namedRafs_.has(name)) {
  4747. this.namedRafs_.delete(name);
  4748. }
  4749. });
  4750. this.namedRafs_.set(name, id);
  4751. return name;
  4752. }
  4753. /**
  4754. * Cancels a current named animation frame if it exists.
  4755. *
  4756. * @param {string} name
  4757. * The name of the requestAnimationFrame to cancel.
  4758. */
  4759. cancelNamedAnimationFrame(name) {
  4760. if (!this.namedRafs_.has(name)) {
  4761. return;
  4762. }
  4763. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4764. this.namedRafs_.delete(name);
  4765. }
  4766. /**
  4767. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4768. * (rAF).
  4769. *
  4770. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4771. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4772. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4773. *
  4774. * @param {number} id
  4775. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4776. *
  4777. * @return {number}
  4778. * Returns the rAF ID that was cleared.
  4779. *
  4780. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4781. */
  4782. cancelAnimationFrame(id) {
  4783. if (this.rafIds_.has(id)) {
  4784. this.rafIds_.delete(id);
  4785. window.cancelAnimationFrame(id);
  4786. }
  4787. return id;
  4788. }
  4789. /**
  4790. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4791. * and `setInterval`, clearing on dispose.
  4792. *
  4793. * > Previously each timer added and removed dispose listeners on it's own.
  4794. * For better performance it was decided to batch them all, and use `Set`s
  4795. * to track outstanding timer ids.
  4796. *
  4797. * @private
  4798. */
  4799. clearTimersOnDispose_() {
  4800. if (this.clearingTimersOnDispose_) {
  4801. return;
  4802. }
  4803. this.clearingTimersOnDispose_ = true;
  4804. this.one('dispose', () => {
  4805. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4806. // for a `Set` key will actually be the value again
  4807. // so forEach((val, val) =>` but for maps we want to use
  4808. // the key.
  4809. this[idName].forEach((val, key) => this[cancelName](key));
  4810. });
  4811. this.clearingTimersOnDispose_ = false;
  4812. });
  4813. }
  4814. /**
  4815. * Decide whether an element is actually disabled or not.
  4816. *
  4817. * @function isActuallyDisabled
  4818. * @param element {Node}
  4819. * @return {boolean}
  4820. *
  4821. * @see {@link https://html.spec.whatwg.org/multipage/semantics-other.html#concept-element-disabled}
  4822. */
  4823. getIsDisabled() {
  4824. return Boolean(this.el_.disabled);
  4825. }
  4826. /**
  4827. * Decide whether the element is expressly inert or not.
  4828. *
  4829. * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#expressly-inert}
  4830. * @function isExpresslyInert
  4831. * @param element {Node}
  4832. * @return {boolean}
  4833. */
  4834. getIsExpresslyInert() {
  4835. return this.el_.inert && !this.el_.ownerDocument.documentElement.inert;
  4836. }
  4837. /**
  4838. * Determine whether or not this component can be considered as focusable component.
  4839. *
  4840. * @param {HTMLElement} el - The HTML element representing the component.
  4841. * @return {boolean}
  4842. * If the component can be focused, will be `true`. Otherwise, `false`.
  4843. */
  4844. getIsFocusable(el) {
  4845. const element = el || this.el_;
  4846. return element.tabIndex >= 0 && !(this.getIsDisabled() || this.getIsExpresslyInert());
  4847. }
  4848. /**
  4849. * Determine whether or not this component is currently visible/enabled/etc...
  4850. *
  4851. * @param {HTMLElement} el - The HTML element representing the component.
  4852. * @return {boolean}
  4853. * If the component can is currently visible & enabled, will be `true`. Otherwise, `false`.
  4854. */
  4855. getIsAvailableToBeFocused(el) {
  4856. /**
  4857. * Decide the style property of this element is specified whether it's visible or not.
  4858. *
  4859. * @function isVisibleStyleProperty
  4860. * @param element {CSSStyleDeclaration}
  4861. * @return {boolean}
  4862. */
  4863. function isVisibleStyleProperty(element) {
  4864. const elementStyle = window.getComputedStyle(element, null);
  4865. const thisVisibility = elementStyle.getPropertyValue('visibility');
  4866. const thisDisplay = elementStyle.getPropertyValue('display');
  4867. const invisibleStyle = ['hidden', 'collapse'];
  4868. return thisDisplay !== 'none' && !invisibleStyle.includes(thisVisibility);
  4869. }
  4870. /**
  4871. * Decide whether the element is being rendered or not.
  4872. * 1. If an element has the style as "visibility: hidden | collapse" or "display: none", it is not being rendered.
  4873. * 2. If an element has the style as "opacity: 0", it is not being rendered.(that is, invisible).
  4874. * 3. If width and height of an element are explicitly set to 0, it is not being rendered.
  4875. * 4. If a parent element is hidden, an element itself is not being rendered.
  4876. * (CSS visibility property and display property are inherited.)
  4877. *
  4878. * @see {@link https://html.spec.whatwg.org/multipage/rendering.html#being-rendered}
  4879. * @function isBeingRendered
  4880. * @param element {Node}
  4881. * @return {boolean}
  4882. */
  4883. function isBeingRendered(element) {
  4884. if (!isVisibleStyleProperty(element.parentElement)) {
  4885. return false;
  4886. }
  4887. if (!isVisibleStyleProperty(element) || element.style.opacity === '0' || window.getComputedStyle(element).height === '0px' || window.getComputedStyle(element).width === '0px') {
  4888. return false;
  4889. }
  4890. return true;
  4891. }
  4892. /**
  4893. * Determine if the element is visible for the user or not.
  4894. * 1. If an element sum of its offsetWidth, offsetHeight, height and width is less than 1 is not visible.
  4895. * 2. If elementCenter.x is less than is not visible.
  4896. * 3. If elementCenter.x is more than the document's width is not visible.
  4897. * 4. If elementCenter.y is less than 0 is not visible.
  4898. * 5. If elementCenter.y is the document's height is not visible.
  4899. *
  4900. * @function isVisible
  4901. * @param element {Node}
  4902. * @return {boolean}
  4903. */
  4904. function isVisible(element) {
  4905. if (element.offsetWidth + element.offsetHeight + element.getBoundingClientRect().height + element.getBoundingClientRect().width === 0) {
  4906. return false;
  4907. }
  4908. // Define elementCenter object with props of x and y
  4909. // x: Left position relative to the viewport plus element's width (no margin) divided between 2.
  4910. // y: Top position relative to the viewport plus element's height (no margin) divided between 2.
  4911. const elementCenter = {
  4912. x: element.getBoundingClientRect().left + element.offsetWidth / 2,
  4913. y: element.getBoundingClientRect().top + element.offsetHeight / 2
  4914. };
  4915. if (elementCenter.x < 0) {
  4916. return false;
  4917. }
  4918. if (elementCenter.x > (document.documentElement.clientWidth || window.innerWidth)) {
  4919. return false;
  4920. }
  4921. if (elementCenter.y < 0) {
  4922. return false;
  4923. }
  4924. if (elementCenter.y > (document.documentElement.clientHeight || window.innerHeight)) {
  4925. return false;
  4926. }
  4927. let pointContainer = document.elementFromPoint(elementCenter.x, elementCenter.y);
  4928. while (pointContainer) {
  4929. if (pointContainer === element) {
  4930. return true;
  4931. }
  4932. if (pointContainer.parentNode) {
  4933. pointContainer = pointContainer.parentNode;
  4934. } else {
  4935. return false;
  4936. }
  4937. }
  4938. }
  4939. // If no DOM element was passed as argument use this component's element.
  4940. if (!el) {
  4941. el = this.el();
  4942. }
  4943. // If element is visible, is being rendered & either does not have a parent element or its tabIndex is not negative.
  4944. if (isVisible(el) && isBeingRendered(el) && (!el.parentElement || el.tabIndex >= 0)) {
  4945. return true;
  4946. }
  4947. return false;
  4948. }
  4949. /**
  4950. * Register a `Component` with `videojs` given the name and the component.
  4951. *
  4952. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4953. * should be registered using {@link Tech.registerTech} or
  4954. * {@link videojs:videojs.registerTech}.
  4955. *
  4956. * > NOTE: This function can also be seen on videojs as
  4957. * {@link videojs:videojs.registerComponent}.
  4958. *
  4959. * @param {string} name
  4960. * The name of the `Component` to register.
  4961. *
  4962. * @param {Component} ComponentToRegister
  4963. * The `Component` class to register.
  4964. *
  4965. * @return {Component}
  4966. * The `Component` that was registered.
  4967. */
  4968. static registerComponent(name, ComponentToRegister) {
  4969. if (typeof name !== 'string' || !name) {
  4970. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4971. }
  4972. const Tech = Component.getComponent('Tech');
  4973. // We need to make sure this check is only done if Tech has been registered.
  4974. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4975. const isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4976. if (isTech || !isComp) {
  4977. let reason;
  4978. if (isTech) {
  4979. reason = 'techs must be registered using Tech.registerTech()';
  4980. } else {
  4981. reason = 'must be a Component subclass';
  4982. }
  4983. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4984. }
  4985. name = toTitleCase(name);
  4986. if (!Component.components_) {
  4987. Component.components_ = {};
  4988. }
  4989. const Player = Component.getComponent('Player');
  4990. if (name === 'Player' && Player && Player.players) {
  4991. const players = Player.players;
  4992. const playerNames = Object.keys(players);
  4993. // If we have players that were disposed, then their name will still be
  4994. // in Players.players. So, we must loop through and verify that the value
  4995. // for each item is not null. This allows registration of the Player component
  4996. // after all players have been disposed or before any were created.
  4997. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4998. throw new Error('Can not register Player component after player has been created.');
  4999. }
  5000. }
  5001. Component.components_[name] = ComponentToRegister;
  5002. Component.components_[toLowerCase(name)] = ComponentToRegister;
  5003. return ComponentToRegister;
  5004. }
  5005. /**
  5006. * Get a `Component` based on the name it was registered with.
  5007. *
  5008. * @param {string} name
  5009. * The Name of the component to get.
  5010. *
  5011. * @return {typeof Component}
  5012. * The `Component` that got registered under the given name.
  5013. */
  5014. static getComponent(name) {
  5015. if (!name || !Component.components_) {
  5016. return;
  5017. }
  5018. return Component.components_[name];
  5019. }
  5020. }
  5021. Component.registerComponent('Component', Component);
  5022. /**
  5023. * @file time.js
  5024. * @module time
  5025. */
  5026. /**
  5027. * Returns the time for the specified index at the start or end
  5028. * of a TimeRange object.
  5029. *
  5030. * @typedef {Function} TimeRangeIndex
  5031. *
  5032. * @param {number} [index=0]
  5033. * The range number to return the time for.
  5034. *
  5035. * @return {number}
  5036. * The time offset at the specified index.
  5037. *
  5038. * @deprecated The index argument must be provided.
  5039. * In the future, leaving it out will throw an error.
  5040. */
  5041. /**
  5042. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  5043. *
  5044. * @typedef {Object} TimeRange
  5045. *
  5046. * @property {number} length
  5047. * The number of time ranges represented by this object.
  5048. *
  5049. * @property {module:time~TimeRangeIndex} start
  5050. * Returns the time offset at which a specified time range begins.
  5051. *
  5052. * @property {module:time~TimeRangeIndex} end
  5053. * Returns the time offset at which a specified time range ends.
  5054. *
  5055. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  5056. */
  5057. /**
  5058. * Check if any of the time ranges are over the maximum index.
  5059. *
  5060. * @private
  5061. * @param {string} fnName
  5062. * The function name to use for logging
  5063. *
  5064. * @param {number} index
  5065. * The index to check
  5066. *
  5067. * @param {number} maxIndex
  5068. * The maximum possible index
  5069. *
  5070. * @throws {Error} if the timeRanges provided are over the maxIndex
  5071. */
  5072. function rangeCheck(fnName, index, maxIndex) {
  5073. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  5074. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  5075. }
  5076. }
  5077. /**
  5078. * Get the time for the specified index at the start or end
  5079. * of a TimeRange object.
  5080. *
  5081. * @private
  5082. * @param {string} fnName
  5083. * The function name to use for logging
  5084. *
  5085. * @param {string} valueIndex
  5086. * The property that should be used to get the time. should be
  5087. * 'start' or 'end'
  5088. *
  5089. * @param {Array} ranges
  5090. * An array of time ranges
  5091. *
  5092. * @param {Array} [rangeIndex=0]
  5093. * The index to start the search at
  5094. *
  5095. * @return {number}
  5096. * The time that offset at the specified index.
  5097. *
  5098. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  5099. * @throws {Error} if rangeIndex is more than the length of ranges
  5100. */
  5101. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  5102. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  5103. return ranges[rangeIndex][valueIndex];
  5104. }
  5105. /**
  5106. * Create a time range object given ranges of time.
  5107. *
  5108. * @private
  5109. * @param {Array} [ranges]
  5110. * An array of time ranges.
  5111. *
  5112. * @return {TimeRange}
  5113. */
  5114. function createTimeRangesObj(ranges) {
  5115. let timeRangesObj;
  5116. if (ranges === undefined || ranges.length === 0) {
  5117. timeRangesObj = {
  5118. length: 0,
  5119. start() {
  5120. throw new Error('This TimeRanges object is empty');
  5121. },
  5122. end() {
  5123. throw new Error('This TimeRanges object is empty');
  5124. }
  5125. };
  5126. } else {
  5127. timeRangesObj = {
  5128. length: ranges.length,
  5129. start: getRange.bind(null, 'start', 0, ranges),
  5130. end: getRange.bind(null, 'end', 1, ranges)
  5131. };
  5132. }
  5133. if (window.Symbol && window.Symbol.iterator) {
  5134. timeRangesObj[window.Symbol.iterator] = () => (ranges || []).values();
  5135. }
  5136. return timeRangesObj;
  5137. }
  5138. /**
  5139. * Create a `TimeRange` object which mimics an
  5140. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  5141. *
  5142. * @param {number|Array[]} start
  5143. * The start of a single range (a number) or an array of ranges (an
  5144. * array of arrays of two numbers each).
  5145. *
  5146. * @param {number} end
  5147. * The end of a single range. Cannot be used with the array form of
  5148. * the `start` argument.
  5149. *
  5150. * @return {TimeRange}
  5151. */
  5152. function createTimeRanges(start, end) {
  5153. if (Array.isArray(start)) {
  5154. return createTimeRangesObj(start);
  5155. } else if (start === undefined || end === undefined) {
  5156. return createTimeRangesObj();
  5157. }
  5158. return createTimeRangesObj([[start, end]]);
  5159. }
  5160. /**
  5161. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  5162. * seconds) will force a number of leading zeros to cover the length of the
  5163. * guide.
  5164. *
  5165. * @private
  5166. * @param {number} seconds
  5167. * Number of seconds to be turned into a string
  5168. *
  5169. * @param {number} guide
  5170. * Number (in seconds) to model the string after
  5171. *
  5172. * @return {string}
  5173. * Time formatted as H:MM:SS or M:SS
  5174. */
  5175. const defaultImplementation = function (seconds, guide) {
  5176. seconds = seconds < 0 ? 0 : seconds;
  5177. let s = Math.floor(seconds % 60);
  5178. let m = Math.floor(seconds / 60 % 60);
  5179. let h = Math.floor(seconds / 3600);
  5180. const gm = Math.floor(guide / 60 % 60);
  5181. const gh = Math.floor(guide / 3600);
  5182. // handle invalid times
  5183. if (isNaN(seconds) || seconds === Infinity) {
  5184. // '-' is false for all relational operators (e.g. <, >=) so this setting
  5185. // will add the minimum number of fields specified by the guide
  5186. h = m = s = '-';
  5187. }
  5188. // Check if we need to show hours
  5189. h = h > 0 || gh > 0 ? h + ':' : '';
  5190. // If hours are showing, we may need to add a leading zero.
  5191. // Always show at least one digit of minutes.
  5192. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  5193. // Check if leading zero is need for seconds
  5194. s = s < 10 ? '0' + s : s;
  5195. return h + m + s;
  5196. };
  5197. // Internal pointer to the current implementation.
  5198. let implementation = defaultImplementation;
  5199. /**
  5200. * Replaces the default formatTime implementation with a custom implementation.
  5201. *
  5202. * @param {Function} customImplementation
  5203. * A function which will be used in place of the default formatTime
  5204. * implementation. Will receive the current time in seconds and the
  5205. * guide (in seconds) as arguments.
  5206. */
  5207. function setFormatTime(customImplementation) {
  5208. implementation = customImplementation;
  5209. }
  5210. /**
  5211. * Resets formatTime to the default implementation.
  5212. */
  5213. function resetFormatTime() {
  5214. implementation = defaultImplementation;
  5215. }
  5216. /**
  5217. * Delegates to either the default time formatting function or a custom
  5218. * function supplied via `setFormatTime`.
  5219. *
  5220. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  5221. * guide (in seconds) will force a number of leading zeros to cover the
  5222. * length of the guide.
  5223. *
  5224. * @example formatTime(125, 600) === "02:05"
  5225. * @param {number} seconds
  5226. * Number of seconds to be turned into a string
  5227. *
  5228. * @param {number} guide
  5229. * Number (in seconds) to model the string after
  5230. *
  5231. * @return {string}
  5232. * Time formatted as H:MM:SS or M:SS
  5233. */
  5234. function formatTime(seconds, guide = seconds) {
  5235. return implementation(seconds, guide);
  5236. }
  5237. var Time = /*#__PURE__*/Object.freeze({
  5238. __proto__: null,
  5239. createTimeRanges: createTimeRanges,
  5240. createTimeRange: createTimeRanges,
  5241. setFormatTime: setFormatTime,
  5242. resetFormatTime: resetFormatTime,
  5243. formatTime: formatTime
  5244. });
  5245. /**
  5246. * @file buffer.js
  5247. * @module buffer
  5248. */
  5249. /** @import { TimeRange } from './time' */
  5250. /**
  5251. * Compute the percentage of the media that has been buffered.
  5252. *
  5253. * @param {TimeRange} buffered
  5254. * The current `TimeRanges` object representing buffered time ranges
  5255. *
  5256. * @param {number} duration
  5257. * Total duration of the media
  5258. *
  5259. * @return {number}
  5260. * Percent buffered of the total duration in decimal form.
  5261. */
  5262. function bufferedPercent(buffered, duration) {
  5263. let bufferedDuration = 0;
  5264. let start;
  5265. let end;
  5266. if (!duration) {
  5267. return 0;
  5268. }
  5269. if (!buffered || !buffered.length) {
  5270. buffered = createTimeRanges(0, 0);
  5271. }
  5272. for (let i = 0; i < buffered.length; i++) {
  5273. start = buffered.start(i);
  5274. end = buffered.end(i);
  5275. // buffered end can be bigger than duration by a very small fraction
  5276. if (end > duration) {
  5277. end = duration;
  5278. }
  5279. bufferedDuration += end - start;
  5280. }
  5281. return bufferedDuration / duration;
  5282. }
  5283. /**
  5284. * @file media-error.js
  5285. */
  5286. /**
  5287. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  5288. *
  5289. * @param {number|string|Object|MediaError} value
  5290. * This can be of multiple types:
  5291. * - number: should be a standard error code
  5292. * - string: an error message (the code will be 0)
  5293. * - Object: arbitrary properties
  5294. * - `MediaError` (native): used to populate a video.js `MediaError` object
  5295. * - `MediaError` (video.js): will return itself if it's already a
  5296. * video.js `MediaError` object.
  5297. *
  5298. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  5299. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  5300. *
  5301. * @class MediaError
  5302. */
  5303. function MediaError(value) {
  5304. // Allow redundant calls to this constructor to avoid having `instanceof`
  5305. // checks peppered around the code.
  5306. if (value instanceof MediaError) {
  5307. return value;
  5308. }
  5309. if (typeof value === 'number') {
  5310. this.code = value;
  5311. } else if (typeof value === 'string') {
  5312. // default code is zero, so this is a custom error
  5313. this.message = value;
  5314. } else if (isObject(value)) {
  5315. // We assign the `code` property manually because native `MediaError` objects
  5316. // do not expose it as an own/enumerable property of the object.
  5317. if (typeof value.code === 'number') {
  5318. this.code = value.code;
  5319. }
  5320. Object.assign(this, value);
  5321. }
  5322. if (!this.message) {
  5323. this.message = MediaError.defaultMessages[this.code] || '';
  5324. }
  5325. }
  5326. /**
  5327. * The error code that refers two one of the defined `MediaError` types
  5328. *
  5329. * @type {Number}
  5330. */
  5331. MediaError.prototype.code = 0;
  5332. /**
  5333. * An optional message that to show with the error. Message is not part of the HTML5
  5334. * video spec but allows for more informative custom errors.
  5335. *
  5336. * @type {String}
  5337. */
  5338. MediaError.prototype.message = '';
  5339. /**
  5340. * An optional status code that can be set by plugins to allow even more detail about
  5341. * the error. For example a plugin might provide a specific HTTP status code and an
  5342. * error message for that code. Then when the plugin gets that error this class will
  5343. * know how to display an error message for it. This allows a custom message to show
  5344. * up on the `Player` error overlay.
  5345. *
  5346. * @type {Array}
  5347. */
  5348. MediaError.prototype.status = null;
  5349. /**
  5350. * An object containing an error type, as well as other information regarding the error.
  5351. *
  5352. * @typedef {{errorType: string, [key: string]: any}} ErrorMetadata
  5353. */
  5354. /**
  5355. * An optional object to give more detail about the error. This can be used to give
  5356. * a higher level of specificity to an error versus the more generic MediaError codes.
  5357. * `metadata` expects an `errorType` string that should align with the values from videojs.Error.
  5358. *
  5359. * @type {ErrorMetadata}
  5360. */
  5361. MediaError.prototype.metadata = null;
  5362. /**
  5363. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5364. * specification listed under {@link MediaError} for more information.
  5365. *
  5366. * @enum {array}
  5367. * @readonly
  5368. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5369. * @property {string} 1 - MEDIA_ERR_ABORTED
  5370. * @property {string} 2 - MEDIA_ERR_NETWORK
  5371. * @property {string} 3 - MEDIA_ERR_DECODE
  5372. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5373. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5374. */
  5375. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5376. /**
  5377. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5378. *
  5379. * @type {Array}
  5380. * @constant
  5381. */
  5382. MediaError.defaultMessages = {
  5383. 1: 'You aborted the media playback',
  5384. 2: 'A network error caused the media download to fail part-way.',
  5385. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5386. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5387. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5388. };
  5389. /**
  5390. * W3C error code for any custom error.
  5391. *
  5392. * @member MediaError#MEDIA_ERR_CUSTOM
  5393. * @constant {number}
  5394. * @default 0
  5395. */
  5396. MediaError.MEDIA_ERR_CUSTOM = 0;
  5397. /**
  5398. * W3C error code for any custom error.
  5399. *
  5400. * @member MediaError.MEDIA_ERR_CUSTOM
  5401. * @constant {number}
  5402. * @default 0
  5403. */
  5404. MediaError.prototype.MEDIA_ERR_CUSTOM = 0;
  5405. /**
  5406. * W3C error code for media error aborted.
  5407. *
  5408. * @member MediaError#MEDIA_ERR_ABORTED
  5409. * @constant {number}
  5410. * @default 1
  5411. */
  5412. MediaError.MEDIA_ERR_ABORTED = 1;
  5413. /**
  5414. * W3C error code for media error aborted.
  5415. *
  5416. * @member MediaError.MEDIA_ERR_ABORTED
  5417. * @constant {number}
  5418. * @default 1
  5419. */
  5420. MediaError.prototype.MEDIA_ERR_ABORTED = 1;
  5421. /**
  5422. * W3C error code for any network error.
  5423. *
  5424. * @member MediaError#MEDIA_ERR_NETWORK
  5425. * @constant {number}
  5426. * @default 2
  5427. */
  5428. MediaError.MEDIA_ERR_NETWORK = 2;
  5429. /**
  5430. * W3C error code for any network error.
  5431. *
  5432. * @member MediaError.MEDIA_ERR_NETWORK
  5433. * @constant {number}
  5434. * @default 2
  5435. */
  5436. MediaError.prototype.MEDIA_ERR_NETWORK = 2;
  5437. /**
  5438. * W3C error code for any decoding error.
  5439. *
  5440. * @member MediaError#MEDIA_ERR_DECODE
  5441. * @constant {number}
  5442. * @default 3
  5443. */
  5444. MediaError.MEDIA_ERR_DECODE = 3;
  5445. /**
  5446. * W3C error code for any decoding error.
  5447. *
  5448. * @member MediaError.MEDIA_ERR_DECODE
  5449. * @constant {number}
  5450. * @default 3
  5451. */
  5452. MediaError.prototype.MEDIA_ERR_DECODE = 3;
  5453. /**
  5454. * W3C error code for any time that a source is not supported.
  5455. *
  5456. * @member MediaError#MEDIA_ERR_SRC_NOT_SUPPORTED
  5457. * @constant {number}
  5458. * @default 4
  5459. */
  5460. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5461. /**
  5462. * W3C error code for any time that a source is not supported.
  5463. *
  5464. * @member MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
  5465. * @constant {number}
  5466. * @default 4
  5467. */
  5468. MediaError.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5469. /**
  5470. * W3C error code for any time that a source is encrypted.
  5471. *
  5472. * @member MediaError#MEDIA_ERR_ENCRYPTED
  5473. * @constant {number}
  5474. * @default 5
  5475. */
  5476. MediaError.MEDIA_ERR_ENCRYPTED = 5;
  5477. /**
  5478. * W3C error code for any time that a source is encrypted.
  5479. *
  5480. * @member MediaError.MEDIA_ERR_ENCRYPTED
  5481. * @constant {number}
  5482. * @default 5
  5483. */
  5484. MediaError.prototype.MEDIA_ERR_ENCRYPTED = 5;
  5485. /**
  5486. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5487. *
  5488. * @param {Object} value
  5489. * An object that may or may not be `Promise`-like.
  5490. *
  5491. * @return {boolean}
  5492. * Whether or not the object is `Promise`-like.
  5493. */
  5494. function isPromise(value) {
  5495. return value !== undefined && value !== null && typeof value.then === 'function';
  5496. }
  5497. /**
  5498. * Silence a Promise-like object.
  5499. *
  5500. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5501. * play promise" rejection error messages.
  5502. *
  5503. * @param {Object} value
  5504. * An object that may or may not be `Promise`-like.
  5505. */
  5506. function silencePromise(value) {
  5507. if (isPromise(value)) {
  5508. value.then(null, e => {});
  5509. }
  5510. }
  5511. /**
  5512. * @file text-track-list-converter.js Utilities for capturing text track state and
  5513. * re-creating tracks based on a capture.
  5514. *
  5515. * @module text-track-list-converter
  5516. */
  5517. /** @import Tech from '../tech/tech' */
  5518. /**
  5519. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5520. * represents the {@link TextTrack}'s state.
  5521. *
  5522. * @param {TextTrack} track
  5523. * The text track to query.
  5524. *
  5525. * @return {Object}
  5526. * A serializable javascript representation of the TextTrack.
  5527. * @private
  5528. */
  5529. const trackToJson_ = function (track) {
  5530. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {
  5531. if (track[prop]) {
  5532. acc[prop] = track[prop];
  5533. }
  5534. return acc;
  5535. }, {
  5536. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5537. return {
  5538. startTime: cue.startTime,
  5539. endTime: cue.endTime,
  5540. text: cue.text,
  5541. id: cue.id
  5542. };
  5543. })
  5544. });
  5545. return ret;
  5546. };
  5547. /**
  5548. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5549. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5550. * {@link text-track-list-converter:jsonToTextTracks}.
  5551. *
  5552. * @param {Tech} tech
  5553. * The tech object to query
  5554. *
  5555. * @return {Array}
  5556. * A serializable javascript representation of the {@link Tech}s
  5557. * {@link TextTrackList}.
  5558. */
  5559. const textTracksToJson = function (tech) {
  5560. const trackEls = tech.$$('track');
  5561. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5562. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5563. const json = trackToJson_(trackEl.track);
  5564. if (trackEl.src) {
  5565. json.src = trackEl.src;
  5566. }
  5567. return json;
  5568. });
  5569. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5570. return trackObjs.indexOf(track) === -1;
  5571. }).map(trackToJson_));
  5572. };
  5573. /**
  5574. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5575. * object {@link TextTrack} representations.
  5576. *
  5577. * @param {Array} json
  5578. * An array of `TextTrack` representation objects, like those that would be
  5579. * produced by `textTracksToJson`.
  5580. *
  5581. * @param {Tech} tech
  5582. * The `Tech` to create the `TextTrack`s on.
  5583. */
  5584. const jsonToTextTracks = function (json, tech) {
  5585. json.forEach(function (track) {
  5586. const addedTrack = tech.addRemoteTextTrack(track).track;
  5587. if (!track.src && track.cues) {
  5588. track.cues.forEach(cue => addedTrack.addCue(cue));
  5589. }
  5590. });
  5591. return tech.textTracks();
  5592. };
  5593. var textTrackConverter = {
  5594. textTracksToJson,
  5595. jsonToTextTracks,
  5596. trackToJson_
  5597. };
  5598. /**
  5599. * @file modal-dialog.js
  5600. */
  5601. /** @import Player from './player' */
  5602. /** @import { ContentDescriptor } from './utils/dom' */
  5603. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5604. /**
  5605. * The `ModalDialog` displays over the video and its controls, which blocks
  5606. * interaction with the player until it is closed.
  5607. *
  5608. * Modal dialogs include a "Close" button and will close when that button
  5609. * is activated - or when ESC is pressed anywhere.
  5610. *
  5611. * @extends Component
  5612. */
  5613. class ModalDialog extends Component {
  5614. /**
  5615. * Creates an instance of this class.
  5616. *
  5617. * @param {Player} player
  5618. * The `Player` that this class should be attached to.
  5619. *
  5620. * @param {Object} [options]
  5621. * The key/value store of player options.
  5622. *
  5623. * @param {ContentDescriptor} [options.content=undefined]
  5624. * Provide customized content for this modal.
  5625. *
  5626. * @param {string} [options.description]
  5627. * A text description for the modal, primarily for accessibility.
  5628. *
  5629. * @param {boolean} [options.fillAlways=false]
  5630. * Normally, modals are automatically filled only the first time
  5631. * they open. This tells the modal to refresh its content
  5632. * every time it opens.
  5633. *
  5634. * @param {string} [options.label]
  5635. * A text label for the modal, primarily for accessibility.
  5636. *
  5637. * @param {boolean} [options.pauseOnOpen=true]
  5638. * If `true`, playback will will be paused if playing when
  5639. * the modal opens, and resumed when it closes.
  5640. *
  5641. * @param {boolean} [options.temporary=true]
  5642. * If `true`, the modal can only be opened once; it will be
  5643. * disposed as soon as it's closed.
  5644. *
  5645. * @param {boolean} [options.uncloseable=false]
  5646. * If `true`, the user will not be able to close the modal
  5647. * through the UI in the normal ways. Programmatic closing is
  5648. * still possible.
  5649. */
  5650. constructor(player, options) {
  5651. super(player, options);
  5652. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5653. this.close_ = e => this.close(e);
  5654. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5655. this.closeable(!this.options_.uncloseable);
  5656. this.content(this.options_.content);
  5657. // Make sure the contentEl is defined AFTER any children are initialized
  5658. // because we only want the contents of the modal in the contentEl
  5659. // (not the UI elements like the close button).
  5660. this.contentEl_ = createEl('div', {
  5661. className: `${MODAL_CLASS_NAME}-content`
  5662. }, {
  5663. role: 'document'
  5664. });
  5665. this.descEl_ = createEl('p', {
  5666. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5667. id: this.el().getAttribute('aria-describedby')
  5668. });
  5669. textContent(this.descEl_, this.description());
  5670. this.el_.appendChild(this.descEl_);
  5671. this.el_.appendChild(this.contentEl_);
  5672. }
  5673. /**
  5674. * Create the `ModalDialog`'s DOM element
  5675. *
  5676. * @return {Element}
  5677. * The DOM element that gets created.
  5678. */
  5679. createEl() {
  5680. return super.createEl('div', {
  5681. className: this.buildCSSClass(),
  5682. tabIndex: -1
  5683. }, {
  5684. 'aria-describedby': `${this.id()}_description`,
  5685. 'aria-hidden': 'true',
  5686. 'aria-label': this.label(),
  5687. 'role': 'dialog',
  5688. 'aria-live': 'polite'
  5689. });
  5690. }
  5691. dispose() {
  5692. this.contentEl_ = null;
  5693. this.descEl_ = null;
  5694. this.previouslyActiveEl_ = null;
  5695. super.dispose();
  5696. }
  5697. /**
  5698. * Builds the default DOM `className`.
  5699. *
  5700. * @return {string}
  5701. * The DOM `className` for this object.
  5702. */
  5703. buildCSSClass() {
  5704. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5705. }
  5706. /**
  5707. * Returns the label string for this modal. Primarily used for accessibility.
  5708. *
  5709. * @return {string}
  5710. * the localized or raw label of this modal.
  5711. */
  5712. label() {
  5713. return this.localize(this.options_.label || 'Modal Window');
  5714. }
  5715. /**
  5716. * Returns the description string for this modal. Primarily used for
  5717. * accessibility.
  5718. *
  5719. * @return {string}
  5720. * The localized or raw description of this modal.
  5721. */
  5722. description() {
  5723. let desc = this.options_.description || this.localize('This is a modal window.');
  5724. // Append a universal closeability message if the modal is closeable.
  5725. if (this.closeable()) {
  5726. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5727. }
  5728. return desc;
  5729. }
  5730. /**
  5731. * Opens the modal.
  5732. *
  5733. * @fires ModalDialog#beforemodalopen
  5734. * @fires ModalDialog#modalopen
  5735. */
  5736. open() {
  5737. if (this.opened_) {
  5738. if (this.options_.fillAlways) {
  5739. this.fill();
  5740. }
  5741. return;
  5742. }
  5743. const player = this.player();
  5744. /**
  5745. * Fired just before a `ModalDialog` is opened.
  5746. *
  5747. * @event ModalDialog#beforemodalopen
  5748. * @type {Event}
  5749. */
  5750. this.trigger('beforemodalopen');
  5751. this.opened_ = true;
  5752. // Fill content if the modal has never opened before and
  5753. // never been filled.
  5754. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5755. this.fill();
  5756. }
  5757. // If the player was playing, pause it and take note of its previously
  5758. // playing state.
  5759. this.wasPlaying_ = !player.paused();
  5760. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5761. player.pause();
  5762. }
  5763. this.on('keydown', this.handleKeyDown_);
  5764. // Hide controls and note if they were enabled.
  5765. this.hadControls_ = player.controls();
  5766. player.controls(false);
  5767. this.show();
  5768. this.conditionalFocus_();
  5769. this.el().setAttribute('aria-hidden', 'false');
  5770. /**
  5771. * Fired just after a `ModalDialog` is opened.
  5772. *
  5773. * @event ModalDialog#modalopen
  5774. * @type {Event}
  5775. */
  5776. this.trigger('modalopen');
  5777. this.hasBeenOpened_ = true;
  5778. }
  5779. /**
  5780. * If the `ModalDialog` is currently open or closed.
  5781. *
  5782. * @param {boolean} [value]
  5783. * If given, it will open (`true`) or close (`false`) the modal.
  5784. *
  5785. * @return {boolean}
  5786. * the current open state of the modaldialog
  5787. */
  5788. opened(value) {
  5789. if (typeof value === 'boolean') {
  5790. this[value ? 'open' : 'close']();
  5791. }
  5792. return this.opened_;
  5793. }
  5794. /**
  5795. * Closes the modal, does nothing if the `ModalDialog` is
  5796. * not open.
  5797. *
  5798. * @fires ModalDialog#beforemodalclose
  5799. * @fires ModalDialog#modalclose
  5800. */
  5801. close() {
  5802. if (!this.opened_) {
  5803. return;
  5804. }
  5805. const player = this.player();
  5806. /**
  5807. * Fired just before a `ModalDialog` is closed.
  5808. *
  5809. * @event ModalDialog#beforemodalclose
  5810. * @type {Event}
  5811. */
  5812. this.trigger('beforemodalclose');
  5813. this.opened_ = false;
  5814. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5815. player.play();
  5816. }
  5817. this.off('keydown', this.handleKeyDown_);
  5818. if (this.hadControls_) {
  5819. player.controls(true);
  5820. }
  5821. this.hide();
  5822. this.el().setAttribute('aria-hidden', 'true');
  5823. /**
  5824. * Fired just after a `ModalDialog` is closed.
  5825. *
  5826. * @event ModalDialog#modalclose
  5827. * @type {Event}
  5828. *
  5829. * @property {boolean} [bubbles=true]
  5830. */
  5831. this.trigger({
  5832. type: 'modalclose',
  5833. bubbles: true
  5834. });
  5835. this.conditionalBlur_();
  5836. if (this.options_.temporary) {
  5837. this.dispose();
  5838. }
  5839. }
  5840. /**
  5841. * Check to see if the `ModalDialog` is closeable via the UI.
  5842. *
  5843. * @param {boolean} [value]
  5844. * If given as a boolean, it will set the `closeable` option.
  5845. *
  5846. * @return {boolean}
  5847. * Returns the final value of the closable option.
  5848. */
  5849. closeable(value) {
  5850. if (typeof value === 'boolean') {
  5851. const closeable = this.closeable_ = !!value;
  5852. let close = this.getChild('closeButton');
  5853. // If this is being made closeable and has no close button, add one.
  5854. if (closeable && !close) {
  5855. // The close button should be a child of the modal - not its
  5856. // content element, so temporarily change the content element.
  5857. const temp = this.contentEl_;
  5858. this.contentEl_ = this.el_;
  5859. close = this.addChild('closeButton', {
  5860. controlText: 'Close Modal Dialog'
  5861. });
  5862. this.contentEl_ = temp;
  5863. this.on(close, 'close', this.close_);
  5864. }
  5865. // If this is being made uncloseable and has a close button, remove it.
  5866. if (!closeable && close) {
  5867. this.off(close, 'close', this.close_);
  5868. this.removeChild(close);
  5869. close.dispose();
  5870. }
  5871. }
  5872. return this.closeable_;
  5873. }
  5874. /**
  5875. * Fill the modal's content element with the modal's "content" option.
  5876. * The content element will be emptied before this change takes place.
  5877. */
  5878. fill() {
  5879. this.fillWith(this.content());
  5880. }
  5881. /**
  5882. * Fill the modal's content element with arbitrary content.
  5883. * The content element will be emptied before this change takes place.
  5884. *
  5885. * @fires ModalDialog#beforemodalfill
  5886. * @fires ModalDialog#modalfill
  5887. *
  5888. * @param {ContentDescriptor} [content]
  5889. * The same rules apply to this as apply to the `content` option.
  5890. */
  5891. fillWith(content) {
  5892. const contentEl = this.contentEl();
  5893. const parentEl = contentEl.parentNode;
  5894. const nextSiblingEl = contentEl.nextSibling;
  5895. /**
  5896. * Fired just before a `ModalDialog` is filled with content.
  5897. *
  5898. * @event ModalDialog#beforemodalfill
  5899. * @type {Event}
  5900. */
  5901. this.trigger('beforemodalfill');
  5902. this.hasBeenFilled_ = true;
  5903. // Detach the content element from the DOM before performing
  5904. // manipulation to avoid modifying the live DOM multiple times.
  5905. parentEl.removeChild(contentEl);
  5906. this.empty();
  5907. insertContent(contentEl, content);
  5908. /**
  5909. * Fired just after a `ModalDialog` is filled with content.
  5910. *
  5911. * @event ModalDialog#modalfill
  5912. * @type {Event}
  5913. */
  5914. this.trigger('modalfill');
  5915. // Re-inject the re-filled content element.
  5916. if (nextSiblingEl) {
  5917. parentEl.insertBefore(contentEl, nextSiblingEl);
  5918. } else {
  5919. parentEl.appendChild(contentEl);
  5920. }
  5921. // make sure that the close button is last in the dialog DOM
  5922. const closeButton = this.getChild('closeButton');
  5923. if (closeButton) {
  5924. parentEl.appendChild(closeButton.el_);
  5925. }
  5926. /**
  5927. * Fired after `ModalDialog` is re-filled with content & close button is appended.
  5928. *
  5929. * @event ModalDialog#aftermodalfill
  5930. * @type {Event}
  5931. */
  5932. this.trigger('aftermodalfill');
  5933. }
  5934. /**
  5935. * Empties the content element. This happens anytime the modal is filled.
  5936. *
  5937. * @fires ModalDialog#beforemodalempty
  5938. * @fires ModalDialog#modalempty
  5939. */
  5940. empty() {
  5941. /**
  5942. * Fired just before a `ModalDialog` is emptied.
  5943. *
  5944. * @event ModalDialog#beforemodalempty
  5945. * @type {Event}
  5946. */
  5947. this.trigger('beforemodalempty');
  5948. emptyEl(this.contentEl());
  5949. /**
  5950. * Fired just after a `ModalDialog` is emptied.
  5951. *
  5952. * @event ModalDialog#modalempty
  5953. * @type {Event}
  5954. */
  5955. this.trigger('modalempty');
  5956. }
  5957. /**
  5958. * Gets or sets the modal content, which gets normalized before being
  5959. * rendered into the DOM.
  5960. *
  5961. * This does not update the DOM or fill the modal, but it is called during
  5962. * that process.
  5963. *
  5964. * @param {ContentDescriptor} [value]
  5965. * If defined, sets the internal content value to be used on the
  5966. * next call(s) to `fill`. This value is normalized before being
  5967. * inserted. To "clear" the internal content value, pass `null`.
  5968. *
  5969. * @return {ContentDescriptor}
  5970. * The current content of the modal dialog
  5971. */
  5972. content(value) {
  5973. if (typeof value !== 'undefined') {
  5974. this.content_ = value;
  5975. }
  5976. return this.content_;
  5977. }
  5978. /**
  5979. * conditionally focus the modal dialog if focus was previously on the player.
  5980. *
  5981. * @private
  5982. */
  5983. conditionalFocus_() {
  5984. const activeEl = document.activeElement;
  5985. const playerEl = this.player_.el_;
  5986. this.previouslyActiveEl_ = null;
  5987. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5988. this.previouslyActiveEl_ = activeEl;
  5989. this.focus();
  5990. }
  5991. }
  5992. /**
  5993. * conditionally blur the element and refocus the last focused element
  5994. *
  5995. * @private
  5996. */
  5997. conditionalBlur_() {
  5998. if (this.previouslyActiveEl_) {
  5999. this.previouslyActiveEl_.focus();
  6000. this.previouslyActiveEl_ = null;
  6001. }
  6002. }
  6003. /**
  6004. * Keydown handler. Attached when modal is focused.
  6005. *
  6006. * @listens keydown
  6007. */
  6008. handleKeyDown(event) {
  6009. /**
  6010. * Fired a custom keyDown event that bubbles.
  6011. *
  6012. * @event ModalDialog#modalKeydown
  6013. * @type {Event}
  6014. */
  6015. this.trigger({
  6016. type: 'modalKeydown',
  6017. originalEvent: event,
  6018. target: this,
  6019. bubbles: true
  6020. });
  6021. // Do not allow keydowns to reach out of the modal dialog.
  6022. event.stopPropagation();
  6023. if (event.key === 'Escape' && this.closeable()) {
  6024. event.preventDefault();
  6025. this.close();
  6026. return;
  6027. }
  6028. // exit early if it isn't a tab key
  6029. if (event.key !== 'Tab') {
  6030. return;
  6031. }
  6032. const focusableEls = this.focusableEls_();
  6033. const activeEl = this.el_.querySelector(':focus');
  6034. let focusIndex;
  6035. for (let i = 0; i < focusableEls.length; i++) {
  6036. if (activeEl === focusableEls[i]) {
  6037. focusIndex = i;
  6038. break;
  6039. }
  6040. }
  6041. if (document.activeElement === this.el_) {
  6042. focusIndex = 0;
  6043. }
  6044. if (event.shiftKey && focusIndex === 0) {
  6045. focusableEls[focusableEls.length - 1].focus();
  6046. event.preventDefault();
  6047. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  6048. focusableEls[0].focus();
  6049. event.preventDefault();
  6050. }
  6051. }
  6052. /**
  6053. * get all focusable elements
  6054. *
  6055. * @private
  6056. */
  6057. focusableEls_() {
  6058. const allChildren = this.el_.querySelectorAll('*');
  6059. return Array.prototype.filter.call(allChildren, child => {
  6060. return (child instanceof window.HTMLAnchorElement || child instanceof window.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window.HTMLInputElement || child instanceof window.HTMLSelectElement || child instanceof window.HTMLTextAreaElement || child instanceof window.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window.HTMLIFrameElement || child instanceof window.HTMLObjectElement || child instanceof window.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
  6061. });
  6062. }
  6063. }
  6064. /**
  6065. * Default options for `ModalDialog` default options.
  6066. *
  6067. * @type {Object}
  6068. * @private
  6069. */
  6070. ModalDialog.prototype.options_ = {
  6071. pauseOnOpen: true,
  6072. temporary: true
  6073. };
  6074. Component.registerComponent('ModalDialog', ModalDialog);
  6075. /**
  6076. * @file track-list.js
  6077. */
  6078. /** @import Track from './track' */
  6079. /**
  6080. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  6081. * {@link VideoTrackList}
  6082. *
  6083. * @extends EventTarget
  6084. */
  6085. class TrackList extends EventTarget {
  6086. /**
  6087. * Create an instance of this class
  6088. *
  6089. * @param { Track[] } tracks
  6090. * A list of tracks to initialize the list with.
  6091. *
  6092. * @abstract
  6093. */
  6094. constructor(tracks = []) {
  6095. super();
  6096. this.tracks_ = [];
  6097. /**
  6098. * @memberof TrackList
  6099. * @member {number} length
  6100. * The current number of `Track`s in the this Trackist.
  6101. * @instance
  6102. */
  6103. Object.defineProperty(this, 'length', {
  6104. get() {
  6105. return this.tracks_.length;
  6106. }
  6107. });
  6108. for (let i = 0; i < tracks.length; i++) {
  6109. this.addTrack(tracks[i]);
  6110. }
  6111. }
  6112. /**
  6113. * Add a {@link Track} to the `TrackList`
  6114. *
  6115. * @param {Track} track
  6116. * The audio, video, or text track to add to the list.
  6117. *
  6118. * @fires TrackList#addtrack
  6119. */
  6120. addTrack(track) {
  6121. const index = this.tracks_.length;
  6122. if (!('' + index in this)) {
  6123. Object.defineProperty(this, index, {
  6124. get() {
  6125. return this.tracks_[index];
  6126. }
  6127. });
  6128. }
  6129. // Do not add duplicate tracks
  6130. if (this.tracks_.indexOf(track) === -1) {
  6131. this.tracks_.push(track);
  6132. /**
  6133. * Triggered when a track is added to a track list.
  6134. *
  6135. * @event TrackList#addtrack
  6136. * @type {Event}
  6137. * @property {Track} track
  6138. * A reference to track that was added.
  6139. */
  6140. this.trigger({
  6141. track,
  6142. type: 'addtrack',
  6143. target: this
  6144. });
  6145. }
  6146. /**
  6147. * Triggered when a track label is changed.
  6148. *
  6149. * @event TrackList#addtrack
  6150. * @type {Event}
  6151. * @property {Track} track
  6152. * A reference to track that was added.
  6153. */
  6154. track.labelchange_ = () => {
  6155. this.trigger({
  6156. track,
  6157. type: 'labelchange',
  6158. target: this
  6159. });
  6160. };
  6161. if (isEvented(track)) {
  6162. track.addEventListener('labelchange', track.labelchange_);
  6163. }
  6164. }
  6165. /**
  6166. * Remove a {@link Track} from the `TrackList`
  6167. *
  6168. * @param {Track} rtrack
  6169. * The audio, video, or text track to remove from the list.
  6170. *
  6171. * @fires TrackList#removetrack
  6172. */
  6173. removeTrack(rtrack) {
  6174. let track;
  6175. for (let i = 0, l = this.length; i < l; i++) {
  6176. if (this[i] === rtrack) {
  6177. track = this[i];
  6178. if (track.off) {
  6179. track.off();
  6180. }
  6181. this.tracks_.splice(i, 1);
  6182. break;
  6183. }
  6184. }
  6185. if (!track) {
  6186. return;
  6187. }
  6188. /**
  6189. * Triggered when a track is removed from track list.
  6190. *
  6191. * @event TrackList#removetrack
  6192. * @type {Event}
  6193. * @property {Track} track
  6194. * A reference to track that was removed.
  6195. */
  6196. this.trigger({
  6197. track,
  6198. type: 'removetrack',
  6199. target: this
  6200. });
  6201. }
  6202. /**
  6203. * Get a Track from the TrackList by a tracks id
  6204. *
  6205. * @param {string} id - the id of the track to get
  6206. * @method getTrackById
  6207. * @return {Track}
  6208. * @private
  6209. */
  6210. getTrackById(id) {
  6211. let result = null;
  6212. for (let i = 0, l = this.length; i < l; i++) {
  6213. const track = this[i];
  6214. if (track.id === id) {
  6215. result = track;
  6216. break;
  6217. }
  6218. }
  6219. return result;
  6220. }
  6221. }
  6222. /**
  6223. * Triggered when a different track is selected/enabled.
  6224. *
  6225. * @event TrackList#change
  6226. * @type {Event}
  6227. */
  6228. /**
  6229. * Events that can be called with on + eventName. See {@link EventHandler}.
  6230. *
  6231. * @property {Object} TrackList#allowedEvents_
  6232. * @protected
  6233. */
  6234. TrackList.prototype.allowedEvents_ = {
  6235. change: 'change',
  6236. addtrack: 'addtrack',
  6237. removetrack: 'removetrack',
  6238. labelchange: 'labelchange'
  6239. };
  6240. // emulate attribute EventHandler support to allow for feature detection
  6241. for (const event in TrackList.prototype.allowedEvents_) {
  6242. TrackList.prototype['on' + event] = null;
  6243. }
  6244. /**
  6245. * @file audio-track-list.js
  6246. */
  6247. /** @import AudioTrack from './audio-track' */
  6248. /**
  6249. * Anywhere we call this function we diverge from the spec
  6250. * as we only support one enabled audiotrack at a time
  6251. *
  6252. * @param {AudioTrackList} list
  6253. * list to work on
  6254. *
  6255. * @param {AudioTrack} track
  6256. * The track to skip
  6257. *
  6258. * @private
  6259. */
  6260. const disableOthers$1 = function (list, track) {
  6261. for (let i = 0; i < list.length; i++) {
  6262. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  6263. continue;
  6264. }
  6265. // another audio track is enabled, disable it
  6266. list[i].enabled = false;
  6267. }
  6268. };
  6269. /**
  6270. * The current list of {@link AudioTrack} for a media file.
  6271. *
  6272. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  6273. * @extends TrackList
  6274. */
  6275. class AudioTrackList extends TrackList {
  6276. /**
  6277. * Create an instance of this class.
  6278. *
  6279. * @param {AudioTrack[]} [tracks=[]]
  6280. * A list of `AudioTrack` to instantiate the list with.
  6281. */
  6282. constructor(tracks = []) {
  6283. // make sure only 1 track is enabled
  6284. // sorted from last index to first index
  6285. for (let i = tracks.length - 1; i >= 0; i--) {
  6286. if (tracks[i].enabled) {
  6287. disableOthers$1(tracks, tracks[i]);
  6288. break;
  6289. }
  6290. }
  6291. super(tracks);
  6292. this.changing_ = false;
  6293. }
  6294. /**
  6295. * Add an {@link AudioTrack} to the `AudioTrackList`.
  6296. *
  6297. * @param {AudioTrack} track
  6298. * The AudioTrack to add to the list
  6299. *
  6300. * @fires TrackList#addtrack
  6301. */
  6302. addTrack(track) {
  6303. if (track.enabled) {
  6304. disableOthers$1(this, track);
  6305. }
  6306. super.addTrack(track);
  6307. // native tracks don't have this
  6308. if (!track.addEventListener) {
  6309. return;
  6310. }
  6311. track.enabledChange_ = () => {
  6312. // when we are disabling other tracks (since we don't support
  6313. // more than one track at a time) we will set changing_
  6314. // to true so that we don't trigger additional change events
  6315. if (this.changing_) {
  6316. return;
  6317. }
  6318. this.changing_ = true;
  6319. disableOthers$1(this, track);
  6320. this.changing_ = false;
  6321. this.trigger('change');
  6322. };
  6323. /**
  6324. * @listens AudioTrack#enabledchange
  6325. * @fires TrackList#change
  6326. */
  6327. track.addEventListener('enabledchange', track.enabledChange_);
  6328. }
  6329. removeTrack(rtrack) {
  6330. super.removeTrack(rtrack);
  6331. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  6332. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  6333. rtrack.enabledChange_ = null;
  6334. }
  6335. }
  6336. }
  6337. /**
  6338. * @file video-track-list.js
  6339. */
  6340. /** @import VideoTrack from './video-track' */
  6341. /**
  6342. * Un-select all other {@link VideoTrack}s that are selected.
  6343. *
  6344. * @param {VideoTrackList} list
  6345. * list to work on
  6346. *
  6347. * @param {VideoTrack} track
  6348. * The track to skip
  6349. *
  6350. * @private
  6351. */
  6352. const disableOthers = function (list, track) {
  6353. for (let i = 0; i < list.length; i++) {
  6354. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  6355. continue;
  6356. }
  6357. // another video track is enabled, disable it
  6358. list[i].selected = false;
  6359. }
  6360. };
  6361. /**
  6362. * The current list of {@link VideoTrack} for a video.
  6363. *
  6364. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  6365. * @extends TrackList
  6366. */
  6367. class VideoTrackList extends TrackList {
  6368. /**
  6369. * Create an instance of this class.
  6370. *
  6371. * @param {VideoTrack[]} [tracks=[]]
  6372. * A list of `VideoTrack` to instantiate the list with.
  6373. */
  6374. constructor(tracks = []) {
  6375. // make sure only 1 track is enabled
  6376. // sorted from last index to first index
  6377. for (let i = tracks.length - 1; i >= 0; i--) {
  6378. if (tracks[i].selected) {
  6379. disableOthers(tracks, tracks[i]);
  6380. break;
  6381. }
  6382. }
  6383. super(tracks);
  6384. this.changing_ = false;
  6385. /**
  6386. * @member {number} VideoTrackList#selectedIndex
  6387. * The current index of the selected {@link VideoTrack`}.
  6388. */
  6389. Object.defineProperty(this, 'selectedIndex', {
  6390. get() {
  6391. for (let i = 0; i < this.length; i++) {
  6392. if (this[i].selected) {
  6393. return i;
  6394. }
  6395. }
  6396. return -1;
  6397. },
  6398. set() {}
  6399. });
  6400. }
  6401. /**
  6402. * Add a {@link VideoTrack} to the `VideoTrackList`.
  6403. *
  6404. * @param {VideoTrack} track
  6405. * The VideoTrack to add to the list
  6406. *
  6407. * @fires TrackList#addtrack
  6408. */
  6409. addTrack(track) {
  6410. if (track.selected) {
  6411. disableOthers(this, track);
  6412. }
  6413. super.addTrack(track);
  6414. // native tracks don't have this
  6415. if (!track.addEventListener) {
  6416. return;
  6417. }
  6418. track.selectedChange_ = () => {
  6419. if (this.changing_) {
  6420. return;
  6421. }
  6422. this.changing_ = true;
  6423. disableOthers(this, track);
  6424. this.changing_ = false;
  6425. this.trigger('change');
  6426. };
  6427. /**
  6428. * @listens VideoTrack#selectedchange
  6429. * @fires TrackList#change
  6430. */
  6431. track.addEventListener('selectedchange', track.selectedChange_);
  6432. }
  6433. removeTrack(rtrack) {
  6434. super.removeTrack(rtrack);
  6435. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  6436. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  6437. rtrack.selectedChange_ = null;
  6438. }
  6439. }
  6440. }
  6441. /**
  6442. * @file text-track-list.js
  6443. */
  6444. /** @import TextTrack from './text-track' */
  6445. /**
  6446. * The current list of {@link TextTrack} for a media file.
  6447. *
  6448. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  6449. * @extends TrackList
  6450. */
  6451. class TextTrackList extends TrackList {
  6452. /**
  6453. * Add a {@link TextTrack} to the `TextTrackList`
  6454. *
  6455. * @param {TextTrack} track
  6456. * The text track to add to the list.
  6457. *
  6458. * @fires TrackList#addtrack
  6459. */
  6460. addTrack(track) {
  6461. super.addTrack(track);
  6462. if (!this.queueChange_) {
  6463. this.queueChange_ = () => this.queueTrigger('change');
  6464. }
  6465. if (!this.triggerSelectedlanguagechange) {
  6466. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  6467. }
  6468. /**
  6469. * @listens TextTrack#modechange
  6470. * @fires TrackList#change
  6471. */
  6472. track.addEventListener('modechange', this.queueChange_);
  6473. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6474. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6475. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6476. }
  6477. }
  6478. removeTrack(rtrack) {
  6479. super.removeTrack(rtrack);
  6480. // manually remove the event handlers we added
  6481. if (rtrack.removeEventListener) {
  6482. if (this.queueChange_) {
  6483. rtrack.removeEventListener('modechange', this.queueChange_);
  6484. }
  6485. if (this.selectedlanguagechange_) {
  6486. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6487. }
  6488. }
  6489. }
  6490. }
  6491. /**
  6492. * @file html-track-element-list.js
  6493. */
  6494. /**
  6495. * The current list of {@link HtmlTrackElement}s.
  6496. */
  6497. class HtmlTrackElementList {
  6498. /**
  6499. * Create an instance of this class.
  6500. *
  6501. * @param {HtmlTrackElement[]} [tracks=[]]
  6502. * A list of `HtmlTrackElement` to instantiate the list with.
  6503. */
  6504. constructor(trackElements = []) {
  6505. this.trackElements_ = [];
  6506. /**
  6507. * @memberof HtmlTrackElementList
  6508. * @member {number} length
  6509. * The current number of `Track`s in the this Trackist.
  6510. * @instance
  6511. */
  6512. Object.defineProperty(this, 'length', {
  6513. get() {
  6514. return this.trackElements_.length;
  6515. }
  6516. });
  6517. for (let i = 0, length = trackElements.length; i < length; i++) {
  6518. this.addTrackElement_(trackElements[i]);
  6519. }
  6520. }
  6521. /**
  6522. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6523. *
  6524. * @param {HtmlTrackElement} trackElement
  6525. * The track element to add to the list.
  6526. *
  6527. * @private
  6528. */
  6529. addTrackElement_(trackElement) {
  6530. const index = this.trackElements_.length;
  6531. if (!('' + index in this)) {
  6532. Object.defineProperty(this, index, {
  6533. get() {
  6534. return this.trackElements_[index];
  6535. }
  6536. });
  6537. }
  6538. // Do not add duplicate elements
  6539. if (this.trackElements_.indexOf(trackElement) === -1) {
  6540. this.trackElements_.push(trackElement);
  6541. }
  6542. }
  6543. /**
  6544. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6545. * {@link TextTrack}.
  6546. *
  6547. * @param {TextTrack} track
  6548. * The track associated with a track element.
  6549. *
  6550. * @return {HtmlTrackElement|undefined}
  6551. * The track element that was found or undefined.
  6552. *
  6553. * @private
  6554. */
  6555. getTrackElementByTrack_(track) {
  6556. let trackElement_;
  6557. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6558. if (track === this.trackElements_[i].track) {
  6559. trackElement_ = this.trackElements_[i];
  6560. break;
  6561. }
  6562. }
  6563. return trackElement_;
  6564. }
  6565. /**
  6566. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6567. *
  6568. * @param {HtmlTrackElement} trackElement
  6569. * The track element to remove from the list.
  6570. *
  6571. * @private
  6572. */
  6573. removeTrackElement_(trackElement) {
  6574. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6575. if (trackElement === this.trackElements_[i]) {
  6576. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6577. this.trackElements_[i].track.off();
  6578. }
  6579. if (typeof this.trackElements_[i].off === 'function') {
  6580. this.trackElements_[i].off();
  6581. }
  6582. this.trackElements_.splice(i, 1);
  6583. break;
  6584. }
  6585. }
  6586. }
  6587. }
  6588. /**
  6589. * @file text-track-cue-list.js
  6590. */
  6591. /**
  6592. * @typedef {Object} TextTrackCueList~TextTrackCue
  6593. *
  6594. * @property {string} id
  6595. * The unique id for this text track cue
  6596. *
  6597. * @property {number} startTime
  6598. * The start time for this text track cue
  6599. *
  6600. * @property {number} endTime
  6601. * The end time for this text track cue
  6602. *
  6603. * @property {boolean} pauseOnExit
  6604. * Pause when the end time is reached if true.
  6605. *
  6606. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6607. */
  6608. /**
  6609. * A List of TextTrackCues.
  6610. *
  6611. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6612. */
  6613. class TextTrackCueList {
  6614. /**
  6615. * Create an instance of this class..
  6616. *
  6617. * @param {Array} cues
  6618. * A list of cues to be initialized with
  6619. */
  6620. constructor(cues) {
  6621. TextTrackCueList.prototype.setCues_.call(this, cues);
  6622. /**
  6623. * @memberof TextTrackCueList
  6624. * @member {number} length
  6625. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6626. * @instance
  6627. */
  6628. Object.defineProperty(this, 'length', {
  6629. get() {
  6630. return this.length_;
  6631. }
  6632. });
  6633. }
  6634. /**
  6635. * A setter for cues in this list. Creates getters
  6636. * an an index for the cues.
  6637. *
  6638. * @param {Array} cues
  6639. * An array of cues to set
  6640. *
  6641. * @private
  6642. */
  6643. setCues_(cues) {
  6644. const oldLength = this.length || 0;
  6645. let i = 0;
  6646. const l = cues.length;
  6647. this.cues_ = cues;
  6648. this.length_ = cues.length;
  6649. const defineProp = function (index) {
  6650. if (!('' + index in this)) {
  6651. Object.defineProperty(this, '' + index, {
  6652. get() {
  6653. return this.cues_[index];
  6654. }
  6655. });
  6656. }
  6657. };
  6658. if (oldLength < l) {
  6659. i = oldLength;
  6660. for (; i < l; i++) {
  6661. defineProp.call(this, i);
  6662. }
  6663. }
  6664. }
  6665. /**
  6666. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6667. *
  6668. * @param {string} id
  6669. * The id of the cue that should be searched for.
  6670. *
  6671. * @return {TextTrackCueList~TextTrackCue|null}
  6672. * A single cue or null if none was found.
  6673. */
  6674. getCueById(id) {
  6675. let result = null;
  6676. for (let i = 0, l = this.length; i < l; i++) {
  6677. const cue = this[i];
  6678. if (cue.id === id) {
  6679. result = cue;
  6680. break;
  6681. }
  6682. }
  6683. return result;
  6684. }
  6685. }
  6686. /**
  6687. * @file track-kinds.js
  6688. */
  6689. /**
  6690. * All possible `VideoTrackKind`s
  6691. *
  6692. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6693. * @typedef VideoTrack~Kind
  6694. * @enum
  6695. */
  6696. const VideoTrackKind = {
  6697. alternative: 'alternative',
  6698. captions: 'captions',
  6699. main: 'main',
  6700. sign: 'sign',
  6701. subtitles: 'subtitles',
  6702. commentary: 'commentary'
  6703. };
  6704. /**
  6705. * All possible `AudioTrackKind`s
  6706. *
  6707. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6708. * @typedef AudioTrack~Kind
  6709. * @enum
  6710. */
  6711. const AudioTrackKind = {
  6712. 'alternative': 'alternative',
  6713. 'descriptions': 'descriptions',
  6714. 'main': 'main',
  6715. 'main-desc': 'main-desc',
  6716. 'translation': 'translation',
  6717. 'commentary': 'commentary'
  6718. };
  6719. /**
  6720. * All possible `TextTrackKind`s
  6721. *
  6722. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6723. * @typedef TextTrack~Kind
  6724. * @enum
  6725. */
  6726. const TextTrackKind = {
  6727. subtitles: 'subtitles',
  6728. captions: 'captions',
  6729. descriptions: 'descriptions',
  6730. chapters: 'chapters',
  6731. metadata: 'metadata'
  6732. };
  6733. /**
  6734. * All possible `TextTrackMode`s
  6735. *
  6736. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6737. * @typedef TextTrack~Mode
  6738. * @enum
  6739. */
  6740. const TextTrackMode = {
  6741. disabled: 'disabled',
  6742. hidden: 'hidden',
  6743. showing: 'showing'
  6744. };
  6745. /**
  6746. * @file track.js
  6747. */
  6748. /**
  6749. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6750. * {@link VideoTrack}, and {@link TextTrack}.
  6751. *
  6752. * > Note: This class should not be used directly
  6753. *
  6754. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6755. * @extends EventTarget
  6756. * @abstract
  6757. */
  6758. class Track extends EventTarget {
  6759. /**
  6760. * Create an instance of this class.
  6761. *
  6762. * @param {Object} [options={}]
  6763. * Object of option names and values
  6764. *
  6765. * @param {string} [options.kind='']
  6766. * A valid kind for the track type you are creating.
  6767. *
  6768. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6769. * A unique id for this AudioTrack.
  6770. *
  6771. * @param {string} [options.label='']
  6772. * The menu label for this track.
  6773. *
  6774. * @param {string} [options.language='']
  6775. * A valid two character language code.
  6776. *
  6777. * @abstract
  6778. */
  6779. constructor(options = {}) {
  6780. super();
  6781. const trackProps = {
  6782. id: options.id || 'vjs_track_' + newGUID(),
  6783. kind: options.kind || '',
  6784. language: options.language || ''
  6785. };
  6786. let label = options.label || '';
  6787. /**
  6788. * @memberof Track
  6789. * @member {string} id
  6790. * The id of this track. Cannot be changed after creation.
  6791. * @instance
  6792. *
  6793. * @readonly
  6794. */
  6795. /**
  6796. * @memberof Track
  6797. * @member {string} kind
  6798. * The kind of track that this is. Cannot be changed after creation.
  6799. * @instance
  6800. *
  6801. * @readonly
  6802. */
  6803. /**
  6804. * @memberof Track
  6805. * @member {string} language
  6806. * The two letter language code for this track. Cannot be changed after
  6807. * creation.
  6808. * @instance
  6809. *
  6810. * @readonly
  6811. */
  6812. for (const key in trackProps) {
  6813. Object.defineProperty(this, key, {
  6814. get() {
  6815. return trackProps[key];
  6816. },
  6817. set() {}
  6818. });
  6819. }
  6820. /**
  6821. * @memberof Track
  6822. * @member {string} label
  6823. * The label of this track. Cannot be changed after creation.
  6824. * @instance
  6825. *
  6826. * @fires Track#labelchange
  6827. */
  6828. Object.defineProperty(this, 'label', {
  6829. get() {
  6830. return label;
  6831. },
  6832. set(newLabel) {
  6833. if (newLabel !== label) {
  6834. label = newLabel;
  6835. /**
  6836. * An event that fires when label changes on this track.
  6837. *
  6838. * > Note: This is not part of the spec!
  6839. *
  6840. * @event Track#labelchange
  6841. * @type {Event}
  6842. */
  6843. this.trigger('labelchange');
  6844. }
  6845. }
  6846. });
  6847. }
  6848. }
  6849. /**
  6850. * @file url.js
  6851. * @module url
  6852. */
  6853. /**
  6854. * Resolve and parse the elements of a URL.
  6855. *
  6856. * @function
  6857. * @param {string} url
  6858. * The url to parse
  6859. *
  6860. * @return {URL}
  6861. * An object of url details
  6862. */
  6863. const parseUrl = function (url) {
  6864. return new URL(url, document.baseURI);
  6865. };
  6866. /**
  6867. * Get absolute version of relative URL.
  6868. *
  6869. * @function
  6870. * @param {string} url
  6871. * URL to make absolute
  6872. *
  6873. * @return {string}
  6874. * Absolute URL
  6875. */
  6876. const getAbsoluteURL = function (url) {
  6877. return new URL(url, document.baseURI).href;
  6878. };
  6879. /**
  6880. * Returns the extension of the passed file name. It will return an empty string
  6881. * if passed an invalid path.
  6882. *
  6883. * @function
  6884. * @param {string} path
  6885. * The fileName path like '/path/to/file.mp4'
  6886. *
  6887. * @return {string}
  6888. * The extension in lower case or an empty string if no
  6889. * extension could be found.
  6890. */
  6891. const getFileExtension = function (path) {
  6892. if (typeof path === 'string') {
  6893. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6894. const pathParts = splitPathRe.exec(path);
  6895. if (pathParts) {
  6896. return pathParts.pop().toLowerCase();
  6897. }
  6898. }
  6899. return '';
  6900. };
  6901. /**
  6902. * Returns whether the url passed is a cross domain request or not.
  6903. *
  6904. * @function
  6905. * @param {string} url
  6906. * The url to check.
  6907. *
  6908. * @param {URL} [winLoc]
  6909. * the domain to check the url against, defaults to window.location
  6910. *
  6911. * @return {boolean}
  6912. * Whether it is a cross domain request or not.
  6913. */
  6914. const isCrossOrigin = function (url, winLoc = window.location) {
  6915. return parseUrl(url).origin !== winLoc.origin;
  6916. };
  6917. var Url = /*#__PURE__*/Object.freeze({
  6918. __proto__: null,
  6919. parseUrl: parseUrl,
  6920. getAbsoluteURL: getAbsoluteURL,
  6921. getFileExtension: getFileExtension,
  6922. isCrossOrigin: isCrossOrigin
  6923. });
  6924. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  6925. function unwrapExports (x) {
  6926. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  6927. }
  6928. function createCommonjsModule(fn, module) {
  6929. return module = { exports: {} }, fn(module, module.exports), module.exports;
  6930. }
  6931. var win;
  6932. if (typeof window !== "undefined") {
  6933. win = window;
  6934. } else if (typeof commonjsGlobal !== "undefined") {
  6935. win = commonjsGlobal;
  6936. } else if (typeof self !== "undefined") {
  6937. win = self;
  6938. } else {
  6939. win = {};
  6940. }
  6941. var window_1 = win;
  6942. var _extends_1 = createCommonjsModule(function (module) {
  6943. function _extends() {
  6944. return (module.exports = _extends = Object.assign ? Object.assign.bind() : function (n) {
  6945. for (var e = 1; e < arguments.length; e++) {
  6946. var t = arguments[e];
  6947. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  6948. }
  6949. return n;
  6950. }, module.exports.__esModule = true, module.exports["default"] = module.exports), _extends.apply(null, arguments);
  6951. }
  6952. module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6953. });
  6954. unwrapExports(_extends_1);
  6955. var isFunction_1 = isFunction;
  6956. var toString = Object.prototype.toString;
  6957. function isFunction(fn) {
  6958. if (!fn) {
  6959. return false;
  6960. }
  6961. var string = toString.call(fn);
  6962. return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && (
  6963. // IE8 and below
  6964. fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt);
  6965. }
  6966. function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  6967. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  6968. if (it) return (it = it.call(o)).next.bind(it);
  6969. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  6970. if (it) o = it;
  6971. var i = 0;
  6972. return function () {
  6973. if (i >= o.length) return {
  6974. done: true
  6975. };
  6976. return {
  6977. done: false,
  6978. value: o[i++]
  6979. };
  6980. };
  6981. }
  6982. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  6983. }
  6984. function _unsupportedIterableToArray(o, minLen) {
  6985. if (!o) return;
  6986. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  6987. var n = Object.prototype.toString.call(o).slice(8, -1);
  6988. if (n === "Object" && o.constructor) n = o.constructor.name;
  6989. if (n === "Map" || n === "Set") return Array.from(o);
  6990. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  6991. }
  6992. function _arrayLikeToArray(arr, len) {
  6993. if (len == null || len > arr.length) len = arr.length;
  6994. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  6995. arr2[i] = arr[i];
  6996. }
  6997. return arr2;
  6998. }
  6999. var InterceptorsStorage = /*#__PURE__*/function () {
  7000. function InterceptorsStorage() {
  7001. this.typeToInterceptorsMap_ = new Map();
  7002. this.enabled_ = false;
  7003. }
  7004. var _proto = InterceptorsStorage.prototype;
  7005. _proto.getIsEnabled = function getIsEnabled() {
  7006. return this.enabled_;
  7007. };
  7008. _proto.enable = function enable() {
  7009. this.enabled_ = true;
  7010. };
  7011. _proto.disable = function disable() {
  7012. this.enabled_ = false;
  7013. };
  7014. _proto.reset = function reset() {
  7015. this.typeToInterceptorsMap_ = new Map();
  7016. this.enabled_ = false;
  7017. };
  7018. _proto.addInterceptor = function addInterceptor(type, interceptor) {
  7019. if (!this.typeToInterceptorsMap_.has(type)) {
  7020. this.typeToInterceptorsMap_.set(type, new Set());
  7021. }
  7022. var interceptorsSet = this.typeToInterceptorsMap_.get(type);
  7023. if (interceptorsSet.has(interceptor)) {
  7024. // already have this interceptor
  7025. return false;
  7026. }
  7027. interceptorsSet.add(interceptor);
  7028. return true;
  7029. };
  7030. _proto.removeInterceptor = function removeInterceptor(type, interceptor) {
  7031. var interceptorsSet = this.typeToInterceptorsMap_.get(type);
  7032. if (interceptorsSet && interceptorsSet.has(interceptor)) {
  7033. interceptorsSet.delete(interceptor);
  7034. return true;
  7035. }
  7036. return false;
  7037. };
  7038. _proto.clearInterceptorsByType = function clearInterceptorsByType(type) {
  7039. var interceptorsSet = this.typeToInterceptorsMap_.get(type);
  7040. if (!interceptorsSet) {
  7041. return false;
  7042. }
  7043. this.typeToInterceptorsMap_.delete(type);
  7044. this.typeToInterceptorsMap_.set(type, new Set());
  7045. return true;
  7046. };
  7047. _proto.clear = function clear() {
  7048. if (!this.typeToInterceptorsMap_.size) {
  7049. return false;
  7050. }
  7051. this.typeToInterceptorsMap_ = new Map();
  7052. return true;
  7053. };
  7054. _proto.getForType = function getForType(type) {
  7055. return this.typeToInterceptorsMap_.get(type) || new Set();
  7056. };
  7057. _proto.execute = function execute(type, payload) {
  7058. var interceptors = this.getForType(type);
  7059. for (var _iterator = _createForOfIteratorHelperLoose(interceptors), _step; !(_step = _iterator()).done;) {
  7060. var interceptor = _step.value;
  7061. try {
  7062. payload = interceptor(payload);
  7063. } catch (e) {//ignore
  7064. }
  7065. }
  7066. return payload;
  7067. };
  7068. return InterceptorsStorage;
  7069. }();
  7070. var interceptors = InterceptorsStorage;
  7071. var RetryManager = /*#__PURE__*/function () {
  7072. function RetryManager() {
  7073. this.maxAttempts_ = 1;
  7074. this.delayFactor_ = 0.1;
  7075. this.fuzzFactor_ = 0.1;
  7076. this.initialDelay_ = 1000;
  7077. this.enabled_ = false;
  7078. }
  7079. var _proto = RetryManager.prototype;
  7080. _proto.getIsEnabled = function getIsEnabled() {
  7081. return this.enabled_;
  7082. };
  7083. _proto.enable = function enable() {
  7084. this.enabled_ = true;
  7085. };
  7086. _proto.disable = function disable() {
  7087. this.enabled_ = false;
  7088. };
  7089. _proto.reset = function reset() {
  7090. this.maxAttempts_ = 1;
  7091. this.delayFactor_ = 0.1;
  7092. this.fuzzFactor_ = 0.1;
  7093. this.initialDelay_ = 1000;
  7094. this.enabled_ = false;
  7095. };
  7096. _proto.getMaxAttempts = function getMaxAttempts() {
  7097. return this.maxAttempts_;
  7098. };
  7099. _proto.setMaxAttempts = function setMaxAttempts(maxAttempts) {
  7100. this.maxAttempts_ = maxAttempts;
  7101. };
  7102. _proto.getDelayFactor = function getDelayFactor() {
  7103. return this.delayFactor_;
  7104. };
  7105. _proto.setDelayFactor = function setDelayFactor(delayFactor) {
  7106. this.delayFactor_ = delayFactor;
  7107. };
  7108. _proto.getFuzzFactor = function getFuzzFactor() {
  7109. return this.fuzzFactor_;
  7110. };
  7111. _proto.setFuzzFactor = function setFuzzFactor(fuzzFactor) {
  7112. this.fuzzFactor_ = fuzzFactor;
  7113. };
  7114. _proto.getInitialDelay = function getInitialDelay() {
  7115. return this.initialDelay_;
  7116. };
  7117. _proto.setInitialDelay = function setInitialDelay(initialDelay) {
  7118. this.initialDelay_ = initialDelay;
  7119. };
  7120. _proto.createRetry = function createRetry(_temp) {
  7121. var _ref = _temp === void 0 ? {} : _temp,
  7122. maxAttempts = _ref.maxAttempts,
  7123. delayFactor = _ref.delayFactor,
  7124. fuzzFactor = _ref.fuzzFactor,
  7125. initialDelay = _ref.initialDelay;
  7126. return new Retry({
  7127. maxAttempts: maxAttempts || this.maxAttempts_,
  7128. delayFactor: delayFactor || this.delayFactor_,
  7129. fuzzFactor: fuzzFactor || this.fuzzFactor_,
  7130. initialDelay: initialDelay || this.initialDelay_
  7131. });
  7132. };
  7133. return RetryManager;
  7134. }();
  7135. var Retry = /*#__PURE__*/function () {
  7136. function Retry(options) {
  7137. this.maxAttempts_ = options.maxAttempts;
  7138. this.delayFactor_ = options.delayFactor;
  7139. this.fuzzFactor_ = options.fuzzFactor;
  7140. this.currentDelay_ = options.initialDelay;
  7141. this.currentAttempt_ = 1;
  7142. }
  7143. var _proto2 = Retry.prototype;
  7144. _proto2.moveToNextAttempt = function moveToNextAttempt() {
  7145. this.currentAttempt_++;
  7146. var delayDelta = this.currentDelay_ * this.delayFactor_;
  7147. this.currentDelay_ = this.currentDelay_ + delayDelta;
  7148. };
  7149. _proto2.shouldRetry = function shouldRetry() {
  7150. return this.currentAttempt_ < this.maxAttempts_;
  7151. };
  7152. _proto2.getCurrentDelay = function getCurrentDelay() {
  7153. return this.currentDelay_;
  7154. };
  7155. _proto2.getCurrentMinPossibleDelay = function getCurrentMinPossibleDelay() {
  7156. return (1 - this.fuzzFactor_) * this.currentDelay_;
  7157. };
  7158. _proto2.getCurrentMaxPossibleDelay = function getCurrentMaxPossibleDelay() {
  7159. return (1 + this.fuzzFactor_) * this.currentDelay_;
  7160. }
  7161. /**
  7162. * For example fuzzFactor is 0.1
  7163. * This means ±10% deviation
  7164. * So if we have delay as 1000
  7165. * This function can generate any value from 900 to 1100
  7166. */;
  7167. _proto2.getCurrentFuzzedDelay = function getCurrentFuzzedDelay() {
  7168. var lowValue = this.getCurrentMinPossibleDelay();
  7169. var highValue = this.getCurrentMaxPossibleDelay();
  7170. return lowValue + Math.random() * (highValue - lowValue);
  7171. };
  7172. return Retry;
  7173. }();
  7174. var retry = RetryManager;
  7175. var httpResponseHandler = function httpResponseHandler(callback, decodeResponseBody) {
  7176. if (decodeResponseBody === void 0) {
  7177. decodeResponseBody = false;
  7178. }
  7179. return function (err, response, responseBody) {
  7180. // if the XHR failed, return that error
  7181. if (err) {
  7182. callback(err);
  7183. return;
  7184. } // if the HTTP status code is 4xx or 5xx, the request also failed
  7185. if (response.statusCode >= 400 && response.statusCode <= 599) {
  7186. var cause = responseBody;
  7187. if (decodeResponseBody) {
  7188. if (window_1.TextDecoder) {
  7189. var charset = getCharset(response.headers && response.headers['content-type']);
  7190. try {
  7191. cause = new TextDecoder(charset).decode(responseBody);
  7192. } catch (e) {}
  7193. } else {
  7194. cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
  7195. }
  7196. }
  7197. callback({
  7198. cause: cause
  7199. });
  7200. return;
  7201. } // otherwise, request succeeded
  7202. callback(null, responseBody);
  7203. };
  7204. };
  7205. function getCharset(contentTypeHeader) {
  7206. if (contentTypeHeader === void 0) {
  7207. contentTypeHeader = '';
  7208. }
  7209. return contentTypeHeader.toLowerCase().split(';').reduce(function (charset, contentType) {
  7210. var _contentType$split = contentType.split('='),
  7211. type = _contentType$split[0],
  7212. value = _contentType$split[1];
  7213. if (type.trim() === 'charset') {
  7214. return value.trim();
  7215. }
  7216. return charset;
  7217. }, 'utf-8');
  7218. }
  7219. var httpHandler = httpResponseHandler;
  7220. createXHR.httpHandler = httpHandler;
  7221. createXHR.requestInterceptorsStorage = new interceptors();
  7222. createXHR.responseInterceptorsStorage = new interceptors();
  7223. createXHR.retryManager = new retry();
  7224. /**
  7225. * @license
  7226. * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
  7227. * Copyright (c) 2014 David Björklund
  7228. * Available under the MIT license
  7229. * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
  7230. */
  7231. var parseHeaders = function parseHeaders(headers) {
  7232. var result = {};
  7233. if (!headers) {
  7234. return result;
  7235. }
  7236. headers.trim().split('\n').forEach(function (row) {
  7237. var index = row.indexOf(':');
  7238. var key = row.slice(0, index).trim().toLowerCase();
  7239. var value = row.slice(index + 1).trim();
  7240. if (typeof result[key] === 'undefined') {
  7241. result[key] = value;
  7242. } else if (Array.isArray(result[key])) {
  7243. result[key].push(value);
  7244. } else {
  7245. result[key] = [result[key], value];
  7246. }
  7247. });
  7248. return result;
  7249. };
  7250. var lib = createXHR; // Allow use of default import syntax in TypeScript
  7251. var default_1 = createXHR;
  7252. createXHR.XMLHttpRequest = window_1.XMLHttpRequest || noop;
  7253. createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window_1.XDomainRequest;
  7254. forEachArray(["get", "put", "post", "patch", "head", "delete"], function (method) {
  7255. createXHR[method === "delete" ? "del" : method] = function (uri, options, callback) {
  7256. options = initParams(uri, options, callback);
  7257. options.method = method.toUpperCase();
  7258. return _createXHR(options);
  7259. };
  7260. });
  7261. function forEachArray(array, iterator) {
  7262. for (var i = 0; i < array.length; i++) {
  7263. iterator(array[i]);
  7264. }
  7265. }
  7266. function isEmpty(obj) {
  7267. for (var i in obj) {
  7268. if (obj.hasOwnProperty(i)) return false;
  7269. }
  7270. return true;
  7271. }
  7272. function initParams(uri, options, callback) {
  7273. var params = uri;
  7274. if (isFunction_1(options)) {
  7275. callback = options;
  7276. if (typeof uri === "string") {
  7277. params = {
  7278. uri: uri
  7279. };
  7280. }
  7281. } else {
  7282. params = _extends_1({}, options, {
  7283. uri: uri
  7284. });
  7285. }
  7286. params.callback = callback;
  7287. return params;
  7288. }
  7289. function createXHR(uri, options, callback) {
  7290. options = initParams(uri, options, callback);
  7291. return _createXHR(options);
  7292. }
  7293. function _createXHR(options) {
  7294. if (typeof options.callback === "undefined") {
  7295. throw new Error("callback argument missing");
  7296. } // call all registered request interceptors for a given request type:
  7297. if (options.requestType && createXHR.requestInterceptorsStorage.getIsEnabled()) {
  7298. var requestInterceptorPayload = {
  7299. uri: options.uri || options.url,
  7300. headers: options.headers || {},
  7301. body: options.body,
  7302. metadata: options.metadata || {},
  7303. retry: options.retry,
  7304. timeout: options.timeout
  7305. };
  7306. var updatedPayload = createXHR.requestInterceptorsStorage.execute(options.requestType, requestInterceptorPayload);
  7307. options.uri = updatedPayload.uri;
  7308. options.headers = updatedPayload.headers;
  7309. options.body = updatedPayload.body;
  7310. options.metadata = updatedPayload.metadata;
  7311. options.retry = updatedPayload.retry;
  7312. options.timeout = updatedPayload.timeout;
  7313. }
  7314. var called = false;
  7315. var callback = function cbOnce(err, response, body) {
  7316. if (!called) {
  7317. called = true;
  7318. options.callback(err, response, body);
  7319. }
  7320. };
  7321. function readystatechange() {
  7322. // do not call load 2 times when response interceptors are enabled
  7323. // why do we even need this 2nd load?
  7324. if (xhr.readyState === 4 && !createXHR.responseInterceptorsStorage.getIsEnabled()) {
  7325. setTimeout(loadFunc, 0);
  7326. }
  7327. }
  7328. function getBody() {
  7329. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  7330. var body = undefined;
  7331. if (xhr.response) {
  7332. body = xhr.response;
  7333. } else {
  7334. body = xhr.responseText || getXml(xhr);
  7335. }
  7336. if (isJson) {
  7337. try {
  7338. body = JSON.parse(body);
  7339. } catch (e) {}
  7340. }
  7341. return body;
  7342. }
  7343. function errorFunc(evt) {
  7344. clearTimeout(timeoutTimer);
  7345. clearTimeout(options.retryTimeout);
  7346. if (!(evt instanceof Error)) {
  7347. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error"));
  7348. }
  7349. evt.statusCode = 0; // we would like to retry on error:
  7350. if (!aborted && createXHR.retryManager.getIsEnabled() && options.retry && options.retry.shouldRetry()) {
  7351. options.retryTimeout = setTimeout(function () {
  7352. options.retry.moveToNextAttempt(); // we want to re-use the same options and the same xhr object:
  7353. options.xhr = xhr;
  7354. _createXHR(options);
  7355. }, options.retry.getCurrentFuzzedDelay());
  7356. return;
  7357. } // call all registered response interceptors for a given request type:
  7358. if (options.requestType && createXHR.responseInterceptorsStorage.getIsEnabled()) {
  7359. var responseInterceptorPayload = {
  7360. headers: failureResponse.headers || {},
  7361. body: failureResponse.body,
  7362. responseUrl: xhr.responseURL,
  7363. responseType: xhr.responseType
  7364. };
  7365. var _updatedPayload = createXHR.responseInterceptorsStorage.execute(options.requestType, responseInterceptorPayload);
  7366. failureResponse.body = _updatedPayload.body;
  7367. failureResponse.headers = _updatedPayload.headers;
  7368. }
  7369. return callback(evt, failureResponse);
  7370. } // will load the data & process the response in a special response object
  7371. function loadFunc() {
  7372. if (aborted) return;
  7373. var status;
  7374. clearTimeout(timeoutTimer);
  7375. clearTimeout(options.retryTimeout);
  7376. if (options.useXDR && xhr.status === undefined) {
  7377. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  7378. status = 200;
  7379. } else {
  7380. status = xhr.status === 1223 ? 204 : xhr.status;
  7381. }
  7382. var response = failureResponse;
  7383. var err = null;
  7384. if (status !== 0) {
  7385. response = {
  7386. body: getBody(),
  7387. statusCode: status,
  7388. method: method,
  7389. headers: {},
  7390. url: uri,
  7391. rawRequest: xhr
  7392. };
  7393. if (xhr.getAllResponseHeaders) {
  7394. //remember xhr can in fact be XDR for CORS in IE
  7395. response.headers = parseHeaders(xhr.getAllResponseHeaders());
  7396. }
  7397. } else {
  7398. err = new Error("Internal XMLHttpRequest Error");
  7399. } // call all registered response interceptors for a given request type:
  7400. if (options.requestType && createXHR.responseInterceptorsStorage.getIsEnabled()) {
  7401. var responseInterceptorPayload = {
  7402. headers: response.headers || {},
  7403. body: response.body,
  7404. responseUrl: xhr.responseURL,
  7405. responseType: xhr.responseType
  7406. };
  7407. var _updatedPayload2 = createXHR.responseInterceptorsStorage.execute(options.requestType, responseInterceptorPayload);
  7408. response.body = _updatedPayload2.body;
  7409. response.headers = _updatedPayload2.headers;
  7410. }
  7411. return callback(err, response, response.body);
  7412. }
  7413. var xhr = options.xhr || null;
  7414. if (!xhr) {
  7415. if (options.cors || options.useXDR) {
  7416. xhr = new createXHR.XDomainRequest();
  7417. } else {
  7418. xhr = new createXHR.XMLHttpRequest();
  7419. }
  7420. }
  7421. var key;
  7422. var aborted;
  7423. var uri = xhr.url = options.uri || options.url;
  7424. var method = xhr.method = options.method || "GET";
  7425. var body = options.body || options.data;
  7426. var headers = xhr.headers = options.headers || {};
  7427. var sync = !!options.sync;
  7428. var isJson = false;
  7429. var timeoutTimer;
  7430. var failureResponse = {
  7431. body: undefined,
  7432. headers: {},
  7433. statusCode: 0,
  7434. method: method,
  7435. url: uri,
  7436. rawRequest: xhr
  7437. };
  7438. if ("json" in options && options.json !== false) {
  7439. isJson = true;
  7440. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json"); //Don't override existing accept header declared by user
  7441. if (method !== "GET" && method !== "HEAD") {
  7442. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json"); //Don't override existing accept header declared by user
  7443. body = JSON.stringify(options.json === true ? body : options.json);
  7444. }
  7445. }
  7446. xhr.onreadystatechange = readystatechange;
  7447. xhr.onload = loadFunc;
  7448. xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function.
  7449. xhr.onprogress = function () {// IE must die
  7450. };
  7451. xhr.onabort = function () {
  7452. aborted = true;
  7453. clearTimeout(options.retryTimeout);
  7454. };
  7455. xhr.ontimeout = errorFunc;
  7456. xhr.open(method, uri, !sync, options.username, options.password); //has to be after open
  7457. if (!sync) {
  7458. xhr.withCredentials = !!options.withCredentials;
  7459. } // Cannot set timeout with sync request
  7460. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  7461. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  7462. if (!sync && options.timeout > 0) {
  7463. timeoutTimer = setTimeout(function () {
  7464. if (aborted) return;
  7465. aborted = true; //IE9 may still call readystatechange
  7466. xhr.abort("timeout");
  7467. var e = new Error("XMLHttpRequest timeout");
  7468. e.code = "ETIMEDOUT";
  7469. errorFunc(e);
  7470. }, options.timeout);
  7471. }
  7472. if (xhr.setRequestHeader) {
  7473. for (key in headers) {
  7474. if (headers.hasOwnProperty(key)) {
  7475. xhr.setRequestHeader(key, headers[key]);
  7476. }
  7477. }
  7478. } else if (options.headers && !isEmpty(options.headers)) {
  7479. throw new Error("Headers cannot be set on an XDomainRequest object");
  7480. }
  7481. if ("responseType" in options) {
  7482. xhr.responseType = options.responseType;
  7483. }
  7484. if ("beforeSend" in options && typeof options.beforeSend === "function") {
  7485. options.beforeSend(xhr);
  7486. } // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  7487. // XMLHttpRequest spec says to pass null as body to indicate no body
  7488. // See https://github.com/naugtur/xhr/issues/100.
  7489. xhr.send(body || null);
  7490. return xhr;
  7491. }
  7492. function getXml(xhr) {
  7493. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  7494. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  7495. try {
  7496. if (xhr.responseType === "document") {
  7497. return xhr.responseXML;
  7498. }
  7499. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror";
  7500. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  7501. return xhr.responseXML;
  7502. }
  7503. } catch (e) {}
  7504. return null;
  7505. }
  7506. function noop() {}
  7507. lib.default = default_1;
  7508. /**
  7509. * @file text-track.js
  7510. */
  7511. /** @import Tech from '../tech/tech' */
  7512. /**
  7513. * Takes a webvtt file contents and parses it into cues
  7514. *
  7515. * @param {string} srcContent
  7516. * webVTT file contents
  7517. *
  7518. * @param {TextTrack} track
  7519. * TextTrack to add cues to. Cues come from the srcContent.
  7520. *
  7521. * @private
  7522. */
  7523. const parseCues = function (srcContent, track) {
  7524. const parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
  7525. const errors = [];
  7526. parser.oncue = function (cue) {
  7527. track.addCue(cue);
  7528. };
  7529. parser.onparsingerror = function (error) {
  7530. errors.push(error);
  7531. };
  7532. parser.onflush = function () {
  7533. track.trigger({
  7534. type: 'loadeddata',
  7535. target: track
  7536. });
  7537. };
  7538. parser.parse(srcContent);
  7539. if (errors.length > 0) {
  7540. if (window.console && window.console.groupCollapsed) {
  7541. window.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  7542. }
  7543. errors.forEach(error => log.error(error));
  7544. if (window.console && window.console.groupEnd) {
  7545. window.console.groupEnd();
  7546. }
  7547. }
  7548. parser.flush();
  7549. };
  7550. /**
  7551. * Load a `TextTrack` from a specified url.
  7552. *
  7553. * @param {string} src
  7554. * Url to load track from.
  7555. *
  7556. * @param {TextTrack} track
  7557. * Track to add cues to. Comes from the content at the end of `url`.
  7558. *
  7559. * @private
  7560. */
  7561. const loadTrack = function (src, track) {
  7562. const opts = {
  7563. uri: src
  7564. };
  7565. const crossOrigin = isCrossOrigin(src);
  7566. if (crossOrigin) {
  7567. opts.cors = crossOrigin;
  7568. }
  7569. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  7570. if (withCredentials) {
  7571. opts.withCredentials = withCredentials;
  7572. }
  7573. lib(opts, bind_(this, function (err, response, responseBody) {
  7574. if (err) {
  7575. return log.error(err, response);
  7576. }
  7577. track.loaded_ = true;
  7578. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  7579. // NOTE: this is only used for the alt/video.novtt.js build
  7580. if (typeof window.WebVTT !== 'function') {
  7581. if (track.tech_) {
  7582. // to prevent use before define eslint error, we define loadHandler
  7583. // as a let here
  7584. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  7585. if (event.type === 'vttjserror') {
  7586. log.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  7587. return;
  7588. }
  7589. return parseCues(responseBody, track);
  7590. });
  7591. }
  7592. } else {
  7593. parseCues(responseBody, track);
  7594. }
  7595. }));
  7596. };
  7597. /**
  7598. * A representation of a single `TextTrack`.
  7599. *
  7600. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  7601. * @extends Track
  7602. */
  7603. class TextTrack extends Track {
  7604. /**
  7605. * Create an instance of this class.
  7606. *
  7607. * @param {Object} options={}
  7608. * Object of option names and values
  7609. *
  7610. * @param {Tech} options.tech
  7611. * A reference to the tech that owns this TextTrack.
  7612. *
  7613. * @param {TextTrack~Kind} [options.kind='subtitles']
  7614. * A valid text track kind.
  7615. *
  7616. * @param {TextTrack~Mode} [options.mode='disabled']
  7617. * A valid text track mode.
  7618. *
  7619. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7620. * A unique id for this TextTrack.
  7621. *
  7622. * @param {string} [options.label='']
  7623. * The menu label for this track.
  7624. *
  7625. * @param {string} [options.language='']
  7626. * A valid two character language code.
  7627. *
  7628. * @param {string} [options.srclang='']
  7629. * A valid two character language code. An alternative, but deprioritized
  7630. * version of `options.language`
  7631. *
  7632. * @param {string} [options.src]
  7633. * A url to TextTrack cues.
  7634. *
  7635. * @param {boolean} [options.default]
  7636. * If this track should default to on or off.
  7637. */
  7638. constructor(options = {}) {
  7639. if (!options.tech) {
  7640. throw new Error('A tech was not provided.');
  7641. }
  7642. const settings = merge(options, {
  7643. kind: TextTrackKind[options.kind] || 'subtitles',
  7644. language: options.language || options.srclang || ''
  7645. });
  7646. let mode = TextTrackMode[settings.mode] || 'disabled';
  7647. const default_ = settings.default;
  7648. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  7649. mode = 'hidden';
  7650. }
  7651. super(settings);
  7652. this.tech_ = settings.tech;
  7653. this.cues_ = [];
  7654. this.activeCues_ = [];
  7655. this.preload_ = this.tech_.preloadTextTracks !== false;
  7656. const cues = new TextTrackCueList(this.cues_);
  7657. const activeCues = new TextTrackCueList(this.activeCues_);
  7658. let changed = false;
  7659. this.timeupdateHandler = bind_(this, function (event = {}) {
  7660. if (this.tech_.isDisposed()) {
  7661. return;
  7662. }
  7663. if (!this.tech_.isReady_) {
  7664. if (event.type !== 'timeupdate') {
  7665. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7666. }
  7667. return;
  7668. }
  7669. // Accessing this.activeCues for the side-effects of updating itself
  7670. // due to its nature as a getter function. Do not remove or cues will
  7671. // stop updating!
  7672. // Use the setter to prevent deletion from uglify (pure_getters rule)
  7673. this.activeCues = this.activeCues;
  7674. if (changed) {
  7675. this.trigger('cuechange');
  7676. changed = false;
  7677. }
  7678. if (event.type !== 'timeupdate') {
  7679. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7680. }
  7681. });
  7682. const disposeHandler = () => {
  7683. this.stopTracking();
  7684. };
  7685. this.tech_.one('dispose', disposeHandler);
  7686. if (mode !== 'disabled') {
  7687. this.startTracking();
  7688. }
  7689. Object.defineProperties(this, {
  7690. /**
  7691. * @memberof TextTrack
  7692. * @member {boolean} default
  7693. * If this track was set to be on or off by default. Cannot be changed after
  7694. * creation.
  7695. * @instance
  7696. *
  7697. * @readonly
  7698. */
  7699. default: {
  7700. get() {
  7701. return default_;
  7702. },
  7703. set() {}
  7704. },
  7705. /**
  7706. * @memberof TextTrack
  7707. * @member {string} mode
  7708. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  7709. * not be set if setting to an invalid mode.
  7710. * @instance
  7711. *
  7712. * @fires TextTrack#modechange
  7713. */
  7714. mode: {
  7715. get() {
  7716. return mode;
  7717. },
  7718. set(newMode) {
  7719. if (!TextTrackMode[newMode]) {
  7720. return;
  7721. }
  7722. if (mode === newMode) {
  7723. return;
  7724. }
  7725. mode = newMode;
  7726. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  7727. // On-demand load.
  7728. loadTrack(this.src, this);
  7729. }
  7730. this.stopTracking();
  7731. if (mode !== 'disabled') {
  7732. this.startTracking();
  7733. }
  7734. /**
  7735. * An event that fires when mode changes on this track. This allows
  7736. * the TextTrackList that holds this track to act accordingly.
  7737. *
  7738. * > Note: This is not part of the spec!
  7739. *
  7740. * @event TextTrack#modechange
  7741. * @type {Event}
  7742. */
  7743. this.trigger('modechange');
  7744. }
  7745. },
  7746. /**
  7747. * @memberof TextTrack
  7748. * @member {TextTrackCueList} cues
  7749. * The text track cue list for this TextTrack.
  7750. * @instance
  7751. */
  7752. cues: {
  7753. get() {
  7754. if (!this.loaded_) {
  7755. return null;
  7756. }
  7757. return cues;
  7758. },
  7759. set() {}
  7760. },
  7761. /**
  7762. * @memberof TextTrack
  7763. * @member {TextTrackCueList} activeCues
  7764. * The list text track cues that are currently active for this TextTrack.
  7765. * @instance
  7766. */
  7767. activeCues: {
  7768. get() {
  7769. if (!this.loaded_) {
  7770. return null;
  7771. }
  7772. // nothing to do
  7773. if (this.cues.length === 0) {
  7774. return activeCues;
  7775. }
  7776. const ct = this.tech_.currentTime();
  7777. const active = [];
  7778. for (let i = 0, l = this.cues.length; i < l; i++) {
  7779. const cue = this.cues[i];
  7780. if (cue.startTime <= ct && cue.endTime >= ct) {
  7781. active.push(cue);
  7782. }
  7783. }
  7784. changed = false;
  7785. if (active.length !== this.activeCues_.length) {
  7786. changed = true;
  7787. } else {
  7788. for (let i = 0; i < active.length; i++) {
  7789. if (this.activeCues_.indexOf(active[i]) === -1) {
  7790. changed = true;
  7791. }
  7792. }
  7793. }
  7794. this.activeCues_ = active;
  7795. activeCues.setCues_(this.activeCues_);
  7796. return activeCues;
  7797. },
  7798. // /!\ Keep this setter empty (see the timeupdate handler above)
  7799. set() {}
  7800. }
  7801. });
  7802. if (settings.src) {
  7803. this.src = settings.src;
  7804. if (!this.preload_) {
  7805. // Tracks will load on-demand.
  7806. // Act like we're loaded for other purposes.
  7807. this.loaded_ = true;
  7808. }
  7809. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  7810. loadTrack(this.src, this);
  7811. }
  7812. } else {
  7813. this.loaded_ = true;
  7814. }
  7815. }
  7816. startTracking() {
  7817. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  7818. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7819. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  7820. this.tech_.on('timeupdate', this.timeupdateHandler);
  7821. }
  7822. stopTracking() {
  7823. if (this.rvf_) {
  7824. this.tech_.cancelVideoFrameCallback(this.rvf_);
  7825. this.rvf_ = undefined;
  7826. }
  7827. this.tech_.off('timeupdate', this.timeupdateHandler);
  7828. }
  7829. /**
  7830. * Add a cue to the internal list of cues.
  7831. *
  7832. * @param {TextTrack~Cue} cue
  7833. * The cue to add to our internal list
  7834. */
  7835. addCue(originalCue) {
  7836. let cue = originalCue;
  7837. // Testing if the cue is a VTTCue in a way that survives minification
  7838. if (!('getCueAsHTML' in cue)) {
  7839. cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  7840. for (const prop in originalCue) {
  7841. if (!(prop in cue)) {
  7842. cue[prop] = originalCue[prop];
  7843. }
  7844. }
  7845. // make sure that `id` is copied over
  7846. cue.id = originalCue.id;
  7847. cue.originalCue_ = originalCue;
  7848. }
  7849. const tracks = this.tech_.textTracks();
  7850. for (let i = 0; i < tracks.length; i++) {
  7851. if (tracks[i] !== this) {
  7852. tracks[i].removeCue(cue);
  7853. }
  7854. }
  7855. this.cues_.push(cue);
  7856. this.cues.setCues_(this.cues_);
  7857. }
  7858. /**
  7859. * Remove a cue from our internal list
  7860. *
  7861. * @param {TextTrack~Cue} removeCue
  7862. * The cue to remove from our internal list
  7863. */
  7864. removeCue(removeCue) {
  7865. let i = this.cues_.length;
  7866. while (i--) {
  7867. const cue = this.cues_[i];
  7868. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  7869. this.cues_.splice(i, 1);
  7870. this.cues.setCues_(this.cues_);
  7871. break;
  7872. }
  7873. }
  7874. }
  7875. }
  7876. /**
  7877. * cuechange - One or more cues in the track have become active or stopped being active.
  7878. *
  7879. * @protected
  7880. */
  7881. TextTrack.prototype.allowedEvents_ = {
  7882. cuechange: 'cuechange'
  7883. };
  7884. /**
  7885. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  7886. * only one `AudioTrack` in the list will be enabled at a time.
  7887. *
  7888. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  7889. * @extends Track
  7890. */
  7891. class AudioTrack extends Track {
  7892. /**
  7893. * Create an instance of this class.
  7894. *
  7895. * @param {Object} [options={}]
  7896. * Object of option names and values
  7897. *
  7898. * @param {AudioTrack~Kind} [options.kind='']
  7899. * A valid audio track kind
  7900. *
  7901. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7902. * A unique id for this AudioTrack.
  7903. *
  7904. * @param {string} [options.label='']
  7905. * The menu label for this track.
  7906. *
  7907. * @param {string} [options.language='']
  7908. * A valid two character language code.
  7909. *
  7910. * @param {boolean} [options.enabled]
  7911. * If this track is the one that is currently playing. If this track is part of
  7912. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  7913. */
  7914. constructor(options = {}) {
  7915. const settings = merge(options, {
  7916. kind: AudioTrackKind[options.kind] || ''
  7917. });
  7918. super(settings);
  7919. let enabled = false;
  7920. /**
  7921. * @memberof AudioTrack
  7922. * @member {boolean} enabled
  7923. * If this `AudioTrack` is enabled or not. When setting this will
  7924. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  7925. * @instance
  7926. *
  7927. * @fires VideoTrack#selectedchange
  7928. */
  7929. Object.defineProperty(this, 'enabled', {
  7930. get() {
  7931. return enabled;
  7932. },
  7933. set(newEnabled) {
  7934. // an invalid or unchanged value
  7935. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  7936. return;
  7937. }
  7938. enabled = newEnabled;
  7939. /**
  7940. * An event that fires when enabled changes on this track. This allows
  7941. * the AudioTrackList that holds this track to act accordingly.
  7942. *
  7943. * > Note: This is not part of the spec! Native tracks will do
  7944. * this internally without an event.
  7945. *
  7946. * @event AudioTrack#enabledchange
  7947. * @type {Event}
  7948. */
  7949. this.trigger('enabledchange');
  7950. }
  7951. });
  7952. // if the user sets this track to selected then
  7953. // set selected to that true value otherwise
  7954. // we keep it false
  7955. if (settings.enabled) {
  7956. this.enabled = settings.enabled;
  7957. }
  7958. this.loaded_ = true;
  7959. }
  7960. }
  7961. /**
  7962. * A representation of a single `VideoTrack`.
  7963. *
  7964. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  7965. * @extends Track
  7966. */
  7967. class VideoTrack extends Track {
  7968. /**
  7969. * Create an instance of this class.
  7970. *
  7971. * @param {Object} [options={}]
  7972. * Object of option names and values
  7973. *
  7974. * @param {string} [options.kind='']
  7975. * A valid {@link VideoTrack~Kind}
  7976. *
  7977. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7978. * A unique id for this AudioTrack.
  7979. *
  7980. * @param {string} [options.label='']
  7981. * The menu label for this track.
  7982. *
  7983. * @param {string} [options.language='']
  7984. * A valid two character language code.
  7985. *
  7986. * @param {boolean} [options.selected]
  7987. * If this track is the one that is currently playing.
  7988. */
  7989. constructor(options = {}) {
  7990. const settings = merge(options, {
  7991. kind: VideoTrackKind[options.kind] || ''
  7992. });
  7993. super(settings);
  7994. let selected = false;
  7995. /**
  7996. * @memberof VideoTrack
  7997. * @member {boolean} selected
  7998. * If this `VideoTrack` is selected or not. When setting this will
  7999. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  8000. * @instance
  8001. *
  8002. * @fires VideoTrack#selectedchange
  8003. */
  8004. Object.defineProperty(this, 'selected', {
  8005. get() {
  8006. return selected;
  8007. },
  8008. set(newSelected) {
  8009. // an invalid or unchanged value
  8010. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  8011. return;
  8012. }
  8013. selected = newSelected;
  8014. /**
  8015. * An event that fires when selected changes on this track. This allows
  8016. * the VideoTrackList that holds this track to act accordingly.
  8017. *
  8018. * > Note: This is not part of the spec! Native tracks will do
  8019. * this internally without an event.
  8020. *
  8021. * @event VideoTrack#selectedchange
  8022. * @type {Event}
  8023. */
  8024. this.trigger('selectedchange');
  8025. }
  8026. });
  8027. // if the user sets this track to selected then
  8028. // set selected to that true value otherwise
  8029. // we keep it false
  8030. if (settings.selected) {
  8031. this.selected = settings.selected;
  8032. }
  8033. }
  8034. }
  8035. /**
  8036. * @file html-track-element.js
  8037. */
  8038. /** @import Tech from '../tech/tech' */
  8039. /**
  8040. * A single track represented in the DOM.
  8041. *
  8042. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  8043. * @extends EventTarget
  8044. */
  8045. class HTMLTrackElement extends EventTarget {
  8046. /**
  8047. * Create an instance of this class.
  8048. *
  8049. * @param {Object} options={}
  8050. * Object of option names and values
  8051. *
  8052. * @param {Tech} options.tech
  8053. * A reference to the tech that owns this HTMLTrackElement.
  8054. *
  8055. * @param {TextTrack~Kind} [options.kind='subtitles']
  8056. * A valid text track kind.
  8057. *
  8058. * @param {TextTrack~Mode} [options.mode='disabled']
  8059. * A valid text track mode.
  8060. *
  8061. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  8062. * A unique id for this TextTrack.
  8063. *
  8064. * @param {string} [options.label='']
  8065. * The menu label for this track.
  8066. *
  8067. * @param {string} [options.language='']
  8068. * A valid two character language code.
  8069. *
  8070. * @param {string} [options.srclang='']
  8071. * A valid two character language code. An alternative, but deprioritized
  8072. * version of `options.language`
  8073. *
  8074. * @param {string} [options.src]
  8075. * A url to TextTrack cues.
  8076. *
  8077. * @param {boolean} [options.default]
  8078. * If this track should default to on or off.
  8079. */
  8080. constructor(options = {}) {
  8081. super();
  8082. let readyState;
  8083. const track = new TextTrack(options);
  8084. this.kind = track.kind;
  8085. this.src = track.src;
  8086. this.srclang = track.language;
  8087. this.label = track.label;
  8088. this.default = track.default;
  8089. Object.defineProperties(this, {
  8090. /**
  8091. * @memberof HTMLTrackElement
  8092. * @member {HTMLTrackElement~ReadyState} readyState
  8093. * The current ready state of the track element.
  8094. * @instance
  8095. */
  8096. readyState: {
  8097. get() {
  8098. return readyState;
  8099. }
  8100. },
  8101. /**
  8102. * @memberof HTMLTrackElement
  8103. * @member {TextTrack} track
  8104. * The underlying TextTrack object.
  8105. * @instance
  8106. *
  8107. */
  8108. track: {
  8109. get() {
  8110. return track;
  8111. }
  8112. }
  8113. });
  8114. readyState = HTMLTrackElement.NONE;
  8115. /**
  8116. * @listens TextTrack#loadeddata
  8117. * @fires HTMLTrackElement#load
  8118. */
  8119. track.addEventListener('loadeddata', () => {
  8120. readyState = HTMLTrackElement.LOADED;
  8121. this.trigger({
  8122. type: 'load',
  8123. target: this
  8124. });
  8125. });
  8126. }
  8127. }
  8128. /**
  8129. * @protected
  8130. */
  8131. HTMLTrackElement.prototype.allowedEvents_ = {
  8132. load: 'load'
  8133. };
  8134. /**
  8135. * The text track not loaded state.
  8136. *
  8137. * @type {number}
  8138. * @static
  8139. */
  8140. HTMLTrackElement.NONE = 0;
  8141. /**
  8142. * The text track loading state.
  8143. *
  8144. * @type {number}
  8145. * @static
  8146. */
  8147. HTMLTrackElement.LOADING = 1;
  8148. /**
  8149. * The text track loaded state.
  8150. *
  8151. * @type {number}
  8152. * @static
  8153. */
  8154. HTMLTrackElement.LOADED = 2;
  8155. /**
  8156. * The text track failed to load state.
  8157. *
  8158. * @type {number}
  8159. * @static
  8160. */
  8161. HTMLTrackElement.ERROR = 3;
  8162. /*
  8163. * This file contains all track properties that are used in
  8164. * player.js, tech.js, html5.js and possibly other techs in the future.
  8165. */
  8166. const NORMAL = {
  8167. audio: {
  8168. ListClass: AudioTrackList,
  8169. TrackClass: AudioTrack,
  8170. capitalName: 'Audio'
  8171. },
  8172. video: {
  8173. ListClass: VideoTrackList,
  8174. TrackClass: VideoTrack,
  8175. capitalName: 'Video'
  8176. },
  8177. text: {
  8178. ListClass: TextTrackList,
  8179. TrackClass: TextTrack,
  8180. capitalName: 'Text'
  8181. }
  8182. };
  8183. Object.keys(NORMAL).forEach(function (type) {
  8184. NORMAL[type].getterName = `${type}Tracks`;
  8185. NORMAL[type].privateName = `${type}Tracks_`;
  8186. });
  8187. const REMOTE = {
  8188. remoteText: {
  8189. ListClass: TextTrackList,
  8190. TrackClass: TextTrack,
  8191. capitalName: 'RemoteText',
  8192. getterName: 'remoteTextTracks',
  8193. privateName: 'remoteTextTracks_'
  8194. },
  8195. remoteTextEl: {
  8196. ListClass: HtmlTrackElementList,
  8197. TrackClass: HTMLTrackElement,
  8198. capitalName: 'RemoteTextTrackEls',
  8199. getterName: 'remoteTextTrackEls',
  8200. privateName: 'remoteTextTrackEls_'
  8201. }
  8202. };
  8203. const ALL = Object.assign({}, NORMAL, REMOTE);
  8204. REMOTE.names = Object.keys(REMOTE);
  8205. NORMAL.names = Object.keys(NORMAL);
  8206. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  8207. var minDoc = {};
  8208. var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : {};
  8209. var doccy;
  8210. if (typeof document !== 'undefined') {
  8211. doccy = document;
  8212. } else {
  8213. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  8214. if (!doccy) {
  8215. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  8216. }
  8217. }
  8218. var document_1 = doccy;
  8219. /**
  8220. * Copyright 2013 vtt.js Contributors
  8221. *
  8222. * Licensed under the Apache License, Version 2.0 (the "License");
  8223. * you may not use this file except in compliance with the License.
  8224. * You may obtain a copy of the License at
  8225. *
  8226. * http://www.apache.org/licenses/LICENSE-2.0
  8227. *
  8228. * Unless required by applicable law or agreed to in writing, software
  8229. * distributed under the License is distributed on an "AS IS" BASIS,
  8230. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8231. * See the License for the specific language governing permissions and
  8232. * limitations under the License.
  8233. */
  8234. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  8235. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  8236. var _objCreate = Object.create || function () {
  8237. function F() {}
  8238. return function (o) {
  8239. if (arguments.length !== 1) {
  8240. throw new Error('Object.create shim only accepts one parameter.');
  8241. }
  8242. F.prototype = o;
  8243. return new F();
  8244. };
  8245. }();
  8246. // Creates a new ParserError object from an errorData object. The errorData
  8247. // object should have default code and message properties. The default message
  8248. // property can be overriden by passing in a message parameter.
  8249. // See ParsingError.Errors below for acceptable errors.
  8250. function ParsingError(errorData, message) {
  8251. this.name = "ParsingError";
  8252. this.code = errorData.code;
  8253. this.message = message || errorData.message;
  8254. }
  8255. ParsingError.prototype = _objCreate(Error.prototype);
  8256. ParsingError.prototype.constructor = ParsingError;
  8257. // ParsingError metadata for acceptable ParsingErrors.
  8258. ParsingError.Errors = {
  8259. BadSignature: {
  8260. code: 0,
  8261. message: "Malformed WebVTT signature."
  8262. },
  8263. BadTimeStamp: {
  8264. code: 1,
  8265. message: "Malformed time stamp."
  8266. }
  8267. };
  8268. // Try to parse input as a time stamp.
  8269. function parseTimeStamp(input) {
  8270. function computeSeconds(h, m, s, f) {
  8271. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  8272. }
  8273. var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
  8274. if (!m) {
  8275. return null;
  8276. }
  8277. if (m[3]) {
  8278. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  8279. return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
  8280. } else if (m[1] > 59) {
  8281. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  8282. // First position is hours as it's over 59.
  8283. return computeSeconds(m[1], m[2], 0, m[4]);
  8284. } else {
  8285. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  8286. return computeSeconds(0, m[1], m[2], m[4]);
  8287. }
  8288. }
  8289. // A settings object holds key/value pairs and will ignore anything but the first
  8290. // assignment to a specific key.
  8291. function Settings() {
  8292. this.values = _objCreate(null);
  8293. }
  8294. Settings.prototype = {
  8295. // Only accept the first assignment to any key.
  8296. set: function (k, v) {
  8297. if (!this.get(k) && v !== "") {
  8298. this.values[k] = v;
  8299. }
  8300. },
  8301. // Return the value for a key, or a default value.
  8302. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  8303. // a number of possible default values as properties where 'defaultKey' is
  8304. // the key of the property that will be chosen; otherwise it's assumed to be
  8305. // a single value.
  8306. get: function (k, dflt, defaultKey) {
  8307. if (defaultKey) {
  8308. return this.has(k) ? this.values[k] : dflt[defaultKey];
  8309. }
  8310. return this.has(k) ? this.values[k] : dflt;
  8311. },
  8312. // Check whether we have a value for a key.
  8313. has: function (k) {
  8314. return k in this.values;
  8315. },
  8316. // Accept a setting if its one of the given alternatives.
  8317. alt: function (k, v, a) {
  8318. for (var n = 0; n < a.length; ++n) {
  8319. if (v === a[n]) {
  8320. this.set(k, v);
  8321. break;
  8322. }
  8323. }
  8324. },
  8325. // Accept a setting if its a valid (signed) integer.
  8326. integer: function (k, v) {
  8327. if (/^-?\d+$/.test(v)) {
  8328. // integer
  8329. this.set(k, parseInt(v, 10));
  8330. }
  8331. },
  8332. // Accept a setting if its a valid percentage.
  8333. percent: function (k, v) {
  8334. if (v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  8335. v = parseFloat(v);
  8336. if (v >= 0 && v <= 100) {
  8337. this.set(k, v);
  8338. return true;
  8339. }
  8340. }
  8341. return false;
  8342. }
  8343. };
  8344. // Helper function to parse input into groups separated by 'groupDelim', and
  8345. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  8346. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  8347. var groups = groupDelim ? input.split(groupDelim) : [input];
  8348. for (var i in groups) {
  8349. if (typeof groups[i] !== "string") {
  8350. continue;
  8351. }
  8352. var kv = groups[i].split(keyValueDelim);
  8353. if (kv.length !== 2) {
  8354. continue;
  8355. }
  8356. var k = kv[0].trim();
  8357. var v = kv[1].trim();
  8358. callback(k, v);
  8359. }
  8360. }
  8361. function parseCue(input, cue, regionList) {
  8362. // Remember the original input if we need to throw an error.
  8363. var oInput = input;
  8364. // 4.1 WebVTT timestamp
  8365. function consumeTimeStamp() {
  8366. var ts = parseTimeStamp(input);
  8367. if (ts === null) {
  8368. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput);
  8369. }
  8370. // Remove time stamp from input.
  8371. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  8372. return ts;
  8373. }
  8374. // 4.4.2 WebVTT cue settings
  8375. function consumeCueSettings(input, cue) {
  8376. var settings = new Settings();
  8377. parseOptions(input, function (k, v) {
  8378. switch (k) {
  8379. case "region":
  8380. // Find the last region we parsed with the same region id.
  8381. for (var i = regionList.length - 1; i >= 0; i--) {
  8382. if (regionList[i].id === v) {
  8383. settings.set(k, regionList[i].region);
  8384. break;
  8385. }
  8386. }
  8387. break;
  8388. case "vertical":
  8389. settings.alt(k, v, ["rl", "lr"]);
  8390. break;
  8391. case "line":
  8392. var vals = v.split(","),
  8393. vals0 = vals[0];
  8394. settings.integer(k, vals0);
  8395. settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
  8396. settings.alt(k, vals0, ["auto"]);
  8397. if (vals.length === 2) {
  8398. settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
  8399. }
  8400. break;
  8401. case "position":
  8402. vals = v.split(",");
  8403. settings.percent(k, vals[0]);
  8404. if (vals.length === 2) {
  8405. settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
  8406. }
  8407. break;
  8408. case "size":
  8409. settings.percent(k, v);
  8410. break;
  8411. case "align":
  8412. settings.alt(k, v, ["start", "center", "end", "left", "right"]);
  8413. break;
  8414. }
  8415. }, /:/, /\s/);
  8416. // Apply default values for any missing fields.
  8417. cue.region = settings.get("region", null);
  8418. cue.vertical = settings.get("vertical", "");
  8419. try {
  8420. cue.line = settings.get("line", "auto");
  8421. } catch (e) {}
  8422. cue.lineAlign = settings.get("lineAlign", "start");
  8423. cue.snapToLines = settings.get("snapToLines", true);
  8424. cue.size = settings.get("size", 100);
  8425. // Safari still uses the old middle value and won't accept center
  8426. try {
  8427. cue.align = settings.get("align", "center");
  8428. } catch (e) {
  8429. cue.align = settings.get("align", "middle");
  8430. }
  8431. try {
  8432. cue.position = settings.get("position", "auto");
  8433. } catch (e) {
  8434. cue.position = settings.get("position", {
  8435. start: 0,
  8436. left: 0,
  8437. center: 50,
  8438. middle: 50,
  8439. end: 100,
  8440. right: 100
  8441. }, cue.align);
  8442. }
  8443. cue.positionAlign = settings.get("positionAlign", {
  8444. start: "start",
  8445. left: "start",
  8446. center: "center",
  8447. middle: "center",
  8448. end: "end",
  8449. right: "end"
  8450. }, cue.align);
  8451. }
  8452. function skipWhitespace() {
  8453. input = input.replace(/^\s+/, "");
  8454. }
  8455. // 4.1 WebVTT cue timings.
  8456. skipWhitespace();
  8457. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  8458. skipWhitespace();
  8459. if (input.substr(0, 3) !== "-->") {
  8460. // (3) next characters must match "-->"
  8461. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  8462. }
  8463. input = input.substr(3);
  8464. skipWhitespace();
  8465. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  8466. // 4.1 WebVTT cue settings list.
  8467. skipWhitespace();
  8468. consumeCueSettings(input, cue);
  8469. }
  8470. // When evaluating this file as part of a Webpack bundle for server
  8471. // side rendering, `document` is an empty object.
  8472. var TEXTAREA_ELEMENT = document_1.createElement && document_1.createElement("textarea");
  8473. var TAG_NAME = {
  8474. c: "span",
  8475. i: "i",
  8476. b: "b",
  8477. u: "u",
  8478. ruby: "ruby",
  8479. rt: "rt",
  8480. v: "span",
  8481. lang: "span"
  8482. };
  8483. // 5.1 default text color
  8484. // 5.2 default text background color is equivalent to text color with bg_ prefix
  8485. var DEFAULT_COLOR_CLASS = {
  8486. white: 'rgba(255,255,255,1)',
  8487. lime: 'rgba(0,255,0,1)',
  8488. cyan: 'rgba(0,255,255,1)',
  8489. red: 'rgba(255,0,0,1)',
  8490. yellow: 'rgba(255,255,0,1)',
  8491. magenta: 'rgba(255,0,255,1)',
  8492. blue: 'rgba(0,0,255,1)',
  8493. black: 'rgba(0,0,0,1)'
  8494. };
  8495. var TAG_ANNOTATION = {
  8496. v: "title",
  8497. lang: "lang"
  8498. };
  8499. var NEEDS_PARENT = {
  8500. rt: "ruby"
  8501. };
  8502. // Parse content into a document fragment.
  8503. function parseContent(window, input) {
  8504. function nextToken() {
  8505. // Check for end-of-string.
  8506. if (!input) {
  8507. return null;
  8508. }
  8509. // Consume 'n' characters from the input.
  8510. function consume(result) {
  8511. input = input.substr(result.length);
  8512. return result;
  8513. }
  8514. var m = input.match(/^([^<]*)(<[^>]*>?)?/);
  8515. // If there is some text before the next tag, return it, otherwise return
  8516. // the tag.
  8517. return consume(m[1] ? m[1] : m[2]);
  8518. }
  8519. function unescape(s) {
  8520. TEXTAREA_ELEMENT.innerHTML = s;
  8521. s = TEXTAREA_ELEMENT.textContent;
  8522. TEXTAREA_ELEMENT.textContent = "";
  8523. return s;
  8524. }
  8525. function shouldAdd(current, element) {
  8526. return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName;
  8527. }
  8528. // Create an element for this tag.
  8529. function createElement(type, annotation) {
  8530. var tagName = TAG_NAME[type];
  8531. if (!tagName) {
  8532. return null;
  8533. }
  8534. var element = window.document.createElement(tagName);
  8535. var name = TAG_ANNOTATION[type];
  8536. if (name && annotation) {
  8537. element[name] = annotation.trim();
  8538. }
  8539. return element;
  8540. }
  8541. var rootDiv = window.document.createElement("div"),
  8542. current = rootDiv,
  8543. t,
  8544. tagStack = [];
  8545. while ((t = nextToken()) !== null) {
  8546. if (t[0] === '<') {
  8547. if (t[1] === "/") {
  8548. // If the closing tag matches, move back up to the parent node.
  8549. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
  8550. tagStack.pop();
  8551. current = current.parentNode;
  8552. }
  8553. // Otherwise just ignore the end tag.
  8554. continue;
  8555. }
  8556. var ts = parseTimeStamp(t.substr(1, t.length - 2));
  8557. var node;
  8558. if (ts) {
  8559. // Timestamps are lead nodes as well.
  8560. node = window.document.createProcessingInstruction("timestamp", ts);
  8561. current.appendChild(node);
  8562. continue;
  8563. }
  8564. var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
  8565. // If we can't parse the tag, skip to the next tag.
  8566. if (!m) {
  8567. continue;
  8568. }
  8569. // Try to construct an element, and ignore the tag if we couldn't.
  8570. node = createElement(m[1], m[3]);
  8571. if (!node) {
  8572. continue;
  8573. }
  8574. // Determine if the tag should be added based on the context of where it
  8575. // is placed in the cuetext.
  8576. if (!shouldAdd(current, node)) {
  8577. continue;
  8578. }
  8579. // Set the class list (as a list of classes, separated by space).
  8580. if (m[2]) {
  8581. var classes = m[2].split('.');
  8582. classes.forEach(function (cl) {
  8583. var bgColor = /^bg_/.test(cl);
  8584. // slice out `bg_` if it's a background color
  8585. var colorName = bgColor ? cl.slice(3) : cl;
  8586. if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
  8587. var propName = bgColor ? 'background-color' : 'color';
  8588. var propValue = DEFAULT_COLOR_CLASS[colorName];
  8589. node.style[propName] = propValue;
  8590. }
  8591. });
  8592. node.className = classes.join(' ');
  8593. }
  8594. // Append the node to the current node, and enter the scope of the new
  8595. // node.
  8596. tagStack.push(m[1]);
  8597. current.appendChild(node);
  8598. current = node;
  8599. continue;
  8600. }
  8601. // Text nodes are leaf nodes.
  8602. current.appendChild(window.document.createTextNode(unescape(t)));
  8603. }
  8604. return rootDiv;
  8605. }
  8606. // This is a list of all the Unicode characters that have a strong
  8607. // right-to-left category. What this means is that these characters are
  8608. // written right-to-left for sure. It was generated by pulling all the strong
  8609. // right-to-left characters out of the Unicode data table. That table can
  8610. // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  8611. var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6], [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d], [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6], [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5], [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815], [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858], [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f], [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c], [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1], [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc], [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808], [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855], [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f], [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13], [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58], [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72], [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f], [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32], [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42], [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f], [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59], [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62], [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77], [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b], [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
  8612. function isStrongRTLChar(charCode) {
  8613. for (var i = 0; i < strongRTLRanges.length; i++) {
  8614. var currentRange = strongRTLRanges[i];
  8615. if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
  8616. return true;
  8617. }
  8618. }
  8619. return false;
  8620. }
  8621. function determineBidi(cueDiv) {
  8622. var nodeStack = [],
  8623. text = "",
  8624. charCode;
  8625. if (!cueDiv || !cueDiv.childNodes) {
  8626. return "ltr";
  8627. }
  8628. function pushNodes(nodeStack, node) {
  8629. for (var i = node.childNodes.length - 1; i >= 0; i--) {
  8630. nodeStack.push(node.childNodes[i]);
  8631. }
  8632. }
  8633. function nextTextNode(nodeStack) {
  8634. if (!nodeStack || !nodeStack.length) {
  8635. return null;
  8636. }
  8637. var node = nodeStack.pop(),
  8638. text = node.textContent || node.innerText;
  8639. if (text) {
  8640. // TODO: This should match all unicode type B characters (paragraph
  8641. // separator characters). See issue #115.
  8642. var m = text.match(/^.*(\n|\r)/);
  8643. if (m) {
  8644. nodeStack.length = 0;
  8645. return m[0];
  8646. }
  8647. return text;
  8648. }
  8649. if (node.tagName === "ruby") {
  8650. return nextTextNode(nodeStack);
  8651. }
  8652. if (node.childNodes) {
  8653. pushNodes(nodeStack, node);
  8654. return nextTextNode(nodeStack);
  8655. }
  8656. }
  8657. pushNodes(nodeStack, cueDiv);
  8658. while (text = nextTextNode(nodeStack)) {
  8659. for (var i = 0; i < text.length; i++) {
  8660. charCode = text.charCodeAt(i);
  8661. if (isStrongRTLChar(charCode)) {
  8662. return "rtl";
  8663. }
  8664. }
  8665. }
  8666. return "ltr";
  8667. }
  8668. function computeLinePos(cue) {
  8669. if (typeof cue.line === "number" && (cue.snapToLines || cue.line >= 0 && cue.line <= 100)) {
  8670. return cue.line;
  8671. }
  8672. if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) {
  8673. return -1;
  8674. }
  8675. var track = cue.track,
  8676. trackList = track.textTrackList,
  8677. count = 0;
  8678. for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
  8679. if (trackList[i].mode === "showing") {
  8680. count++;
  8681. }
  8682. }
  8683. return ++count * -1;
  8684. }
  8685. function StyleBox() {}
  8686. // Apply styles to a div. If there is no div passed then it defaults to the
  8687. // div on 'this'.
  8688. StyleBox.prototype.applyStyles = function (styles, div) {
  8689. div = div || this.div;
  8690. for (var prop in styles) {
  8691. if (styles.hasOwnProperty(prop)) {
  8692. div.style[prop] = styles[prop];
  8693. }
  8694. }
  8695. };
  8696. StyleBox.prototype.formatStyle = function (val, unit) {
  8697. return val === 0 ? 0 : val + unit;
  8698. };
  8699. // Constructs the computed display state of the cue (a div). Places the div
  8700. // into the overlay which should be a block level element (usually a div).
  8701. function CueStyleBox(window, cue, styleOptions) {
  8702. StyleBox.call(this);
  8703. this.cue = cue;
  8704. // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
  8705. // have inline positioning and will function as the cue background box.
  8706. this.cueDiv = parseContent(window, cue.text);
  8707. var styles = {
  8708. color: "rgba(255, 255, 255, 1)",
  8709. backgroundColor: "rgba(0, 0, 0, 0.8)",
  8710. position: "relative",
  8711. left: 0,
  8712. right: 0,
  8713. top: 0,
  8714. bottom: 0,
  8715. display: "inline",
  8716. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8717. unicodeBidi: "plaintext"
  8718. };
  8719. this.applyStyles(styles, this.cueDiv);
  8720. // Create an absolutely positioned div that will be used to position the cue
  8721. // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
  8722. // mirrors of them except middle instead of center on Safari.
  8723. this.div = window.document.createElement("div");
  8724. styles = {
  8725. direction: determineBidi(this.cueDiv),
  8726. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8727. unicodeBidi: "plaintext",
  8728. textAlign: cue.align === "middle" ? "center" : cue.align,
  8729. font: styleOptions.font,
  8730. whiteSpace: "pre-line",
  8731. position: "absolute"
  8732. };
  8733. this.applyStyles(styles);
  8734. this.div.appendChild(this.cueDiv);
  8735. // Calculate the distance from the reference edge of the viewport to the text
  8736. // position of the cue box. The reference edge will be resolved later when
  8737. // the box orientation styles are applied.
  8738. var textPos = 0;
  8739. switch (cue.positionAlign) {
  8740. case "start":
  8741. case "line-left":
  8742. textPos = cue.position;
  8743. break;
  8744. case "center":
  8745. textPos = cue.position - cue.size / 2;
  8746. break;
  8747. case "end":
  8748. case "line-right":
  8749. textPos = cue.position - cue.size;
  8750. break;
  8751. }
  8752. // Horizontal box orientation; textPos is the distance from the left edge of the
  8753. // area to the left edge of the box and cue.size is the distance extending to
  8754. // the right from there.
  8755. if (cue.vertical === "") {
  8756. this.applyStyles({
  8757. left: this.formatStyle(textPos, "%"),
  8758. width: this.formatStyle(cue.size, "%")
  8759. });
  8760. // Vertical box orientation; textPos is the distance from the top edge of the
  8761. // area to the top edge of the box and cue.size is the height extending
  8762. // downwards from there.
  8763. } else {
  8764. this.applyStyles({
  8765. top: this.formatStyle(textPos, "%"),
  8766. height: this.formatStyle(cue.size, "%")
  8767. });
  8768. }
  8769. this.move = function (box) {
  8770. this.applyStyles({
  8771. top: this.formatStyle(box.top, "px"),
  8772. bottom: this.formatStyle(box.bottom, "px"),
  8773. left: this.formatStyle(box.left, "px"),
  8774. right: this.formatStyle(box.right, "px"),
  8775. height: this.formatStyle(box.height, "px"),
  8776. width: this.formatStyle(box.width, "px")
  8777. });
  8778. };
  8779. }
  8780. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  8781. CueStyleBox.prototype.constructor = CueStyleBox;
  8782. // Represents the co-ordinates of an Element in a way that we can easily
  8783. // compute things with such as if it overlaps or intersects with another Element.
  8784. // Can initialize it with either a StyleBox or another BoxPosition.
  8785. function BoxPosition(obj) {
  8786. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  8787. // was passed in and we need to copy the results of 'getBoundingClientRect'
  8788. // as the object returned is readonly. All co-ordinate values are in reference
  8789. // to the viewport origin (top left).
  8790. var lh, height, width, top;
  8791. if (obj.div) {
  8792. height = obj.div.offsetHeight;
  8793. width = obj.div.offsetWidth;
  8794. top = obj.div.offsetTop;
  8795. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects();
  8796. obj = obj.div.getBoundingClientRect();
  8797. // In certain cases the outter div will be slightly larger then the sum of
  8798. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  8799. // In this case we should get the average line height and use that. This will
  8800. // result in the desired behaviour.
  8801. lh = rects ? Math.max(rects[0] && rects[0].height || 0, obj.height / rects.length) : 0;
  8802. }
  8803. this.left = obj.left;
  8804. this.right = obj.right;
  8805. this.top = obj.top || top;
  8806. this.height = obj.height || height;
  8807. this.bottom = obj.bottom || top + (obj.height || height);
  8808. this.width = obj.width || width;
  8809. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  8810. }
  8811. // Move the box along a particular axis. Optionally pass in an amount to move
  8812. // the box. If no amount is passed then the default is the line height of the
  8813. // box.
  8814. BoxPosition.prototype.move = function (axis, toMove) {
  8815. toMove = toMove !== undefined ? toMove : this.lineHeight;
  8816. switch (axis) {
  8817. case "+x":
  8818. this.left += toMove;
  8819. this.right += toMove;
  8820. break;
  8821. case "-x":
  8822. this.left -= toMove;
  8823. this.right -= toMove;
  8824. break;
  8825. case "+y":
  8826. this.top += toMove;
  8827. this.bottom += toMove;
  8828. break;
  8829. case "-y":
  8830. this.top -= toMove;
  8831. this.bottom -= toMove;
  8832. break;
  8833. }
  8834. };
  8835. // Check if this box overlaps another box, b2.
  8836. BoxPosition.prototype.overlaps = function (b2) {
  8837. return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top;
  8838. };
  8839. // Check if this box overlaps any other boxes in boxes.
  8840. BoxPosition.prototype.overlapsAny = function (boxes) {
  8841. for (var i = 0; i < boxes.length; i++) {
  8842. if (this.overlaps(boxes[i])) {
  8843. return true;
  8844. }
  8845. }
  8846. return false;
  8847. };
  8848. // Check if this box is within another box.
  8849. BoxPosition.prototype.within = function (container) {
  8850. return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right;
  8851. };
  8852. // Check if this box is entirely within the container or it is overlapping
  8853. // on the edge opposite of the axis direction passed. For example, if "+x" is
  8854. // passed and the box is overlapping on the left edge of the container, then
  8855. // return true.
  8856. BoxPosition.prototype.overlapsOppositeAxis = function (container, axis) {
  8857. switch (axis) {
  8858. case "+x":
  8859. return this.left < container.left;
  8860. case "-x":
  8861. return this.right > container.right;
  8862. case "+y":
  8863. return this.top < container.top;
  8864. case "-y":
  8865. return this.bottom > container.bottom;
  8866. }
  8867. };
  8868. // Find the percentage of the area that this box is overlapping with another
  8869. // box.
  8870. BoxPosition.prototype.intersectPercentage = function (b2) {
  8871. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  8872. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  8873. intersectArea = x * y;
  8874. return intersectArea / (this.height * this.width);
  8875. };
  8876. // Convert the positions from this box to CSS compatible positions using
  8877. // the reference container's positions. This has to be done because this
  8878. // box's positions are in reference to the viewport origin, whereas, CSS
  8879. // values are in referecne to their respective edges.
  8880. BoxPosition.prototype.toCSSCompatValues = function (reference) {
  8881. return {
  8882. top: this.top - reference.top,
  8883. bottom: reference.bottom - this.bottom,
  8884. left: this.left - reference.left,
  8885. right: reference.right - this.right,
  8886. height: this.height,
  8887. width: this.width
  8888. };
  8889. };
  8890. // Get an object that represents the box's position without anything extra.
  8891. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  8892. BoxPosition.getSimpleBoxPosition = function (obj) {
  8893. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  8894. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  8895. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  8896. obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj;
  8897. var ret = {
  8898. left: obj.left,
  8899. right: obj.right,
  8900. top: obj.top || top,
  8901. height: obj.height || height,
  8902. bottom: obj.bottom || top + (obj.height || height),
  8903. width: obj.width || width
  8904. };
  8905. return ret;
  8906. };
  8907. // Move a StyleBox to its specified, or next best, position. The containerBox
  8908. // is the box that contains the StyleBox, such as a div. boxPositions are
  8909. // a list of other boxes that the styleBox can't overlap with.
  8910. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  8911. // Find the best position for a cue box, b, on the video. The axis parameter
  8912. // is a list of axis, the order of which, it will move the box along. For example:
  8913. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  8914. // direction. If it doesn't find a good position for it there it will then move
  8915. // it along the x axis in the negative direction.
  8916. function findBestPosition(b, axis) {
  8917. var bestPosition,
  8918. specifiedPosition = new BoxPosition(b),
  8919. percentage = 1; // Highest possible so the first thing we get is better.
  8920. for (var i = 0; i < axis.length; i++) {
  8921. while (b.overlapsOppositeAxis(containerBox, axis[i]) || b.within(containerBox) && b.overlapsAny(boxPositions)) {
  8922. b.move(axis[i]);
  8923. }
  8924. // We found a spot where we aren't overlapping anything. This is our
  8925. // best position.
  8926. if (b.within(containerBox)) {
  8927. return b;
  8928. }
  8929. var p = b.intersectPercentage(containerBox);
  8930. // If we're outside the container box less then we were on our last try
  8931. // then remember this position as the best position.
  8932. if (percentage > p) {
  8933. bestPosition = new BoxPosition(b);
  8934. percentage = p;
  8935. }
  8936. // Reset the box position to the specified position.
  8937. b = new BoxPosition(specifiedPosition);
  8938. }
  8939. return bestPosition || specifiedPosition;
  8940. }
  8941. var boxPosition = new BoxPosition(styleBox),
  8942. cue = styleBox.cue,
  8943. linePos = computeLinePos(cue),
  8944. axis = [];
  8945. // If we have a line number to align the cue to.
  8946. if (cue.snapToLines) {
  8947. var size;
  8948. switch (cue.vertical) {
  8949. case "":
  8950. axis = ["+y", "-y"];
  8951. size = "height";
  8952. break;
  8953. case "rl":
  8954. axis = ["+x", "-x"];
  8955. size = "width";
  8956. break;
  8957. case "lr":
  8958. axis = ["-x", "+x"];
  8959. size = "width";
  8960. break;
  8961. }
  8962. var step = boxPosition.lineHeight,
  8963. position = step * Math.round(linePos),
  8964. maxPosition = containerBox[size] + step,
  8965. initialAxis = axis[0];
  8966. // If the specified intial position is greater then the max position then
  8967. // clamp the box to the amount of steps it would take for the box to
  8968. // reach the max position.
  8969. if (Math.abs(position) > maxPosition) {
  8970. position = position < 0 ? -1 : 1;
  8971. position *= Math.ceil(maxPosition / step) * step;
  8972. }
  8973. // If computed line position returns negative then line numbers are
  8974. // relative to the bottom of the video instead of the top. Therefore, we
  8975. // need to increase our initial position by the length or width of the
  8976. // video, depending on the writing direction, and reverse our axis directions.
  8977. if (linePos < 0) {
  8978. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  8979. axis = axis.reverse();
  8980. }
  8981. // Move the box to the specified position. This may not be its best
  8982. // position.
  8983. boxPosition.move(initialAxis, position);
  8984. } else {
  8985. // If we have a percentage line value for the cue.
  8986. var calculatedPercentage = boxPosition.lineHeight / containerBox.height * 100;
  8987. switch (cue.lineAlign) {
  8988. case "center":
  8989. linePos -= calculatedPercentage / 2;
  8990. break;
  8991. case "end":
  8992. linePos -= calculatedPercentage;
  8993. break;
  8994. }
  8995. // Apply initial line position to the cue box.
  8996. switch (cue.vertical) {
  8997. case "":
  8998. styleBox.applyStyles({
  8999. top: styleBox.formatStyle(linePos, "%")
  9000. });
  9001. break;
  9002. case "rl":
  9003. styleBox.applyStyles({
  9004. left: styleBox.formatStyle(linePos, "%")
  9005. });
  9006. break;
  9007. case "lr":
  9008. styleBox.applyStyles({
  9009. right: styleBox.formatStyle(linePos, "%")
  9010. });
  9011. break;
  9012. }
  9013. axis = ["+y", "-x", "+x", "-y"];
  9014. // Get the box position again after we've applied the specified positioning
  9015. // to it.
  9016. boxPosition = new BoxPosition(styleBox);
  9017. }
  9018. var bestPosition = findBestPosition(boxPosition, axis);
  9019. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  9020. }
  9021. function WebVTT$1() {
  9022. // Nothing
  9023. }
  9024. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  9025. WebVTT$1.StringDecoder = function () {
  9026. return {
  9027. decode: function (data) {
  9028. if (!data) {
  9029. return "";
  9030. }
  9031. if (typeof data !== "string") {
  9032. throw new Error("Error - expected string data.");
  9033. }
  9034. return decodeURIComponent(encodeURIComponent(data));
  9035. }
  9036. };
  9037. };
  9038. WebVTT$1.convertCueToDOMTree = function (window, cuetext) {
  9039. if (!window || !cuetext) {
  9040. return null;
  9041. }
  9042. return parseContent(window, cuetext);
  9043. };
  9044. var FONT_SIZE_PERCENT = 0.05;
  9045. var FONT_STYLE = "sans-serif";
  9046. var CUE_BACKGROUND_PADDING = "1.5%";
  9047. // Runs the processing model over the cues and regions passed to it.
  9048. // @param overlay A block level element (usually a div) that the computed cues
  9049. // and regions will be placed into.
  9050. WebVTT$1.processCues = function (window, cues, overlay) {
  9051. if (!window || !cues || !overlay) {
  9052. return null;
  9053. }
  9054. // Remove all previous children.
  9055. while (overlay.firstChild) {
  9056. overlay.removeChild(overlay.firstChild);
  9057. }
  9058. var paddedOverlay = window.document.createElement("div");
  9059. paddedOverlay.style.position = "absolute";
  9060. paddedOverlay.style.left = "0";
  9061. paddedOverlay.style.right = "0";
  9062. paddedOverlay.style.top = "0";
  9063. paddedOverlay.style.bottom = "0";
  9064. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  9065. overlay.appendChild(paddedOverlay);
  9066. // Determine if we need to compute the display states of the cues. This could
  9067. // be the case if a cue's state has been changed since the last computation or
  9068. // if it has not been computed yet.
  9069. function shouldCompute(cues) {
  9070. for (var i = 0; i < cues.length; i++) {
  9071. if (cues[i].hasBeenReset || !cues[i].displayState) {
  9072. return true;
  9073. }
  9074. }
  9075. return false;
  9076. }
  9077. // We don't need to recompute the cues' display states. Just reuse them.
  9078. if (!shouldCompute(cues)) {
  9079. for (var i = 0; i < cues.length; i++) {
  9080. paddedOverlay.appendChild(cues[i].displayState);
  9081. }
  9082. return;
  9083. }
  9084. var boxPositions = [],
  9085. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  9086. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  9087. var styleOptions = {
  9088. font: fontSize + "px " + FONT_STYLE
  9089. };
  9090. (function () {
  9091. var styleBox, cue;
  9092. for (var i = 0; i < cues.length; i++) {
  9093. cue = cues[i];
  9094. // Compute the intial position and styles of the cue div.
  9095. styleBox = new CueStyleBox(window, cue, styleOptions);
  9096. paddedOverlay.appendChild(styleBox.div);
  9097. // Move the cue div to it's correct line position.
  9098. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  9099. // Remember the computed div so that we don't have to recompute it later
  9100. // if we don't have too.
  9101. cue.displayState = styleBox.div;
  9102. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  9103. }
  9104. })();
  9105. };
  9106. WebVTT$1.Parser = function (window, vttjs, decoder) {
  9107. if (!decoder) {
  9108. decoder = vttjs;
  9109. vttjs = {};
  9110. }
  9111. if (!vttjs) {
  9112. vttjs = {};
  9113. }
  9114. this.window = window;
  9115. this.vttjs = vttjs;
  9116. this.state = "INITIAL";
  9117. this.buffer = "";
  9118. this.decoder = decoder || new TextDecoder("utf8");
  9119. this.regionList = [];
  9120. };
  9121. WebVTT$1.Parser.prototype = {
  9122. // If the error is a ParsingError then report it to the consumer if
  9123. // possible. If it's not a ParsingError then throw it like normal.
  9124. reportOrThrowError: function (e) {
  9125. if (e instanceof ParsingError) {
  9126. this.onparsingerror && this.onparsingerror(e);
  9127. } else {
  9128. throw e;
  9129. }
  9130. },
  9131. parse: function (data) {
  9132. var self = this;
  9133. // If there is no data then we won't decode it, but will just try to parse
  9134. // whatever is in buffer already. This may occur in circumstances, for
  9135. // example when flush() is called.
  9136. if (data) {
  9137. // Try to decode the data that we received.
  9138. self.buffer += self.decoder.decode(data, {
  9139. stream: true
  9140. });
  9141. }
  9142. function collectNextLine() {
  9143. var buffer = self.buffer;
  9144. var pos = 0;
  9145. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  9146. ++pos;
  9147. }
  9148. var line = buffer.substr(0, pos);
  9149. // Advance the buffer early in case we fail below.
  9150. if (buffer[pos] === '\r') {
  9151. ++pos;
  9152. }
  9153. if (buffer[pos] === '\n') {
  9154. ++pos;
  9155. }
  9156. self.buffer = buffer.substr(pos);
  9157. return line;
  9158. }
  9159. // 3.4 WebVTT region and WebVTT region settings syntax
  9160. function parseRegion(input) {
  9161. var settings = new Settings();
  9162. parseOptions(input, function (k, v) {
  9163. switch (k) {
  9164. case "id":
  9165. settings.set(k, v);
  9166. break;
  9167. case "width":
  9168. settings.percent(k, v);
  9169. break;
  9170. case "lines":
  9171. settings.integer(k, v);
  9172. break;
  9173. case "regionanchor":
  9174. case "viewportanchor":
  9175. var xy = v.split(',');
  9176. if (xy.length !== 2) {
  9177. break;
  9178. }
  9179. // We have to make sure both x and y parse, so use a temporary
  9180. // settings object here.
  9181. var anchor = new Settings();
  9182. anchor.percent("x", xy[0]);
  9183. anchor.percent("y", xy[1]);
  9184. if (!anchor.has("x") || !anchor.has("y")) {
  9185. break;
  9186. }
  9187. settings.set(k + "X", anchor.get("x"));
  9188. settings.set(k + "Y", anchor.get("y"));
  9189. break;
  9190. case "scroll":
  9191. settings.alt(k, v, ["up"]);
  9192. break;
  9193. }
  9194. }, /=/, /\s/);
  9195. // Create the region, using default values for any values that were not
  9196. // specified.
  9197. if (settings.has("id")) {
  9198. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  9199. region.width = settings.get("width", 100);
  9200. region.lines = settings.get("lines", 3);
  9201. region.regionAnchorX = settings.get("regionanchorX", 0);
  9202. region.regionAnchorY = settings.get("regionanchorY", 100);
  9203. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  9204. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  9205. region.scroll = settings.get("scroll", "");
  9206. // Register the region.
  9207. self.onregion && self.onregion(region);
  9208. // Remember the VTTRegion for later in case we parse any VTTCues that
  9209. // reference it.
  9210. self.regionList.push({
  9211. id: settings.get("id"),
  9212. region: region
  9213. });
  9214. }
  9215. }
  9216. // draft-pantos-http-live-streaming-20
  9217. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  9218. // 3.5 WebVTT
  9219. function parseTimestampMap(input) {
  9220. var settings = new Settings();
  9221. parseOptions(input, function (k, v) {
  9222. switch (k) {
  9223. case "MPEGT":
  9224. settings.integer(k + 'S', v);
  9225. break;
  9226. case "LOCA":
  9227. settings.set(k + 'L', parseTimeStamp(v));
  9228. break;
  9229. }
  9230. }, /[^\d]:/, /,/);
  9231. self.ontimestampmap && self.ontimestampmap({
  9232. "MPEGTS": settings.get("MPEGTS"),
  9233. "LOCAL": settings.get("LOCAL")
  9234. });
  9235. }
  9236. // 3.2 WebVTT metadata header syntax
  9237. function parseHeader(input) {
  9238. if (input.match(/X-TIMESTAMP-MAP/)) {
  9239. // This line contains HLS X-TIMESTAMP-MAP metadata
  9240. parseOptions(input, function (k, v) {
  9241. switch (k) {
  9242. case "X-TIMESTAMP-MAP":
  9243. parseTimestampMap(v);
  9244. break;
  9245. }
  9246. }, /=/);
  9247. } else {
  9248. parseOptions(input, function (k, v) {
  9249. switch (k) {
  9250. case "Region":
  9251. // 3.3 WebVTT region metadata header syntax
  9252. parseRegion(v);
  9253. break;
  9254. }
  9255. }, /:/);
  9256. }
  9257. }
  9258. // 5.1 WebVTT file parsing.
  9259. try {
  9260. var line;
  9261. if (self.state === "INITIAL") {
  9262. // We can't start parsing until we have the first line.
  9263. if (!/\r\n|\n/.test(self.buffer)) {
  9264. return this;
  9265. }
  9266. line = collectNextLine();
  9267. var m = line.match(/^WEBVTT([ \t].*)?$/);
  9268. if (!m || !m[0]) {
  9269. throw new ParsingError(ParsingError.Errors.BadSignature);
  9270. }
  9271. self.state = "HEADER";
  9272. }
  9273. var alreadyCollectedLine = false;
  9274. while (self.buffer) {
  9275. // We can't parse a line until we have the full line.
  9276. if (!/\r\n|\n/.test(self.buffer)) {
  9277. return this;
  9278. }
  9279. if (!alreadyCollectedLine) {
  9280. line = collectNextLine();
  9281. } else {
  9282. alreadyCollectedLine = false;
  9283. }
  9284. switch (self.state) {
  9285. case "HEADER":
  9286. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  9287. if (/:/.test(line)) {
  9288. parseHeader(line);
  9289. } else if (!line) {
  9290. // An empty line terminates the header and starts the body (cues).
  9291. self.state = "ID";
  9292. }
  9293. continue;
  9294. case "NOTE":
  9295. // Ignore NOTE blocks.
  9296. if (!line) {
  9297. self.state = "ID";
  9298. }
  9299. continue;
  9300. case "ID":
  9301. // Check for the start of NOTE blocks.
  9302. if (/^NOTE($|[ \t])/.test(line)) {
  9303. self.state = "NOTE";
  9304. break;
  9305. }
  9306. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  9307. if (!line) {
  9308. continue;
  9309. }
  9310. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  9311. // Safari still uses the old middle value and won't accept center
  9312. try {
  9313. self.cue.align = "center";
  9314. } catch (e) {
  9315. self.cue.align = "middle";
  9316. }
  9317. self.state = "CUE";
  9318. // 30-39 - Check if self line contains an optional identifier or timing data.
  9319. if (line.indexOf("-->") === -1) {
  9320. self.cue.id = line;
  9321. continue;
  9322. }
  9323. // Process line as start of a cue.
  9324. /*falls through*/
  9325. case "CUE":
  9326. // 40 - Collect cue timings and settings.
  9327. try {
  9328. parseCue(line, self.cue, self.regionList);
  9329. } catch (e) {
  9330. self.reportOrThrowError(e);
  9331. // In case of an error ignore rest of the cue.
  9332. self.cue = null;
  9333. self.state = "BADCUE";
  9334. continue;
  9335. }
  9336. self.state = "CUETEXT";
  9337. continue;
  9338. case "CUETEXT":
  9339. var hasSubstring = line.indexOf("-->") !== -1;
  9340. // 34 - If we have an empty line then report the cue.
  9341. // 35 - If we have the special substring '-->' then report the cue,
  9342. // but do not collect the line as we need to process the current
  9343. // one as a new cue.
  9344. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  9345. // We are done parsing self cue.
  9346. self.oncue && self.oncue(self.cue);
  9347. self.cue = null;
  9348. self.state = "ID";
  9349. continue;
  9350. }
  9351. if (self.cue.text) {
  9352. self.cue.text += "\n";
  9353. }
  9354. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  9355. continue;
  9356. case "BADCUE":
  9357. // BADCUE
  9358. // 54-62 - Collect and discard the remaining cue.
  9359. if (!line) {
  9360. self.state = "ID";
  9361. }
  9362. continue;
  9363. }
  9364. }
  9365. } catch (e) {
  9366. self.reportOrThrowError(e);
  9367. // If we are currently parsing a cue, report what we have.
  9368. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  9369. self.oncue(self.cue);
  9370. }
  9371. self.cue = null;
  9372. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  9373. // another exception occurred so enter BADCUE state.
  9374. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  9375. }
  9376. return this;
  9377. },
  9378. flush: function () {
  9379. var self = this;
  9380. try {
  9381. // Finish decoding the stream.
  9382. self.buffer += self.decoder.decode();
  9383. // Synthesize the end of the current cue or region.
  9384. if (self.cue || self.state === "HEADER") {
  9385. self.buffer += "\n\n";
  9386. self.parse();
  9387. }
  9388. // If we've flushed, parsed, and we're still on the INITIAL state then
  9389. // that means we don't have enough of the stream to parse the first
  9390. // line.
  9391. if (self.state === "INITIAL") {
  9392. throw new ParsingError(ParsingError.Errors.BadSignature);
  9393. }
  9394. } catch (e) {
  9395. self.reportOrThrowError(e);
  9396. }
  9397. self.onflush && self.onflush();
  9398. return this;
  9399. }
  9400. };
  9401. var vtt = WebVTT$1;
  9402. /**
  9403. * Copyright 2013 vtt.js Contributors
  9404. *
  9405. * Licensed under the Apache License, Version 2.0 (the "License");
  9406. * you may not use this file except in compliance with the License.
  9407. * You may obtain a copy of the License at
  9408. *
  9409. * http://www.apache.org/licenses/LICENSE-2.0
  9410. *
  9411. * Unless required by applicable law or agreed to in writing, software
  9412. * distributed under the License is distributed on an "AS IS" BASIS,
  9413. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9414. * See the License for the specific language governing permissions and
  9415. * limitations under the License.
  9416. */
  9417. var autoKeyword = "auto";
  9418. var directionSetting = {
  9419. "": 1,
  9420. "lr": 1,
  9421. "rl": 1
  9422. };
  9423. var alignSetting = {
  9424. "start": 1,
  9425. "center": 1,
  9426. "end": 1,
  9427. "left": 1,
  9428. "right": 1,
  9429. "auto": 1,
  9430. "line-left": 1,
  9431. "line-right": 1
  9432. };
  9433. function findDirectionSetting(value) {
  9434. if (typeof value !== "string") {
  9435. return false;
  9436. }
  9437. var dir = directionSetting[value.toLowerCase()];
  9438. return dir ? value.toLowerCase() : false;
  9439. }
  9440. function findAlignSetting(value) {
  9441. if (typeof value !== "string") {
  9442. return false;
  9443. }
  9444. var align = alignSetting[value.toLowerCase()];
  9445. return align ? value.toLowerCase() : false;
  9446. }
  9447. function VTTCue(startTime, endTime, text) {
  9448. /**
  9449. * Shim implementation specific properties. These properties are not in
  9450. * the spec.
  9451. */
  9452. // Lets us know when the VTTCue's data has changed in such a way that we need
  9453. // to recompute its display state. This lets us compute its display state
  9454. // lazily.
  9455. this.hasBeenReset = false;
  9456. /**
  9457. * VTTCue and TextTrackCue properties
  9458. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  9459. */
  9460. var _id = "";
  9461. var _pauseOnExit = false;
  9462. var _startTime = startTime;
  9463. var _endTime = endTime;
  9464. var _text = text;
  9465. var _region = null;
  9466. var _vertical = "";
  9467. var _snapToLines = true;
  9468. var _line = "auto";
  9469. var _lineAlign = "start";
  9470. var _position = "auto";
  9471. var _positionAlign = "auto";
  9472. var _size = 100;
  9473. var _align = "center";
  9474. Object.defineProperties(this, {
  9475. "id": {
  9476. enumerable: true,
  9477. get: function () {
  9478. return _id;
  9479. },
  9480. set: function (value) {
  9481. _id = "" + value;
  9482. }
  9483. },
  9484. "pauseOnExit": {
  9485. enumerable: true,
  9486. get: function () {
  9487. return _pauseOnExit;
  9488. },
  9489. set: function (value) {
  9490. _pauseOnExit = !!value;
  9491. }
  9492. },
  9493. "startTime": {
  9494. enumerable: true,
  9495. get: function () {
  9496. return _startTime;
  9497. },
  9498. set: function (value) {
  9499. if (typeof value !== "number") {
  9500. throw new TypeError("Start time must be set to a number.");
  9501. }
  9502. _startTime = value;
  9503. this.hasBeenReset = true;
  9504. }
  9505. },
  9506. "endTime": {
  9507. enumerable: true,
  9508. get: function () {
  9509. return _endTime;
  9510. },
  9511. set: function (value) {
  9512. if (typeof value !== "number") {
  9513. throw new TypeError("End time must be set to a number.");
  9514. }
  9515. _endTime = value;
  9516. this.hasBeenReset = true;
  9517. }
  9518. },
  9519. "text": {
  9520. enumerable: true,
  9521. get: function () {
  9522. return _text;
  9523. },
  9524. set: function (value) {
  9525. _text = "" + value;
  9526. this.hasBeenReset = true;
  9527. }
  9528. },
  9529. "region": {
  9530. enumerable: true,
  9531. get: function () {
  9532. return _region;
  9533. },
  9534. set: function (value) {
  9535. _region = value;
  9536. this.hasBeenReset = true;
  9537. }
  9538. },
  9539. "vertical": {
  9540. enumerable: true,
  9541. get: function () {
  9542. return _vertical;
  9543. },
  9544. set: function (value) {
  9545. var setting = findDirectionSetting(value);
  9546. // Have to check for false because the setting an be an empty string.
  9547. if (setting === false) {
  9548. throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
  9549. }
  9550. _vertical = setting;
  9551. this.hasBeenReset = true;
  9552. }
  9553. },
  9554. "snapToLines": {
  9555. enumerable: true,
  9556. get: function () {
  9557. return _snapToLines;
  9558. },
  9559. set: function (value) {
  9560. _snapToLines = !!value;
  9561. this.hasBeenReset = true;
  9562. }
  9563. },
  9564. "line": {
  9565. enumerable: true,
  9566. get: function () {
  9567. return _line;
  9568. },
  9569. set: function (value) {
  9570. if (typeof value !== "number" && value !== autoKeyword) {
  9571. throw new SyntaxError("Line: an invalid number or illegal string was specified.");
  9572. }
  9573. _line = value;
  9574. this.hasBeenReset = true;
  9575. }
  9576. },
  9577. "lineAlign": {
  9578. enumerable: true,
  9579. get: function () {
  9580. return _lineAlign;
  9581. },
  9582. set: function (value) {
  9583. var setting = findAlignSetting(value);
  9584. if (!setting) {
  9585. console.warn("lineAlign: an invalid or illegal string was specified.");
  9586. } else {
  9587. _lineAlign = setting;
  9588. this.hasBeenReset = true;
  9589. }
  9590. }
  9591. },
  9592. "position": {
  9593. enumerable: true,
  9594. get: function () {
  9595. return _position;
  9596. },
  9597. set: function (value) {
  9598. if (value < 0 || value > 100) {
  9599. throw new Error("Position must be between 0 and 100.");
  9600. }
  9601. _position = value;
  9602. this.hasBeenReset = true;
  9603. }
  9604. },
  9605. "positionAlign": {
  9606. enumerable: true,
  9607. get: function () {
  9608. return _positionAlign;
  9609. },
  9610. set: function (value) {
  9611. var setting = findAlignSetting(value);
  9612. if (!setting) {
  9613. console.warn("positionAlign: an invalid or illegal string was specified.");
  9614. } else {
  9615. _positionAlign = setting;
  9616. this.hasBeenReset = true;
  9617. }
  9618. }
  9619. },
  9620. "size": {
  9621. enumerable: true,
  9622. get: function () {
  9623. return _size;
  9624. },
  9625. set: function (value) {
  9626. if (value < 0 || value > 100) {
  9627. throw new Error("Size must be between 0 and 100.");
  9628. }
  9629. _size = value;
  9630. this.hasBeenReset = true;
  9631. }
  9632. },
  9633. "align": {
  9634. enumerable: true,
  9635. get: function () {
  9636. return _align;
  9637. },
  9638. set: function (value) {
  9639. var setting = findAlignSetting(value);
  9640. if (!setting) {
  9641. throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
  9642. }
  9643. _align = setting;
  9644. this.hasBeenReset = true;
  9645. }
  9646. }
  9647. });
  9648. /**
  9649. * Other <track> spec defined properties
  9650. */
  9651. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  9652. this.displayState = undefined;
  9653. }
  9654. /**
  9655. * VTTCue methods
  9656. */
  9657. VTTCue.prototype.getCueAsHTML = function () {
  9658. // Assume WebVTT.convertCueToDOMTree is on the global.
  9659. return WebVTT.convertCueToDOMTree(window, this.text);
  9660. };
  9661. var vttcue = VTTCue;
  9662. /**
  9663. * Copyright 2013 vtt.js Contributors
  9664. *
  9665. * Licensed under the Apache License, Version 2.0 (the "License");
  9666. * you may not use this file except in compliance with the License.
  9667. * You may obtain a copy of the License at
  9668. *
  9669. * http://www.apache.org/licenses/LICENSE-2.0
  9670. *
  9671. * Unless required by applicable law or agreed to in writing, software
  9672. * distributed under the License is distributed on an "AS IS" BASIS,
  9673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9674. * See the License for the specific language governing permissions and
  9675. * limitations under the License.
  9676. */
  9677. var scrollSetting = {
  9678. "": true,
  9679. "up": true
  9680. };
  9681. function findScrollSetting(value) {
  9682. if (typeof value !== "string") {
  9683. return false;
  9684. }
  9685. var scroll = scrollSetting[value.toLowerCase()];
  9686. return scroll ? value.toLowerCase() : false;
  9687. }
  9688. function isValidPercentValue(value) {
  9689. return typeof value === "number" && value >= 0 && value <= 100;
  9690. }
  9691. // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
  9692. function VTTRegion() {
  9693. var _width = 100;
  9694. var _lines = 3;
  9695. var _regionAnchorX = 0;
  9696. var _regionAnchorY = 100;
  9697. var _viewportAnchorX = 0;
  9698. var _viewportAnchorY = 100;
  9699. var _scroll = "";
  9700. Object.defineProperties(this, {
  9701. "width": {
  9702. enumerable: true,
  9703. get: function () {
  9704. return _width;
  9705. },
  9706. set: function (value) {
  9707. if (!isValidPercentValue(value)) {
  9708. throw new Error("Width must be between 0 and 100.");
  9709. }
  9710. _width = value;
  9711. }
  9712. },
  9713. "lines": {
  9714. enumerable: true,
  9715. get: function () {
  9716. return _lines;
  9717. },
  9718. set: function (value) {
  9719. if (typeof value !== "number") {
  9720. throw new TypeError("Lines must be set to a number.");
  9721. }
  9722. _lines = value;
  9723. }
  9724. },
  9725. "regionAnchorY": {
  9726. enumerable: true,
  9727. get: function () {
  9728. return _regionAnchorY;
  9729. },
  9730. set: function (value) {
  9731. if (!isValidPercentValue(value)) {
  9732. throw new Error("RegionAnchorX must be between 0 and 100.");
  9733. }
  9734. _regionAnchorY = value;
  9735. }
  9736. },
  9737. "regionAnchorX": {
  9738. enumerable: true,
  9739. get: function () {
  9740. return _regionAnchorX;
  9741. },
  9742. set: function (value) {
  9743. if (!isValidPercentValue(value)) {
  9744. throw new Error("RegionAnchorY must be between 0 and 100.");
  9745. }
  9746. _regionAnchorX = value;
  9747. }
  9748. },
  9749. "viewportAnchorY": {
  9750. enumerable: true,
  9751. get: function () {
  9752. return _viewportAnchorY;
  9753. },
  9754. set: function (value) {
  9755. if (!isValidPercentValue(value)) {
  9756. throw new Error("ViewportAnchorY must be between 0 and 100.");
  9757. }
  9758. _viewportAnchorY = value;
  9759. }
  9760. },
  9761. "viewportAnchorX": {
  9762. enumerable: true,
  9763. get: function () {
  9764. return _viewportAnchorX;
  9765. },
  9766. set: function (value) {
  9767. if (!isValidPercentValue(value)) {
  9768. throw new Error("ViewportAnchorX must be between 0 and 100.");
  9769. }
  9770. _viewportAnchorX = value;
  9771. }
  9772. },
  9773. "scroll": {
  9774. enumerable: true,
  9775. get: function () {
  9776. return _scroll;
  9777. },
  9778. set: function (value) {
  9779. var setting = findScrollSetting(value);
  9780. // Have to check for false as an empty string is a legal value.
  9781. if (setting === false) {
  9782. console.warn("Scroll: an invalid or illegal string was specified.");
  9783. } else {
  9784. _scroll = setting;
  9785. }
  9786. }
  9787. }
  9788. });
  9789. }
  9790. var vttregion = VTTRegion;
  9791. var browserIndex = createCommonjsModule(function (module) {
  9792. /**
  9793. * Copyright 2013 vtt.js Contributors
  9794. *
  9795. * Licensed under the Apache License, Version 2.0 (the "License");
  9796. * you may not use this file except in compliance with the License.
  9797. * You may obtain a copy of the License at
  9798. *
  9799. * http://www.apache.org/licenses/LICENSE-2.0
  9800. *
  9801. * Unless required by applicable law or agreed to in writing, software
  9802. * distributed under the License is distributed on an "AS IS" BASIS,
  9803. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9804. * See the License for the specific language governing permissions and
  9805. * limitations under the License.
  9806. */
  9807. // Default exports for Node. Export the extended versions of VTTCue and
  9808. // VTTRegion in Node since we likely want the capability to convert back and
  9809. // forth between JSON. If we don't then it's not that big of a deal since we're
  9810. // off browser.
  9811. var vttjs = module.exports = {
  9812. WebVTT: vtt,
  9813. VTTCue: vttcue,
  9814. VTTRegion: vttregion
  9815. };
  9816. window_1.vttjs = vttjs;
  9817. window_1.WebVTT = vttjs.WebVTT;
  9818. var cueShim = vttjs.VTTCue;
  9819. var regionShim = vttjs.VTTRegion;
  9820. var nativeVTTCue = window_1.VTTCue;
  9821. var nativeVTTRegion = window_1.VTTRegion;
  9822. vttjs.shim = function () {
  9823. window_1.VTTCue = cueShim;
  9824. window_1.VTTRegion = regionShim;
  9825. };
  9826. vttjs.restore = function () {
  9827. window_1.VTTCue = nativeVTTCue;
  9828. window_1.VTTRegion = nativeVTTRegion;
  9829. };
  9830. if (!window_1.VTTCue) {
  9831. vttjs.shim();
  9832. }
  9833. });
  9834. browserIndex.WebVTT;
  9835. browserIndex.VTTCue;
  9836. browserIndex.VTTRegion;
  9837. /**
  9838. * @file tech.js
  9839. */
  9840. /** @import { TimeRange } from '../utils/time' */
  9841. /**
  9842. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  9843. * that just contains the src url alone.
  9844. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  9845. * `var SourceString = 'http://example.com/some-video.mp4';`
  9846. *
  9847. * @typedef {Object|string} SourceObject
  9848. *
  9849. * @property {string} src
  9850. * The url to the source
  9851. *
  9852. * @property {string} type
  9853. * The mime type of the source
  9854. */
  9855. /**
  9856. * A function used by {@link Tech} to create a new {@link TextTrack}.
  9857. *
  9858. * @private
  9859. *
  9860. * @param {Tech} self
  9861. * An instance of the Tech class.
  9862. *
  9863. * @param {string} kind
  9864. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9865. *
  9866. * @param {string} [label]
  9867. * Label to identify the text track
  9868. *
  9869. * @param {string} [language]
  9870. * Two letter language abbreviation
  9871. *
  9872. * @param {Object} [options={}]
  9873. * An object with additional text track options
  9874. *
  9875. * @return {TextTrack}
  9876. * The text track that was created.
  9877. */
  9878. function createTrackHelper(self, kind, label, language, options = {}) {
  9879. const tracks = self.textTracks();
  9880. options.kind = kind;
  9881. if (label) {
  9882. options.label = label;
  9883. }
  9884. if (language) {
  9885. options.language = language;
  9886. }
  9887. options.tech = self;
  9888. const track = new ALL.text.TrackClass(options);
  9889. tracks.addTrack(track);
  9890. return track;
  9891. }
  9892. /**
  9893. * This is the base class for media playback technology controllers, such as
  9894. * {@link HTML5}
  9895. *
  9896. * @extends Component
  9897. */
  9898. class Tech extends Component {
  9899. /**
  9900. * Create an instance of this Tech.
  9901. *
  9902. * @param {Object} [options]
  9903. * The key/value store of player options.
  9904. *
  9905. * @param {Function} [ready]
  9906. * Callback function to call when the `HTML5` Tech is ready.
  9907. */
  9908. constructor(options = {}, ready = function () {}) {
  9909. // we don't want the tech to report user activity automatically.
  9910. // This is done manually in addControlsListeners
  9911. options.reportTouchActivity = false;
  9912. super(null, options, ready);
  9913. this.onDurationChange_ = e => this.onDurationChange(e);
  9914. this.trackProgress_ = e => this.trackProgress(e);
  9915. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  9916. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  9917. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  9918. this.queuedHanders_ = new Set();
  9919. // keep track of whether the current source has played at all to
  9920. // implement a very limited played()
  9921. this.hasStarted_ = false;
  9922. this.on('playing', function () {
  9923. this.hasStarted_ = true;
  9924. });
  9925. this.on('loadstart', function () {
  9926. this.hasStarted_ = false;
  9927. });
  9928. ALL.names.forEach(name => {
  9929. const props = ALL[name];
  9930. if (options && options[props.getterName]) {
  9931. this[props.privateName] = options[props.getterName];
  9932. }
  9933. });
  9934. // Manually track progress in cases where the browser/tech doesn't report it.
  9935. if (!this.featuresProgressEvents) {
  9936. this.manualProgressOn();
  9937. }
  9938. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  9939. if (!this.featuresTimeupdateEvents) {
  9940. this.manualTimeUpdatesOn();
  9941. }
  9942. ['Text', 'Audio', 'Video'].forEach(track => {
  9943. if (options[`native${track}Tracks`] === false) {
  9944. this[`featuresNative${track}Tracks`] = false;
  9945. }
  9946. });
  9947. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  9948. this.featuresNativeTextTracks = false;
  9949. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  9950. this.featuresNativeTextTracks = true;
  9951. }
  9952. if (!this.featuresNativeTextTracks) {
  9953. this.emulateTextTracks();
  9954. }
  9955. this.preloadTextTracks = options.preloadTextTracks !== false;
  9956. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  9957. this.initTrackListeners();
  9958. // Turn on component tap events only if not using native controls
  9959. if (!options.nativeControlsForTouch) {
  9960. this.emitTapEvents();
  9961. }
  9962. if (this.constructor) {
  9963. this.name_ = this.constructor.name || 'Unknown Tech';
  9964. }
  9965. }
  9966. /**
  9967. * A special function to trigger source set in a way that will allow player
  9968. * to re-trigger if the player or tech are not ready yet.
  9969. *
  9970. * @fires Tech#sourceset
  9971. * @param {string} src The source string at the time of the source changing.
  9972. */
  9973. triggerSourceset(src) {
  9974. if (!this.isReady_) {
  9975. // on initial ready we have to trigger source set
  9976. // 1ms after ready so that player can watch for it.
  9977. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  9978. }
  9979. /**
  9980. * Fired when the source is set on the tech causing the media element
  9981. * to reload.
  9982. *
  9983. * @see {@link Player#event:sourceset}
  9984. * @event Tech#sourceset
  9985. * @type {Event}
  9986. */
  9987. this.trigger({
  9988. src,
  9989. type: 'sourceset'
  9990. });
  9991. }
  9992. /* Fallbacks for unsupported event types
  9993. ================================================================================ */
  9994. /**
  9995. * Polyfill the `progress` event for browsers that don't support it natively.
  9996. *
  9997. * @see {@link Tech#trackProgress}
  9998. */
  9999. manualProgressOn() {
  10000. this.on('durationchange', this.onDurationChange_);
  10001. this.manualProgress = true;
  10002. // Trigger progress watching when a source begins loading
  10003. this.one('ready', this.trackProgress_);
  10004. }
  10005. /**
  10006. * Turn off the polyfill for `progress` events that was created in
  10007. * {@link Tech#manualProgressOn}
  10008. */
  10009. manualProgressOff() {
  10010. this.manualProgress = false;
  10011. this.stopTrackingProgress();
  10012. this.off('durationchange', this.onDurationChange_);
  10013. }
  10014. /**
  10015. * This is used to trigger a `progress` event when the buffered percent changes. It
  10016. * sets an interval function that will be called every 500 milliseconds to check if the
  10017. * buffer end percent has changed.
  10018. *
  10019. * > This function is called by {@link Tech#manualProgressOn}
  10020. *
  10021. * @param {Event} event
  10022. * The `ready` event that caused this to run.
  10023. *
  10024. * @listens Tech#ready
  10025. * @fires Tech#progress
  10026. */
  10027. trackProgress(event) {
  10028. this.stopTrackingProgress();
  10029. this.progressInterval = this.setInterval(bind_(this, function () {
  10030. // Don't trigger unless buffered amount is greater than last time
  10031. const numBufferedPercent = this.bufferedPercent();
  10032. if (this.bufferedPercent_ !== numBufferedPercent) {
  10033. /**
  10034. * See {@link Player#progress}
  10035. *
  10036. * @event Tech#progress
  10037. * @type {Event}
  10038. */
  10039. this.trigger('progress');
  10040. }
  10041. this.bufferedPercent_ = numBufferedPercent;
  10042. if (numBufferedPercent === 1) {
  10043. this.stopTrackingProgress();
  10044. }
  10045. }), 500);
  10046. }
  10047. /**
  10048. * Update our internal duration on a `durationchange` event by calling
  10049. * {@link Tech#duration}.
  10050. *
  10051. * @param {Event} event
  10052. * The `durationchange` event that caused this to run.
  10053. *
  10054. * @listens Tech#durationchange
  10055. */
  10056. onDurationChange(event) {
  10057. this.duration_ = this.duration();
  10058. }
  10059. /**
  10060. * Get and create a `TimeRange` object for buffering.
  10061. *
  10062. * @return {TimeRange}
  10063. * The time range object that was created.
  10064. */
  10065. buffered() {
  10066. return createTimeRanges(0, 0);
  10067. }
  10068. /**
  10069. * Get the percentage of the current video that is currently buffered.
  10070. *
  10071. * @return {number}
  10072. * A number from 0 to 1 that represents the decimal percentage of the
  10073. * video that is buffered.
  10074. *
  10075. */
  10076. bufferedPercent() {
  10077. return bufferedPercent(this.buffered(), this.duration_);
  10078. }
  10079. /**
  10080. * Turn off the polyfill for `progress` events that was created in
  10081. * {@link Tech#manualProgressOn}
  10082. * Stop manually tracking progress events by clearing the interval that was set in
  10083. * {@link Tech#trackProgress}.
  10084. */
  10085. stopTrackingProgress() {
  10086. this.clearInterval(this.progressInterval);
  10087. }
  10088. /**
  10089. * Polyfill the `timeupdate` event for browsers that don't support it.
  10090. *
  10091. * @see {@link Tech#trackCurrentTime}
  10092. */
  10093. manualTimeUpdatesOn() {
  10094. this.manualTimeUpdates = true;
  10095. this.on('play', this.trackCurrentTime_);
  10096. this.on('pause', this.stopTrackingCurrentTime_);
  10097. }
  10098. /**
  10099. * Turn off the polyfill for `timeupdate` events that was created in
  10100. * {@link Tech#manualTimeUpdatesOn}
  10101. */
  10102. manualTimeUpdatesOff() {
  10103. this.manualTimeUpdates = false;
  10104. this.stopTrackingCurrentTime();
  10105. this.off('play', this.trackCurrentTime_);
  10106. this.off('pause', this.stopTrackingCurrentTime_);
  10107. }
  10108. /**
  10109. * Sets up an interval function to track current time and trigger `timeupdate` every
  10110. * 250 milliseconds.
  10111. *
  10112. * @listens Tech#play
  10113. * @triggers Tech#timeupdate
  10114. */
  10115. trackCurrentTime() {
  10116. if (this.currentTimeInterval) {
  10117. this.stopTrackingCurrentTime();
  10118. }
  10119. this.currentTimeInterval = this.setInterval(function () {
  10120. /**
  10121. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  10122. *
  10123. * @event Tech#timeupdate
  10124. * @type {Event}
  10125. */
  10126. this.trigger({
  10127. type: 'timeupdate',
  10128. target: this,
  10129. manuallyTriggered: true
  10130. });
  10131. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  10132. }, 250);
  10133. }
  10134. /**
  10135. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  10136. * `timeupdate` event is no longer triggered.
  10137. *
  10138. * @listens {Tech#pause}
  10139. */
  10140. stopTrackingCurrentTime() {
  10141. this.clearInterval(this.currentTimeInterval);
  10142. // #1002 - if the video ends right before the next timeupdate would happen,
  10143. // the progress bar won't make it all the way to the end
  10144. this.trigger({
  10145. type: 'timeupdate',
  10146. target: this,
  10147. manuallyTriggered: true
  10148. });
  10149. }
  10150. /**
  10151. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  10152. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  10153. *
  10154. * @fires Component#dispose
  10155. */
  10156. dispose() {
  10157. // clear out all tracks because we can't reuse them between techs
  10158. this.clearTracks(NORMAL.names);
  10159. // Turn off any manual progress or timeupdate tracking
  10160. if (this.manualProgress) {
  10161. this.manualProgressOff();
  10162. }
  10163. if (this.manualTimeUpdates) {
  10164. this.manualTimeUpdatesOff();
  10165. }
  10166. super.dispose();
  10167. }
  10168. /**
  10169. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  10170. *
  10171. * > Note: Techs without source handlers should call this between sources for `video`
  10172. * & `audio` tracks. You don't want to use them between tracks!
  10173. *
  10174. * @param {string[]|string} types
  10175. * TrackList names to clear, valid names are `video`, `audio`, and
  10176. * `text`.
  10177. */
  10178. clearTracks(types) {
  10179. types = [].concat(types);
  10180. // clear out all tracks because we can't reuse them between techs
  10181. types.forEach(type => {
  10182. const list = this[`${type}Tracks`]() || [];
  10183. let i = list.length;
  10184. while (i--) {
  10185. const track = list[i];
  10186. if (type === 'text') {
  10187. this.removeRemoteTextTrack(track);
  10188. }
  10189. list.removeTrack(track);
  10190. }
  10191. });
  10192. }
  10193. /**
  10194. * Remove any TextTracks added via addRemoteTextTrack that are
  10195. * flagged for automatic garbage collection
  10196. */
  10197. cleanupAutoTextTracks() {
  10198. const list = this.autoRemoteTextTracks_ || [];
  10199. let i = list.length;
  10200. while (i--) {
  10201. const track = list[i];
  10202. this.removeRemoteTextTrack(track);
  10203. }
  10204. }
  10205. /**
  10206. * Reset the tech, which will removes all sources and reset the internal readyState.
  10207. *
  10208. * @abstract
  10209. */
  10210. reset() {}
  10211. /**
  10212. * Get the value of `crossOrigin` from the tech.
  10213. *
  10214. * @abstract
  10215. *
  10216. * @see {Html5#crossOrigin}
  10217. */
  10218. crossOrigin() {}
  10219. /**
  10220. * Set the value of `crossOrigin` on the tech.
  10221. *
  10222. * @abstract
  10223. *
  10224. * @param {string} crossOrigin the crossOrigin value
  10225. * @see {Html5#setCrossOrigin}
  10226. */
  10227. setCrossOrigin() {}
  10228. /**
  10229. * Get or set an error on the Tech.
  10230. *
  10231. * @param {MediaError} [err]
  10232. * Error to set on the Tech
  10233. *
  10234. * @return {MediaError|null}
  10235. * The current error object on the tech, or null if there isn't one.
  10236. */
  10237. error(err) {
  10238. if (err !== undefined) {
  10239. this.error_ = new MediaError(err);
  10240. this.trigger('error');
  10241. }
  10242. return this.error_;
  10243. }
  10244. /**
  10245. * Returns the `TimeRange`s that have been played through for the current source.
  10246. *
  10247. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  10248. * It only checks whether the source has played at all or not.
  10249. *
  10250. * @return {TimeRange}
  10251. * - A single time range if this video has played
  10252. * - An empty set of ranges if not.
  10253. */
  10254. played() {
  10255. if (this.hasStarted_) {
  10256. return createTimeRanges(0, 0);
  10257. }
  10258. return createTimeRanges();
  10259. }
  10260. /**
  10261. * Start playback
  10262. *
  10263. * @abstract
  10264. *
  10265. * @see {Html5#play}
  10266. */
  10267. play() {}
  10268. /**
  10269. * Set whether we are scrubbing or not
  10270. *
  10271. * @abstract
  10272. * @param {boolean} _isScrubbing
  10273. * - true for we are currently scrubbing
  10274. * - false for we are no longer scrubbing
  10275. *
  10276. * @see {Html5#setScrubbing}
  10277. */
  10278. setScrubbing(_isScrubbing) {}
  10279. /**
  10280. * Get whether we are scrubbing or not
  10281. *
  10282. * @abstract
  10283. *
  10284. * @see {Html5#scrubbing}
  10285. */
  10286. scrubbing() {}
  10287. /**
  10288. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  10289. * previously called.
  10290. *
  10291. * @param {number} _seconds
  10292. * Set the current time of the media to this.
  10293. * @fires Tech#timeupdate
  10294. */
  10295. setCurrentTime(_seconds) {
  10296. // improve the accuracy of manual timeupdates
  10297. if (this.manualTimeUpdates) {
  10298. /**
  10299. * A manual `timeupdate` event.
  10300. *
  10301. * @event Tech#timeupdate
  10302. * @type {Event}
  10303. */
  10304. this.trigger({
  10305. type: 'timeupdate',
  10306. target: this,
  10307. manuallyTriggered: true
  10308. });
  10309. }
  10310. }
  10311. /**
  10312. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  10313. * {@link TextTrackList} events.
  10314. *
  10315. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  10316. *
  10317. * @fires Tech#audiotrackchange
  10318. * @fires Tech#videotrackchange
  10319. * @fires Tech#texttrackchange
  10320. */
  10321. initTrackListeners() {
  10322. /**
  10323. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  10324. *
  10325. * @event Tech#audiotrackchange
  10326. * @type {Event}
  10327. */
  10328. /**
  10329. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  10330. *
  10331. * @event Tech#videotrackchange
  10332. * @type {Event}
  10333. */
  10334. /**
  10335. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  10336. *
  10337. * @event Tech#texttrackchange
  10338. * @type {Event}
  10339. */
  10340. NORMAL.names.forEach(name => {
  10341. const props = NORMAL[name];
  10342. const trackListChanges = () => {
  10343. this.trigger(`${name}trackchange`);
  10344. };
  10345. const tracks = this[props.getterName]();
  10346. tracks.addEventListener('removetrack', trackListChanges);
  10347. tracks.addEventListener('addtrack', trackListChanges);
  10348. this.on('dispose', () => {
  10349. tracks.removeEventListener('removetrack', trackListChanges);
  10350. tracks.removeEventListener('addtrack', trackListChanges);
  10351. });
  10352. });
  10353. }
  10354. /**
  10355. * Emulate TextTracks using vtt.js if necessary
  10356. *
  10357. * @fires Tech#vttjsloaded
  10358. * @fires Tech#vttjserror
  10359. */
  10360. addWebVttScript_() {
  10361. if (window.WebVTT) {
  10362. return;
  10363. }
  10364. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  10365. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  10366. // before inserting the WebVTT script
  10367. if (document.body.contains(this.el())) {
  10368. // load via require if available and vtt.js script location was not passed in
  10369. // as an option. novtt builds will turn the above require call into an empty object
  10370. // which will cause this if check to always fail.
  10371. if (!this.options_['vtt.js'] && isPlain(browserIndex) && Object.keys(browserIndex).length > 0) {
  10372. this.trigger('vttjsloaded');
  10373. return;
  10374. }
  10375. // load vtt.js via the script location option or the cdn of no location was
  10376. // passed in
  10377. const script = document.createElement('script');
  10378. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  10379. script.onload = () => {
  10380. /**
  10381. * Fired when vtt.js is loaded.
  10382. *
  10383. * @event Tech#vttjsloaded
  10384. * @type {Event}
  10385. */
  10386. this.trigger('vttjsloaded');
  10387. };
  10388. script.onerror = () => {
  10389. /**
  10390. * Fired when vtt.js was not loaded due to an error
  10391. *
  10392. * @event Tech#vttjsloaded
  10393. * @type {Event}
  10394. */
  10395. this.trigger('vttjserror');
  10396. };
  10397. this.on('dispose', () => {
  10398. script.onload = null;
  10399. script.onerror = null;
  10400. });
  10401. // but have not loaded yet and we set it to true before the inject so that
  10402. // we don't overwrite the injected window.WebVTT if it loads right away
  10403. window.WebVTT = true;
  10404. this.el().parentNode.appendChild(script);
  10405. } else {
  10406. this.ready(this.addWebVttScript_);
  10407. }
  10408. }
  10409. /**
  10410. * Emulate texttracks
  10411. *
  10412. */
  10413. emulateTextTracks() {
  10414. const tracks = this.textTracks();
  10415. const remoteTracks = this.remoteTextTracks();
  10416. const handleAddTrack = e => tracks.addTrack(e.track);
  10417. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  10418. remoteTracks.on('addtrack', handleAddTrack);
  10419. remoteTracks.on('removetrack', handleRemoveTrack);
  10420. this.addWebVttScript_();
  10421. const updateDisplay = () => this.trigger('texttrackchange');
  10422. const textTracksChanges = () => {
  10423. updateDisplay();
  10424. for (let i = 0; i < tracks.length; i++) {
  10425. const track = tracks[i];
  10426. track.removeEventListener('cuechange', updateDisplay);
  10427. if (track.mode === 'showing') {
  10428. track.addEventListener('cuechange', updateDisplay);
  10429. }
  10430. }
  10431. };
  10432. textTracksChanges();
  10433. tracks.addEventListener('change', textTracksChanges);
  10434. tracks.addEventListener('addtrack', textTracksChanges);
  10435. tracks.addEventListener('removetrack', textTracksChanges);
  10436. this.on('dispose', function () {
  10437. remoteTracks.off('addtrack', handleAddTrack);
  10438. remoteTracks.off('removetrack', handleRemoveTrack);
  10439. tracks.removeEventListener('change', textTracksChanges);
  10440. tracks.removeEventListener('addtrack', textTracksChanges);
  10441. tracks.removeEventListener('removetrack', textTracksChanges);
  10442. for (let i = 0; i < tracks.length; i++) {
  10443. const track = tracks[i];
  10444. track.removeEventListener('cuechange', updateDisplay);
  10445. }
  10446. });
  10447. }
  10448. /**
  10449. * Create and returns a remote {@link TextTrack} object.
  10450. *
  10451. * @param {string} kind
  10452. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  10453. *
  10454. * @param {string} [label]
  10455. * Label to identify the text track
  10456. *
  10457. * @param {string} [language]
  10458. * Two letter language abbreviation
  10459. *
  10460. * @return {TextTrack}
  10461. * The TextTrack that gets created.
  10462. */
  10463. addTextTrack(kind, label, language) {
  10464. if (!kind) {
  10465. throw new Error('TextTrack kind is required but was not provided');
  10466. }
  10467. return createTrackHelper(this, kind, label, language);
  10468. }
  10469. /**
  10470. * Create an emulated TextTrack for use by addRemoteTextTrack
  10471. *
  10472. * This is intended to be overridden by classes that inherit from
  10473. * Tech in order to create native or custom TextTracks.
  10474. *
  10475. * @param {Object} options
  10476. * The object should contain the options to initialize the TextTrack with.
  10477. *
  10478. * @param {string} [options.kind]
  10479. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  10480. *
  10481. * @param {string} [options.label].
  10482. * Label to identify the text track
  10483. *
  10484. * @param {string} [options.language]
  10485. * Two letter language abbreviation.
  10486. *
  10487. * @return {HTMLTrackElement}
  10488. * The track element that gets created.
  10489. */
  10490. createRemoteTextTrack(options) {
  10491. const track = merge(options, {
  10492. tech: this
  10493. });
  10494. return new REMOTE.remoteTextEl.TrackClass(track);
  10495. }
  10496. /**
  10497. * Creates a remote text track object and returns an html track element.
  10498. *
  10499. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  10500. *
  10501. * @param {Object} options
  10502. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  10503. *
  10504. * @param {boolean} [manualCleanup=false]
  10505. * - When false: the TextTrack will be automatically removed from the video
  10506. * element whenever the source changes
  10507. * - When True: The TextTrack will have to be cleaned up manually
  10508. *
  10509. * @return {HTMLTrackElement}
  10510. * An Html Track Element.
  10511. *
  10512. */
  10513. addRemoteTextTrack(options = {}, manualCleanup) {
  10514. const htmlTrackElement = this.createRemoteTextTrack(options);
  10515. if (typeof manualCleanup !== 'boolean') {
  10516. manualCleanup = false;
  10517. }
  10518. // store HTMLTrackElement and TextTrack to remote list
  10519. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  10520. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  10521. if (manualCleanup === false) {
  10522. // create the TextTrackList if it doesn't exist
  10523. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  10524. }
  10525. return htmlTrackElement;
  10526. }
  10527. /**
  10528. * Remove a remote text track from the remote `TextTrackList`.
  10529. *
  10530. * @param {TextTrack} track
  10531. * `TextTrack` to remove from the `TextTrackList`
  10532. */
  10533. removeRemoteTextTrack(track) {
  10534. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  10535. // remove HTMLTrackElement and TextTrack from remote list
  10536. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  10537. this.remoteTextTracks().removeTrack(track);
  10538. this.autoRemoteTextTracks_.removeTrack(track);
  10539. }
  10540. /**
  10541. * Gets available media playback quality metrics as specified by the W3C's Media
  10542. * Playback Quality API.
  10543. *
  10544. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  10545. *
  10546. * @return {Object}
  10547. * An object with supported media playback quality metrics
  10548. *
  10549. * @abstract
  10550. */
  10551. getVideoPlaybackQuality() {
  10552. return {};
  10553. }
  10554. /**
  10555. * Attempt to create a floating video window always on top of other windows
  10556. * so that users may continue consuming media while they interact with other
  10557. * content sites, or applications on their device.
  10558. *
  10559. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  10560. *
  10561. * @return {Promise|undefined}
  10562. * A promise with a Picture-in-Picture window if the browser supports
  10563. * Promises (or one was passed in as an option). It returns undefined
  10564. * otherwise.
  10565. *
  10566. * @abstract
  10567. */
  10568. requestPictureInPicture() {
  10569. return Promise.reject();
  10570. }
  10571. /**
  10572. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  10573. * Defaults to true, as it should be considered disabled if the tech does not support pip
  10574. *
  10575. * @abstract
  10576. */
  10577. disablePictureInPicture() {
  10578. return true;
  10579. }
  10580. /**
  10581. * A method to set or unset the 'disablePictureInPicture' <video> property.
  10582. *
  10583. * @abstract
  10584. */
  10585. setDisablePictureInPicture() {}
  10586. /**
  10587. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  10588. *
  10589. * @param {function} cb
  10590. * @return {number} request id
  10591. */
  10592. requestVideoFrameCallback(cb) {
  10593. const id = newGUID();
  10594. if (!this.isReady_ || this.paused()) {
  10595. this.queuedHanders_.add(id);
  10596. this.one('playing', () => {
  10597. if (this.queuedHanders_.has(id)) {
  10598. this.queuedHanders_.delete(id);
  10599. cb();
  10600. }
  10601. });
  10602. } else {
  10603. this.requestNamedAnimationFrame(id, cb);
  10604. }
  10605. return id;
  10606. }
  10607. /**
  10608. * A fallback implementation of cancelVideoFrameCallback
  10609. *
  10610. * @param {number} id id of callback to be cancelled
  10611. */
  10612. cancelVideoFrameCallback(id) {
  10613. if (this.queuedHanders_.has(id)) {
  10614. this.queuedHanders_.delete(id);
  10615. } else {
  10616. this.cancelNamedAnimationFrame(id);
  10617. }
  10618. }
  10619. /**
  10620. * A method to set a poster from a `Tech`.
  10621. *
  10622. * @abstract
  10623. */
  10624. setPoster() {}
  10625. /**
  10626. * A method to check for the presence of the 'playsinline' <video> attribute.
  10627. *
  10628. * @abstract
  10629. */
  10630. playsinline() {}
  10631. /**
  10632. * A method to set or unset the 'playsinline' <video> attribute.
  10633. *
  10634. * @abstract
  10635. */
  10636. setPlaysinline() {}
  10637. /**
  10638. * Attempt to force override of native audio tracks.
  10639. *
  10640. * @param {boolean} override - If set to true native audio will be overridden,
  10641. * otherwise native audio will potentially be used.
  10642. *
  10643. * @abstract
  10644. */
  10645. overrideNativeAudioTracks(override) {}
  10646. /**
  10647. * Attempt to force override of native video tracks.
  10648. *
  10649. * @param {boolean} override - If set to true native video will be overridden,
  10650. * otherwise native video will potentially be used.
  10651. *
  10652. * @abstract
  10653. */
  10654. overrideNativeVideoTracks(override) {}
  10655. /**
  10656. * Check if the tech can support the given mime-type.
  10657. *
  10658. * The base tech does not support any type, but source handlers might
  10659. * overwrite this.
  10660. *
  10661. * @param {string} _type
  10662. * The mimetype to check for support
  10663. *
  10664. * @return {string}
  10665. * 'probably', 'maybe', or empty string
  10666. *
  10667. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  10668. *
  10669. * @abstract
  10670. */
  10671. canPlayType(_type) {
  10672. return '';
  10673. }
  10674. /**
  10675. * Check if the type is supported by this tech.
  10676. *
  10677. * The base tech does not support any type, but source handlers might
  10678. * overwrite this.
  10679. *
  10680. * @param {string} _type
  10681. * The media type to check
  10682. * @return {string} Returns the native video element's response
  10683. */
  10684. static canPlayType(_type) {
  10685. return '';
  10686. }
  10687. /**
  10688. * Check if the tech can support the given source
  10689. *
  10690. * @param {Object} srcObj
  10691. * The source object
  10692. * @param {Object} options
  10693. * The options passed to the tech
  10694. * @return {string} 'probably', 'maybe', or '' (empty string)
  10695. */
  10696. static canPlaySource(srcObj, options) {
  10697. return Tech.canPlayType(srcObj.type);
  10698. }
  10699. /*
  10700. * Return whether the argument is a Tech or not.
  10701. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  10702. *
  10703. * @param {Object} component
  10704. * The item to check
  10705. *
  10706. * @return {boolean}
  10707. * Whether it is a tech or not
  10708. * - True if it is a tech
  10709. * - False if it is not
  10710. */
  10711. static isTech(component) {
  10712. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  10713. }
  10714. /**
  10715. * Registers a `Tech` into a shared list for videojs.
  10716. *
  10717. * @param {string} name
  10718. * Name of the `Tech` to register.
  10719. *
  10720. * @param {Object} tech
  10721. * The `Tech` class to register.
  10722. */
  10723. static registerTech(name, tech) {
  10724. if (!Tech.techs_) {
  10725. Tech.techs_ = {};
  10726. }
  10727. if (!Tech.isTech(tech)) {
  10728. throw new Error(`Tech ${name} must be a Tech`);
  10729. }
  10730. if (!Tech.canPlayType) {
  10731. throw new Error('Techs must have a static canPlayType method on them');
  10732. }
  10733. if (!Tech.canPlaySource) {
  10734. throw new Error('Techs must have a static canPlaySource method on them');
  10735. }
  10736. name = toTitleCase(name);
  10737. Tech.techs_[name] = tech;
  10738. Tech.techs_[toLowerCase(name)] = tech;
  10739. if (name !== 'Tech') {
  10740. // camel case the techName for use in techOrder
  10741. Tech.defaultTechOrder_.push(name);
  10742. }
  10743. return tech;
  10744. }
  10745. /**
  10746. * Get a `Tech` from the shared list by name.
  10747. *
  10748. * @param {string} name
  10749. * `camelCase` or `TitleCase` name of the Tech to get
  10750. *
  10751. * @return {Tech|undefined}
  10752. * The `Tech` or undefined if there was no tech with the name requested.
  10753. */
  10754. static getTech(name) {
  10755. if (!name) {
  10756. return;
  10757. }
  10758. if (Tech.techs_ && Tech.techs_[name]) {
  10759. return Tech.techs_[name];
  10760. }
  10761. name = toTitleCase(name);
  10762. if (window && window.videojs && window.videojs[name]) {
  10763. log.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  10764. return window.videojs[name];
  10765. }
  10766. }
  10767. }
  10768. /**
  10769. * Get the {@link VideoTrackList}
  10770. *
  10771. * @returns {VideoTrackList}
  10772. * @method Tech.prototype.videoTracks
  10773. */
  10774. /**
  10775. * Get the {@link AudioTrackList}
  10776. *
  10777. * @returns {AudioTrackList}
  10778. * @method Tech.prototype.audioTracks
  10779. */
  10780. /**
  10781. * Get the {@link TextTrackList}
  10782. *
  10783. * @returns {TextTrackList}
  10784. * @method Tech.prototype.textTracks
  10785. */
  10786. /**
  10787. * Get the remote element {@link TextTrackList}
  10788. *
  10789. * @returns {TextTrackList}
  10790. * @method Tech.prototype.remoteTextTracks
  10791. */
  10792. /**
  10793. * Get the remote element {@link HtmlTrackElementList}
  10794. *
  10795. * @returns {HtmlTrackElementList}
  10796. * @method Tech.prototype.remoteTextTrackEls
  10797. */
  10798. ALL.names.forEach(function (name) {
  10799. const props = ALL[name];
  10800. Tech.prototype[props.getterName] = function () {
  10801. this[props.privateName] = this[props.privateName] || new props.ListClass();
  10802. return this[props.privateName];
  10803. };
  10804. });
  10805. /**
  10806. * List of associated text tracks
  10807. *
  10808. * @type {TextTrackList}
  10809. * @private
  10810. * @property Tech#textTracks_
  10811. */
  10812. /**
  10813. * List of associated audio tracks.
  10814. *
  10815. * @type {AudioTrackList}
  10816. * @private
  10817. * @property Tech#audioTracks_
  10818. */
  10819. /**
  10820. * List of associated video tracks.
  10821. *
  10822. * @type {VideoTrackList}
  10823. * @private
  10824. * @property Tech#videoTracks_
  10825. */
  10826. /**
  10827. * Boolean indicating whether the `Tech` supports volume control.
  10828. *
  10829. * @type {boolean}
  10830. * @default
  10831. */
  10832. Tech.prototype.featuresVolumeControl = true;
  10833. /**
  10834. * Boolean indicating whether the `Tech` supports muting volume.
  10835. *
  10836. * @type {boolean}
  10837. * @default
  10838. */
  10839. Tech.prototype.featuresMuteControl = true;
  10840. /**
  10841. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  10842. * Resizing plugins using request fullscreen reloads the plugin
  10843. *
  10844. * @type {boolean}
  10845. * @default
  10846. */
  10847. Tech.prototype.featuresFullscreenResize = false;
  10848. /**
  10849. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  10850. * plays. Examples:
  10851. * - Set player to play 2x (twice) as fast
  10852. * - Set player to play 0.5x (half) as fast
  10853. *
  10854. * @type {boolean}
  10855. * @default
  10856. */
  10857. Tech.prototype.featuresPlaybackRate = false;
  10858. /**
  10859. * Boolean indicating whether the `Tech` supports the `progress` event.
  10860. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  10861. *
  10862. * @type {boolean}
  10863. * @default
  10864. */
  10865. Tech.prototype.featuresProgressEvents = false;
  10866. /**
  10867. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  10868. *
  10869. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  10870. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  10871. * a new source.
  10872. *
  10873. * @type {boolean}
  10874. * @default
  10875. */
  10876. Tech.prototype.featuresSourceset = false;
  10877. /**
  10878. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  10879. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  10880. *
  10881. * @type {boolean}
  10882. * @default
  10883. */
  10884. Tech.prototype.featuresTimeupdateEvents = false;
  10885. /**
  10886. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  10887. * This will help us integrate with native `TextTrack`s if the browser supports them.
  10888. *
  10889. * @type {boolean}
  10890. * @default
  10891. */
  10892. Tech.prototype.featuresNativeTextTracks = false;
  10893. /**
  10894. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  10895. *
  10896. * @type {boolean}
  10897. * @default
  10898. */
  10899. Tech.prototype.featuresVideoFrameCallback = false;
  10900. /**
  10901. * A functional mixin for techs that want to use the Source Handler pattern.
  10902. * Source handlers are scripts for handling specific formats.
  10903. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  10904. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  10905. * Example: `Tech.withSourceHandlers.call(MyTech);`
  10906. *
  10907. * @param {Tech} _Tech
  10908. * The tech to add source handler functions to.
  10909. *
  10910. * @mixes Tech~SourceHandlerAdditions
  10911. */
  10912. Tech.withSourceHandlers = function (_Tech) {
  10913. /**
  10914. * Register a source handler
  10915. *
  10916. * @param {Function} handler
  10917. * The source handler class
  10918. *
  10919. * @param {number} [index]
  10920. * Register it at the following index
  10921. */
  10922. _Tech.registerSourceHandler = function (handler, index) {
  10923. let handlers = _Tech.sourceHandlers;
  10924. if (!handlers) {
  10925. handlers = _Tech.sourceHandlers = [];
  10926. }
  10927. if (index === undefined) {
  10928. // add to the end of the list
  10929. index = handlers.length;
  10930. }
  10931. handlers.splice(index, 0, handler);
  10932. };
  10933. /**
  10934. * Check if the tech can support the given type. Also checks the
  10935. * Techs sourceHandlers.
  10936. *
  10937. * @param {string} type
  10938. * The mimetype to check.
  10939. *
  10940. * @return {string}
  10941. * 'probably', 'maybe', or '' (empty string)
  10942. */
  10943. _Tech.canPlayType = function (type) {
  10944. const handlers = _Tech.sourceHandlers || [];
  10945. let can;
  10946. for (let i = 0; i < handlers.length; i++) {
  10947. can = handlers[i].canPlayType(type);
  10948. if (can) {
  10949. return can;
  10950. }
  10951. }
  10952. return '';
  10953. };
  10954. /**
  10955. * Returns the first source handler that supports the source.
  10956. *
  10957. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  10958. *
  10959. * @param {SourceObject} source
  10960. * The source object
  10961. *
  10962. * @param {Object} options
  10963. * The options passed to the tech
  10964. *
  10965. * @return {SourceHandler|null}
  10966. * The first source handler that supports the source or null if
  10967. * no SourceHandler supports the source
  10968. */
  10969. _Tech.selectSourceHandler = function (source, options) {
  10970. const handlers = _Tech.sourceHandlers || [];
  10971. let can;
  10972. for (let i = 0; i < handlers.length; i++) {
  10973. can = handlers[i].canHandleSource(source, options);
  10974. if (can) {
  10975. return handlers[i];
  10976. }
  10977. }
  10978. return null;
  10979. };
  10980. /**
  10981. * Check if the tech can support the given source.
  10982. *
  10983. * @param {SourceObject} srcObj
  10984. * The source object
  10985. *
  10986. * @param {Object} options
  10987. * The options passed to the tech
  10988. *
  10989. * @return {string}
  10990. * 'probably', 'maybe', or '' (empty string)
  10991. */
  10992. _Tech.canPlaySource = function (srcObj, options) {
  10993. const sh = _Tech.selectSourceHandler(srcObj, options);
  10994. if (sh) {
  10995. return sh.canHandleSource(srcObj, options);
  10996. }
  10997. return '';
  10998. };
  10999. /**
  11000. * When using a source handler, prefer its implementation of
  11001. * any function normally provided by the tech.
  11002. */
  11003. const deferrable = ['seekable', 'seeking', 'duration'];
  11004. /**
  11005. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  11006. * function if it exists, with a fallback to the Techs seekable function.
  11007. *
  11008. * @method _Tech.seekable
  11009. */
  11010. /**
  11011. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  11012. * function if it exists, otherwise it will fallback to the techs duration function.
  11013. *
  11014. * @method _Tech.duration
  11015. */
  11016. deferrable.forEach(function (fnName) {
  11017. const originalFn = this[fnName];
  11018. if (typeof originalFn !== 'function') {
  11019. return;
  11020. }
  11021. this[fnName] = function () {
  11022. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  11023. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  11024. }
  11025. return originalFn.apply(this, arguments);
  11026. };
  11027. }, _Tech.prototype);
  11028. /**
  11029. * Create a function for setting the source using a source object
  11030. * and source handlers.
  11031. * Should never be called unless a source handler was found.
  11032. *
  11033. * @param {SourceObject} source
  11034. * A source object with src and type keys
  11035. */
  11036. _Tech.prototype.setSource = function (source) {
  11037. let sh = _Tech.selectSourceHandler(source, this.options_);
  11038. if (!sh) {
  11039. // Fall back to a native source handler when unsupported sources are
  11040. // deliberately set
  11041. if (_Tech.nativeSourceHandler) {
  11042. sh = _Tech.nativeSourceHandler;
  11043. } else {
  11044. log.error('No source handler found for the current source.');
  11045. }
  11046. }
  11047. // Dispose any existing source handler
  11048. this.disposeSourceHandler();
  11049. this.off('dispose', this.disposeSourceHandler_);
  11050. if (sh !== _Tech.nativeSourceHandler) {
  11051. this.currentSource_ = source;
  11052. }
  11053. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  11054. this.one('dispose', this.disposeSourceHandler_);
  11055. };
  11056. /**
  11057. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  11058. *
  11059. * @listens Tech#dispose
  11060. */
  11061. _Tech.prototype.disposeSourceHandler = function () {
  11062. // if we have a source and get another one
  11063. // then we are loading something new
  11064. // than clear all of our current tracks
  11065. if (this.currentSource_) {
  11066. this.clearTracks(['audio', 'video']);
  11067. this.currentSource_ = null;
  11068. }
  11069. // always clean up auto-text tracks
  11070. this.cleanupAutoTextTracks();
  11071. if (this.sourceHandler_) {
  11072. if (this.sourceHandler_.dispose) {
  11073. this.sourceHandler_.dispose();
  11074. }
  11075. this.sourceHandler_ = null;
  11076. }
  11077. };
  11078. };
  11079. // The base Tech class needs to be registered as a Component. It is the only
  11080. // Tech that can be registered as a Component.
  11081. Component.registerComponent('Tech', Tech);
  11082. Tech.registerTech('Tech', Tech);
  11083. /**
  11084. * A list of techs that should be added to techOrder on Players
  11085. *
  11086. * @private
  11087. */
  11088. Tech.defaultTechOrder_ = [];
  11089. /**
  11090. * @file middleware.js
  11091. * @module middleware
  11092. */
  11093. /** @import Player from '../player' */
  11094. /** @import Tech from '../tech/tech' */
  11095. const middlewares = {};
  11096. const middlewareInstances = {};
  11097. const TERMINATOR = {};
  11098. /**
  11099. * A middleware object is a plain JavaScript object that has methods that
  11100. * match the {@link Tech} methods found in the lists of allowed
  11101. * {@link module:middleware.allowedGetters|getters},
  11102. * {@link module:middleware.allowedSetters|setters}, and
  11103. * {@link module:middleware.allowedMediators|mediators}.
  11104. *
  11105. * @typedef {Object} MiddlewareObject
  11106. */
  11107. /**
  11108. * A middleware factory function that should return a
  11109. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  11110. *
  11111. * This factory will be called for each player when needed, with the player
  11112. * passed in as an argument.
  11113. *
  11114. * @callback MiddlewareFactory
  11115. * @param {Player} player
  11116. * A Video.js player.
  11117. */
  11118. /**
  11119. * Define a middleware that the player should use by way of a factory function
  11120. * that returns a middleware object.
  11121. *
  11122. * @param {string} type
  11123. * The MIME type to match or `"*"` for all MIME types.
  11124. *
  11125. * @param {MiddlewareFactory} middleware
  11126. * A middleware factory function that will be executed for
  11127. * matching types.
  11128. */
  11129. function use(type, middleware) {
  11130. middlewares[type] = middlewares[type] || [];
  11131. middlewares[type].push(middleware);
  11132. }
  11133. /**
  11134. * Asynchronously sets a source using middleware by recursing through any
  11135. * matching middlewares and calling `setSource` on each, passing along the
  11136. * previous returned value each time.
  11137. *
  11138. * @param {Player} player
  11139. * A {@link Player} instance.
  11140. *
  11141. * @param {Tech~SourceObject} src
  11142. * A source object.
  11143. *
  11144. * @param {Function}
  11145. * The next middleware to run.
  11146. */
  11147. function setSource(player, src, next) {
  11148. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  11149. }
  11150. /**
  11151. * When the tech is set, passes the tech to each middleware's `setTech` method.
  11152. *
  11153. * @param {Object[]} middleware
  11154. * An array of middleware instances.
  11155. *
  11156. * @param {Tech} tech
  11157. * A Video.js tech.
  11158. */
  11159. function setTech(middleware, tech) {
  11160. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  11161. }
  11162. /**
  11163. * Calls a getter on the tech first, through each middleware
  11164. * from right to left to the player.
  11165. *
  11166. * @param {Object[]} middleware
  11167. * An array of middleware instances.
  11168. *
  11169. * @param {Tech} tech
  11170. * The current tech.
  11171. *
  11172. * @param {string} method
  11173. * A method name.
  11174. *
  11175. * @return {*}
  11176. * The final value from the tech after middleware has intercepted it.
  11177. */
  11178. function get(middleware, tech, method) {
  11179. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  11180. }
  11181. /**
  11182. * Takes the argument given to the player and calls the setter method on each
  11183. * middleware from left to right to the tech.
  11184. *
  11185. * @param {Object[]} middleware
  11186. * An array of middleware instances.
  11187. *
  11188. * @param {Tech} tech
  11189. * The current tech.
  11190. *
  11191. * @param {string} method
  11192. * A method name.
  11193. *
  11194. * @param {*} arg
  11195. * The value to set on the tech.
  11196. *
  11197. * @return {*}
  11198. * The return value of the `method` of the `tech`.
  11199. */
  11200. function set(middleware, tech, method, arg) {
  11201. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  11202. }
  11203. /**
  11204. * Takes the argument given to the player and calls the `call` version of the
  11205. * method on each middleware from left to right.
  11206. *
  11207. * Then, call the passed in method on the tech and return the result unchanged
  11208. * back to the player, through middleware, this time from right to left.
  11209. *
  11210. * @param {Object[]} middleware
  11211. * An array of middleware instances.
  11212. *
  11213. * @param {Tech} tech
  11214. * The current tech.
  11215. *
  11216. * @param {string} method
  11217. * A method name.
  11218. *
  11219. * @param {*} arg
  11220. * The value to set on the tech.
  11221. *
  11222. * @return {*}
  11223. * The return value of the `method` of the `tech`, regardless of the
  11224. * return values of middlewares.
  11225. */
  11226. function mediate(middleware, tech, method, arg = null) {
  11227. const callMethod = 'call' + toTitleCase(method);
  11228. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  11229. const terminated = middlewareValue === TERMINATOR;
  11230. // deprecated. The `null` return value should instead return TERMINATOR to
  11231. // prevent confusion if a techs method actually returns null.
  11232. const returnValue = terminated ? null : tech[method](middlewareValue);
  11233. executeRight(middleware, method, returnValue, terminated);
  11234. return returnValue;
  11235. }
  11236. /**
  11237. * Enumeration of allowed getters where the keys are method names.
  11238. *
  11239. * @type {Object}
  11240. */
  11241. const allowedGetters = {
  11242. buffered: 1,
  11243. currentTime: 1,
  11244. duration: 1,
  11245. muted: 1,
  11246. played: 1,
  11247. paused: 1,
  11248. seekable: 1,
  11249. volume: 1,
  11250. ended: 1
  11251. };
  11252. /**
  11253. * Enumeration of allowed setters where the keys are method names.
  11254. *
  11255. * @type {Object}
  11256. */
  11257. const allowedSetters = {
  11258. setCurrentTime: 1,
  11259. setMuted: 1,
  11260. setVolume: 1
  11261. };
  11262. /**
  11263. * Enumeration of allowed mediators where the keys are method names.
  11264. *
  11265. * @type {Object}
  11266. */
  11267. const allowedMediators = {
  11268. play: 1,
  11269. pause: 1
  11270. };
  11271. function middlewareIterator(method) {
  11272. return (value, mw) => {
  11273. // if the previous middleware terminated, pass along the termination
  11274. if (value === TERMINATOR) {
  11275. return TERMINATOR;
  11276. }
  11277. if (mw[method]) {
  11278. return mw[method](value);
  11279. }
  11280. return value;
  11281. };
  11282. }
  11283. function executeRight(mws, method, value, terminated) {
  11284. for (let i = mws.length - 1; i >= 0; i--) {
  11285. const mw = mws[i];
  11286. if (mw[method]) {
  11287. mw[method](terminated, value);
  11288. }
  11289. }
  11290. }
  11291. /**
  11292. * Clear the middleware cache for a player.
  11293. *
  11294. * @param {Player} player
  11295. * A {@link Player} instance.
  11296. */
  11297. function clearCacheForPlayer(player) {
  11298. if (middlewareInstances.hasOwnProperty(player.id())) {
  11299. delete middlewareInstances[player.id()];
  11300. }
  11301. }
  11302. /**
  11303. * {
  11304. * [playerId]: [[mwFactory, mwInstance], ...]
  11305. * }
  11306. *
  11307. * @private
  11308. */
  11309. function getOrCreateFactory(player, mwFactory) {
  11310. const mws = middlewareInstances[player.id()];
  11311. let mw = null;
  11312. if (mws === undefined || mws === null) {
  11313. mw = mwFactory(player);
  11314. middlewareInstances[player.id()] = [[mwFactory, mw]];
  11315. return mw;
  11316. }
  11317. for (let i = 0; i < mws.length; i++) {
  11318. const [mwf, mwi] = mws[i];
  11319. if (mwf !== mwFactory) {
  11320. continue;
  11321. }
  11322. mw = mwi;
  11323. }
  11324. if (mw === null) {
  11325. mw = mwFactory(player);
  11326. mws.push([mwFactory, mw]);
  11327. }
  11328. return mw;
  11329. }
  11330. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  11331. const [mwFactory, ...mwrest] = middleware;
  11332. // if mwFactory is a string, then we're at a fork in the road
  11333. if (typeof mwFactory === 'string') {
  11334. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  11335. // if we have an mwFactory, call it with the player to get the mw,
  11336. // then call the mw's setSource method
  11337. } else if (mwFactory) {
  11338. const mw = getOrCreateFactory(player, mwFactory);
  11339. // if setSource isn't present, implicitly select this middleware
  11340. if (!mw.setSource) {
  11341. acc.push(mw);
  11342. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  11343. }
  11344. mw.setSource(Object.assign({}, src), function (err, _src) {
  11345. // something happened, try the next middleware on the current level
  11346. // make sure to use the old src
  11347. if (err) {
  11348. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  11349. }
  11350. // we've succeeded, now we need to go deeper
  11351. acc.push(mw);
  11352. // if it's the same type, continue down the current chain
  11353. // otherwise, we want to go down the new chain
  11354. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  11355. });
  11356. } else if (mwrest.length) {
  11357. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  11358. } else if (lastRun) {
  11359. next(src, acc);
  11360. } else {
  11361. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  11362. }
  11363. }
  11364. /** @import Player from '../player' */
  11365. /**
  11366. * Mimetypes
  11367. *
  11368. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  11369. * @typedef Mimetypes~Kind
  11370. * @enum
  11371. */
  11372. const MimetypesKind = {
  11373. opus: 'video/ogg',
  11374. ogv: 'video/ogg',
  11375. mp4: 'video/mp4',
  11376. mov: 'video/mp4',
  11377. m4v: 'video/mp4',
  11378. mkv: 'video/x-matroska',
  11379. m4a: 'audio/mp4',
  11380. mp3: 'audio/mpeg',
  11381. aac: 'audio/aac',
  11382. caf: 'audio/x-caf',
  11383. flac: 'audio/flac',
  11384. oga: 'audio/ogg',
  11385. wav: 'audio/wav',
  11386. m3u8: 'application/x-mpegURL',
  11387. mpd: 'application/dash+xml',
  11388. jpg: 'image/jpeg',
  11389. jpeg: 'image/jpeg',
  11390. gif: 'image/gif',
  11391. png: 'image/png',
  11392. svg: 'image/svg+xml',
  11393. webp: 'image/webp'
  11394. };
  11395. /**
  11396. * Get the mimetype of a given src url if possible
  11397. *
  11398. * @param {string} src
  11399. * The url to the src
  11400. *
  11401. * @return {string}
  11402. * return the mimetype if it was known or empty string otherwise
  11403. */
  11404. const getMimetype = function (src = '') {
  11405. const ext = getFileExtension(src);
  11406. const mimetype = MimetypesKind[ext.toLowerCase()];
  11407. return mimetype || '';
  11408. };
  11409. /**
  11410. * Find the mime type of a given source string if possible. Uses the player
  11411. * source cache.
  11412. *
  11413. * @param {Player} player
  11414. * The player object
  11415. *
  11416. * @param {string} src
  11417. * The source string
  11418. *
  11419. * @return {string}
  11420. * The type that was found
  11421. */
  11422. const findMimetype = (player, src) => {
  11423. if (!src) {
  11424. return '';
  11425. }
  11426. // 1. check for the type in the `source` cache
  11427. if (player.cache_.source.src === src && player.cache_.source.type) {
  11428. return player.cache_.source.type;
  11429. }
  11430. // 2. see if we have this source in our `currentSources` cache
  11431. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  11432. if (matchingSources.length) {
  11433. return matchingSources[0].type;
  11434. }
  11435. // 3. look for the src url in source elements and use the type there
  11436. const sources = player.$$('source');
  11437. for (let i = 0; i < sources.length; i++) {
  11438. const s = sources[i];
  11439. if (s.type && s.src && s.src === src) {
  11440. return s.type;
  11441. }
  11442. }
  11443. // 4. finally fallback to our list of mime types based on src url extension
  11444. return getMimetype(src);
  11445. };
  11446. /**
  11447. * @module filter-source
  11448. */
  11449. /**
  11450. * Filter out single bad source objects or multiple source objects in an
  11451. * array. Also flattens nested source object arrays into a 1 dimensional
  11452. * array of source objects.
  11453. *
  11454. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  11455. * The src object to filter
  11456. *
  11457. * @return {Tech~SourceObject[]}
  11458. * An array of sourceobjects containing only valid sources
  11459. *
  11460. * @private
  11461. */
  11462. const filterSource = function (src) {
  11463. // traverse array
  11464. if (Array.isArray(src)) {
  11465. let newsrc = [];
  11466. src.forEach(function (srcobj) {
  11467. srcobj = filterSource(srcobj);
  11468. if (Array.isArray(srcobj)) {
  11469. newsrc = newsrc.concat(srcobj);
  11470. } else if (isObject(srcobj)) {
  11471. newsrc.push(srcobj);
  11472. }
  11473. });
  11474. src = newsrc;
  11475. } else if (typeof src === 'string' && src.trim()) {
  11476. // convert string into object
  11477. src = [fixSource({
  11478. src
  11479. })];
  11480. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  11481. // src is already valid
  11482. src = [fixSource(src)];
  11483. } else {
  11484. // invalid source, turn it into an empty array
  11485. src = [];
  11486. }
  11487. return src;
  11488. };
  11489. /**
  11490. * Checks src mimetype, adding it when possible
  11491. *
  11492. * @param {Tech~SourceObject} src
  11493. * The src object to check
  11494. * @return {Tech~SourceObject}
  11495. * src Object with known type
  11496. */
  11497. function fixSource(src) {
  11498. if (!src.type) {
  11499. const mimetype = getMimetype(src.src);
  11500. if (mimetype) {
  11501. src.type = mimetype;
  11502. }
  11503. }
  11504. return src;
  11505. }
  11506. var icons = "<svg xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-play\">\n <path d=\"M16 10v28l22-14z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-pause\">\n <path d=\"M12 38h8V10h-8v28zm16-28v28h8V10h-8z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-audio\">\n <path d=\"M24 2C14.06 2 6 10.06 6 20v14c0 3.31 2.69 6 6 6h6V24h-8v-4c0-7.73 6.27-14 14-14s14 6.27 14 14v4h-8v16h6c3.31 0 6-2.69 6-6V20c0-9.94-8.06-18-18-18z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-captions\">\n <path d=\"M38 8H10c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM22 22h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2zm14 0h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-subtitles\">\n <path d=\"M40 8H8c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM8 24h8v4H8v-4zm20 12H8v-4h20v4zm12 0h-8v-4h8v4zm0-8H20v-4h20v4z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-fullscreen-enter\">\n <path d=\"M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-fullscreen-exit\">\n <path d=\"M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-play-circle\">\n <path d=\"M20 33l12-9-12-9v18zm4-29C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-volume-mute\">\n <path d=\"M33 24c0-3.53-2.04-6.58-5-8.05v4.42l4.91 4.91c.06-.42.09-.85.09-1.28zm5 0c0 1.88-.41 3.65-1.08 5.28l3.03 3.03C41.25 29.82 42 27 42 24c0-8.56-5.99-15.72-14-17.54v4.13c5.78 1.72 10 7.07 10 13.41zM8.55 6L6 8.55 15.45 18H6v12h8l10 10V26.55l8.51 8.51c-1.34 1.03-2.85 1.86-4.51 2.36v4.13a17.94 17.94 0 0 0 7.37-3.62L39.45 42 42 39.45l-18-18L8.55 6zM24 8l-4.18 4.18L24 16.36V8z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-volume-low\">\n <path d=\"M14 18v12h8l10 10V8L22 18h-8z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-volume-medium\">\n <path d=\"M37 24c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zm-27-6v12h8l10 10V8L18 18h-8z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-volume-high\">\n <path d=\"M6 18v12h8l10 10V8L14 18H6zm27 6c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zM28 6.46v4.13c5.78 1.72 10 7.07 10 13.41s-4.22 11.69-10 13.41v4.13c8.01-1.82 14-8.97 14-17.54S36.01 8.28 28 6.46z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-spinner\">\n <path d=\"M18.8 21l9.53-16.51C26.94 4.18 25.49 4 24 4c-4.8 0-9.19 1.69-12.64 4.51l7.33 12.69.11-.2zm24.28-3c-1.84-5.85-6.3-10.52-11.99-12.68L23.77 18h19.31zm.52 2H28.62l.58 1 9.53 16.5C41.99 33.94 44 29.21 44 24c0-1.37-.14-2.71-.4-4zm-26.53 4l-7.8-13.5C6.01 14.06 4 18.79 4 24c0 1.37.14 2.71.4 4h14.98l-2.31-4zM4.92 30c1.84 5.85 6.3 10.52 11.99 12.68L24.23 30H4.92zm22.54 0l-7.8 13.51c1.4.31 2.85.49 4.34.49 4.8 0 9.19-1.69 12.64-4.51L29.31 26.8 27.46 30z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 24 24\" id=\"vjs-icon-hd\">\n <path d=\"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 48 48\" id=\"vjs-icon-chapters\">\n <path d=\"M6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm8 8h28v-4H14v4zm0 8h28v-4H14v4zm0-20v4h28v-4H14z\"></path>\n </symbol>\n <symbol viewBox=\"0 0 40 40\" id=\"vjs-icon-downloading\">\n <path d=\
  11507. // /**
  11508. // Determine the keycode for the 'back' key based on the platform
  11509. const backKeyCode = IS_TIZEN ? 10009 : IS_WEBOS ? 461 : 8;
  11510. const SpatialNavKeyCodes = {
  11511. codes: {
  11512. play: 415,
  11513. pause: 19,
  11514. ff: 417,
  11515. rw: 412,
  11516. back: backKeyCode
  11517. },
  11518. names: {
  11519. 415: 'play',
  11520. 19: 'pause',
  11521. 417: 'ff',
  11522. 412: 'rw',
  11523. [backKeyCode]: 'back'
  11524. },
  11525. isEventKey(event, keyName) {
  11526. keyName = keyName.toLowerCase();
  11527. if (this.names[event.keyCode] && this.names[event.keyCode] === keyName) {
  11528. return true;
  11529. }
  11530. return false;
  11531. },
  11532. getEventName(event) {
  11533. if (this.names[event.keyCode]) {
  11534. return this.names[event.keyCode];
  11535. } else if (this.codes[event.code]) {
  11536. const code = this.codes[event.code];
  11537. return this.names[code];
  11538. }
  11539. return null;
  11540. }
  11541. };
  11542. /**
  11543. * @file spatial-navigation.js
  11544. */
  11545. /** @import Component from './component' */
  11546. /** @import Player from './player' */
  11547. // The number of seconds the `step*` functions move the timeline.
  11548. const STEP_SECONDS$1 = 5;
  11549. /**
  11550. * Spatial Navigation in Video.js enhances user experience and accessibility on smartTV devices,
  11551. * enabling seamless navigation through interactive elements within the player using remote control arrow keys.
  11552. * This functionality allows users to effortlessly navigate through focusable components.
  11553. *
  11554. * @extends EventTarget
  11555. */
  11556. class SpatialNavigation extends EventTarget {
  11557. /**
  11558. * Constructs a SpatialNavigation instance with initial settings.
  11559. * Sets up the player instance, and prepares the spatial navigation system.
  11560. *
  11561. * @class
  11562. * @param {Player} player - The Video.js player instance to which the spatial navigation is attached.
  11563. */
  11564. constructor(player) {
  11565. super();
  11566. this.player_ = player;
  11567. this.focusableComponents = [];
  11568. this.isListening_ = false;
  11569. this.isPaused_ = false;
  11570. this.onKeyDown_ = this.onKeyDown_.bind(this);
  11571. this.lastFocusedComponent_ = null;
  11572. }
  11573. /**
  11574. * Starts the spatial navigation by adding a keydown event listener to the video container.
  11575. * This method ensures that the event listener is added only once.
  11576. */
  11577. start() {
  11578. // If the listener is already active, exit early.
  11579. if (this.isListening_) {
  11580. return;
  11581. }
  11582. // Add the event listener since the listener is not yet active.
  11583. this.player_.on('keydown', this.onKeyDown_);
  11584. this.player_.on('modalKeydown', this.onKeyDown_);
  11585. // Listen for source change events
  11586. this.player_.on('loadedmetadata', () => {
  11587. this.focus(this.updateFocusableComponents()[0]);
  11588. });
  11589. this.player_.on('modalclose', () => {
  11590. this.refocusComponent();
  11591. });
  11592. this.player_.on('focusin', this.handlePlayerFocus_.bind(this));
  11593. this.player_.on('focusout', this.handlePlayerBlur_.bind(this));
  11594. this.isListening_ = true;
  11595. if (this.player_.errorDisplay) {
  11596. this.player_.errorDisplay.on('aftermodalfill', () => {
  11597. this.updateFocusableComponents();
  11598. if (this.focusableComponents.length) {
  11599. // The modal has focusable components:
  11600. if (this.focusableComponents.length > 1) {
  11601. // The modal has close button + some additional buttons.
  11602. // Focusing first additional button:
  11603. this.focusableComponents[1].focus();
  11604. } else {
  11605. // The modal has only close button,
  11606. // Focusing it:
  11607. this.focusableComponents[0].focus();
  11608. }
  11609. }
  11610. });
  11611. }
  11612. }
  11613. /**
  11614. * Stops the spatial navigation by removing the keydown event listener from the video container.
  11615. * Also sets the `isListening_` flag to false.
  11616. */
  11617. stop() {
  11618. this.player_.off('keydown', this.onKeyDown_);
  11619. this.isListening_ = false;
  11620. }
  11621. /**
  11622. * Responds to keydown events for spatial navigation and media control.
  11623. *
  11624. * Determines if spatial navigation or media control is active and handles key inputs accordingly.
  11625. *
  11626. * @param {KeyboardEvent} event - The keydown event to be handled.
  11627. */
  11628. onKeyDown_(event) {
  11629. // Determine if the event is a custom modalKeydown event
  11630. const actualEvent = event.originalEvent ? event.originalEvent : event;
  11631. if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(actualEvent.key)) {
  11632. // Handle directional navigation
  11633. if (this.isPaused_) {
  11634. return;
  11635. }
  11636. actualEvent.preventDefault();
  11637. // "ArrowLeft" => "left" etc
  11638. const direction = actualEvent.key.substring(5).toLowerCase();
  11639. this.move(direction);
  11640. } else if (SpatialNavKeyCodes.isEventKey(actualEvent, 'play') || SpatialNavKeyCodes.isEventKey(actualEvent, 'pause') || SpatialNavKeyCodes.isEventKey(actualEvent, 'ff') || SpatialNavKeyCodes.isEventKey(actualEvent, 'rw')) {
  11641. // Handle media actions
  11642. actualEvent.preventDefault();
  11643. const action = SpatialNavKeyCodes.getEventName(actualEvent);
  11644. this.performMediaAction_(action);
  11645. } else if (SpatialNavKeyCodes.isEventKey(actualEvent, 'Back') && event.target && typeof event.target.closeable === 'function' && event.target.closeable()) {
  11646. actualEvent.preventDefault();
  11647. event.target.close();
  11648. }
  11649. }
  11650. /**
  11651. * Performs media control actions based on the given key input.
  11652. *
  11653. * Controls the playback and seeking functionalities of the media player.
  11654. *
  11655. * @param {string} key - The key representing the media action to be performed.
  11656. * Accepted keys: 'play', 'pause', 'ff' (fast-forward), 'rw' (rewind).
  11657. */
  11658. performMediaAction_(key) {
  11659. if (this.player_) {
  11660. switch (key) {
  11661. case 'play':
  11662. if (this.player_.paused()) {
  11663. this.player_.play();
  11664. }
  11665. break;
  11666. case 'pause':
  11667. if (!this.player_.paused()) {
  11668. this.player_.pause();
  11669. }
  11670. break;
  11671. case 'ff':
  11672. this.userSeek_(this.player_.currentTime() + STEP_SECONDS$1);
  11673. break;
  11674. case 'rw':
  11675. this.userSeek_(this.player_.currentTime() - STEP_SECONDS$1);
  11676. break;
  11677. }
  11678. }
  11679. }
  11680. /**
  11681. * Prevent liveThreshold from causing seeks to seem like they
  11682. * are not happening from a user perspective.
  11683. *
  11684. * @param {number} ct
  11685. * current time to seek to
  11686. */
  11687. userSeek_(ct) {
  11688. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11689. this.player_.liveTracker.nextSeekedFromUser();
  11690. }
  11691. this.player_.currentTime(ct);
  11692. }
  11693. /**
  11694. * Pauses the spatial navigation functionality.
  11695. * This method sets a flag that can be used to temporarily disable the navigation logic.
  11696. */
  11697. pause() {
  11698. this.isPaused_ = true;
  11699. }
  11700. /**
  11701. * Resumes the spatial navigation functionality if it has been paused.
  11702. * This method resets the pause flag, re-enabling the navigation logic.
  11703. */
  11704. resume() {
  11705. this.isPaused_ = false;
  11706. }
  11707. /**
  11708. * Handles Player Blur.
  11709. *
  11710. * @param {string|Event|Object} event
  11711. * The name of the event, an `Event`, or an object with a key of type set to
  11712. * an event name.
  11713. *
  11714. * Calls for handling of the Player Blur if:
  11715. * *The next focused element is not a child of current focused element &
  11716. * The next focused element is not a child of the Player.
  11717. * *There is no next focused element
  11718. */
  11719. handlePlayerBlur_(event) {
  11720. const nextFocusedElement = event.relatedTarget;
  11721. let isChildrenOfPlayer = null;
  11722. const currentComponent = this.getCurrentComponent(event.target);
  11723. if (nextFocusedElement) {
  11724. isChildrenOfPlayer = Boolean(nextFocusedElement.closest('.video-js'));
  11725. // If nextFocusedElement is the 'TextTrackSettings' component
  11726. if (nextFocusedElement.classList.contains('vjs-text-track-settings') && !this.isPaused_) {
  11727. this.searchForTrackSelect_();
  11728. }
  11729. }
  11730. if (!event.currentTarget.contains(event.relatedTarget) && !isChildrenOfPlayer || !nextFocusedElement) {
  11731. if (currentComponent && currentComponent.name() === 'CloseButton') {
  11732. this.refocusComponent();
  11733. } else {
  11734. this.pause();
  11735. if (currentComponent && currentComponent.el()) {
  11736. // Store last focused component
  11737. this.lastFocusedComponent_ = currentComponent;
  11738. }
  11739. }
  11740. }
  11741. }
  11742. /**
  11743. * Handles the Player focus event.
  11744. *
  11745. * Calls for handling of the Player Focus if current element is focusable.
  11746. */
  11747. handlePlayerFocus_() {
  11748. if (this.getCurrentComponent() && this.getCurrentComponent().getIsFocusable()) {
  11749. this.resume();
  11750. }
  11751. }
  11752. /**
  11753. * Gets a set of focusable components.
  11754. *
  11755. * @return {Array}
  11756. * Returns an array of focusable components.
  11757. */
  11758. updateFocusableComponents() {
  11759. const player = this.player_;
  11760. const focusableComponents = [];
  11761. /**
  11762. * Searches for children candidates.
  11763. *
  11764. * Pushes Components to array of 'focusableComponents'.
  11765. * Calls itself if there is children elements inside iterated component.
  11766. *
  11767. * @param {Array} componentsArray - The array of components to search for focusable children.
  11768. */
  11769. function searchForChildrenCandidates(componentsArray) {
  11770. for (const i of componentsArray) {
  11771. if (i.hasOwnProperty('el_') && i.getIsFocusable() && i.getIsAvailableToBeFocused(i.el())) {
  11772. focusableComponents.push(i);
  11773. }
  11774. if (i.hasOwnProperty('children_') && i.children_.length > 0) {
  11775. searchForChildrenCandidates(i.children_);
  11776. }
  11777. }
  11778. }
  11779. // Iterate inside all children components of the player.
  11780. player.children_.forEach(value => {
  11781. if (value.hasOwnProperty('el_')) {
  11782. // If component has required functions 'getIsFocusable' & 'getIsAvailableToBeFocused', is focusable & available to be focused.
  11783. if (value.getIsFocusable && value.getIsAvailableToBeFocused && value.getIsFocusable() && value.getIsAvailableToBeFocused(value.el())) {
  11784. focusableComponents.push(value);
  11785. return;
  11786. // If component has posible children components as candidates.
  11787. } else if (value.hasOwnProperty('children_') && value.children_.length > 0) {
  11788. searchForChildrenCandidates(value.children_);
  11789. // If component has posible item components as candidates.
  11790. } else if (value.hasOwnProperty('items') && value.items.length > 0) {
  11791. searchForChildrenCandidates(value.items);
  11792. // If there is a suitable child element within the component's DOM element.
  11793. } else if (this.findSuitableDOMChild(value)) {
  11794. focusableComponents.push(value);
  11795. }
  11796. }
  11797. // TODO - Refactor the following logic after refactor of videojs-errors elements to be components is done.
  11798. if (value.name_ === 'ErrorDisplay' && value.opened_) {
  11799. const buttonContainer = value.el_.querySelector('.vjs-errors-ok-button-container');
  11800. if (buttonContainer) {
  11801. const modalButtons = buttonContainer.querySelectorAll('button');
  11802. modalButtons.forEach((element, index) => {
  11803. // Add elements as objects to be handled by the spatial navigation
  11804. focusableComponents.push({
  11805. name: () => {
  11806. return 'ModalButton' + (index + 1);
  11807. },
  11808. el: () => element,
  11809. getPositions: () => {
  11810. const rect = element.getBoundingClientRect();
  11811. // Creating objects that mirror DOMRectReadOnly for boundingClientRect and center
  11812. const boundingClientRect = {
  11813. x: rect.x,
  11814. y: rect.y,
  11815. width: rect.width,
  11816. height: rect.height,
  11817. top: rect.top,
  11818. right: rect.right,
  11819. bottom: rect.bottom,
  11820. left: rect.left
  11821. };
  11822. // Calculating the center position
  11823. const center = {
  11824. x: rect.left + rect.width / 2,
  11825. y: rect.top + rect.height / 2,
  11826. width: 0,
  11827. height: 0,
  11828. top: rect.top + rect.height / 2,
  11829. right: rect.left + rect.width / 2,
  11830. bottom: rect.top + rect.height / 2,
  11831. left: rect.left + rect.width / 2
  11832. };
  11833. return {
  11834. boundingClientRect,
  11835. center
  11836. };
  11837. },
  11838. // Asume that the following are always focusable
  11839. getIsAvailableToBeFocused: () => true,
  11840. getIsFocusable: el => true,
  11841. focus: () => element.focus()
  11842. });
  11843. });
  11844. }
  11845. }
  11846. });
  11847. this.focusableComponents = focusableComponents;
  11848. return this.focusableComponents;
  11849. }
  11850. /**
  11851. * Finds a suitable child element within the provided component's DOM element.
  11852. *
  11853. * @param {Object} component - The component containing the DOM element to search within.
  11854. * @return {HTMLElement|null} Returns the suitable child element if found, or null if not found.
  11855. */
  11856. findSuitableDOMChild(component) {
  11857. /**
  11858. * Recursively searches for a suitable child node that can be focused within a given component.
  11859. * It first checks if the provided node itself can be focused according to the component's
  11860. * `getIsFocusable` and `getIsAvailableToBeFocused` methods. If not, it recursively searches
  11861. * through the node's children to find a suitable child node that meets the focusability criteria.
  11862. *
  11863. * @param {HTMLElement} node - The DOM node to start the search from.
  11864. * @return {HTMLElement|null} The first child node that is focusable and available to be focused,
  11865. * or `null` if no suitable child is found.
  11866. */
  11867. function searchForSuitableChild(node) {
  11868. if (component.getIsFocusable(node) && component.getIsAvailableToBeFocused(node)) {
  11869. return node;
  11870. }
  11871. for (let i = 0; i < node.children.length; i++) {
  11872. const child = node.children[i];
  11873. const suitableChild = searchForSuitableChild(child);
  11874. if (suitableChild) {
  11875. return suitableChild;
  11876. }
  11877. }
  11878. return null;
  11879. }
  11880. if (component.el()) {
  11881. return searchForSuitableChild(component.el());
  11882. }
  11883. return null;
  11884. }
  11885. /**
  11886. * Gets the currently focused component from the list of focusable components.
  11887. * If a target element is provided, it uses that element to find the corresponding
  11888. * component. If no target is provided, it defaults to using the document's currently
  11889. * active element.
  11890. *
  11891. * @param {HTMLElement} [target] - The DOM element to check against the focusable components.
  11892. * If not provided, `document.activeElement` is used.
  11893. * @return {Component|null} - Returns the focused component if found among the focusable components,
  11894. * otherwise returns null if no matching component is found.
  11895. */
  11896. getCurrentComponent(target) {
  11897. this.updateFocusableComponents();
  11898. // eslint-disable-next-line
  11899. const curComp = target || document.activeElement;
  11900. if (this.focusableComponents.length) {
  11901. for (const i of this.focusableComponents) {
  11902. // If component Node is equal to the current active element.
  11903. if (i.el() === curComp) {
  11904. return i;
  11905. }
  11906. }
  11907. }
  11908. }
  11909. /**
  11910. * Adds a component to the array of focusable components.
  11911. *
  11912. * @param {Component} component
  11913. * The `Component` to be added.
  11914. */
  11915. add(component) {
  11916. const focusableComponents = [...this.focusableComponents];
  11917. if (component.hasOwnProperty('el_') && component.getIsFocusable() && component.getIsAvailableToBeFocused(component.el())) {
  11918. focusableComponents.push(component);
  11919. }
  11920. this.focusableComponents = focusableComponents;
  11921. // Trigger the notification manually
  11922. this.trigger({
  11923. type: 'focusableComponentsChanged',
  11924. focusableComponents: this.focusableComponents
  11925. });
  11926. }
  11927. /**
  11928. * Removes component from the array of focusable components.
  11929. *
  11930. * @param {Component} component - The component to be removed from the focusable components array.
  11931. */
  11932. remove(component) {
  11933. for (let i = 0; i < this.focusableComponents.length; i++) {
  11934. if (this.focusableComponents[i].name() === component.name()) {
  11935. this.focusableComponents.splice(i, 1);
  11936. // Trigger the notification manually
  11937. this.trigger({
  11938. type: 'focusableComponentsChanged',
  11939. focusableComponents: this.focusableComponents
  11940. });
  11941. return;
  11942. }
  11943. }
  11944. }
  11945. /**
  11946. * Clears array of focusable components.
  11947. */
  11948. clear() {
  11949. // Check if the array is already empty to avoid unnecessary event triggering
  11950. if (this.focusableComponents.length > 0) {
  11951. // Clear the array
  11952. this.focusableComponents = [];
  11953. // Trigger the notification manually
  11954. this.trigger({
  11955. type: 'focusableComponentsChanged',
  11956. focusableComponents: this.focusableComponents
  11957. });
  11958. }
  11959. }
  11960. /**
  11961. * Navigates to the next focusable component based on the specified direction.
  11962. *
  11963. * @param {string} direction 'up', 'down', 'left', 'right'
  11964. */
  11965. move(direction) {
  11966. const currentFocusedComponent = this.getCurrentComponent();
  11967. if (!currentFocusedComponent) {
  11968. return;
  11969. }
  11970. const currentPositions = currentFocusedComponent.getPositions();
  11971. const candidates = this.focusableComponents.filter(component => component !== currentFocusedComponent && this.isInDirection_(currentPositions.boundingClientRect, component.getPositions().boundingClientRect, direction));
  11972. const bestCandidate = this.findBestCandidate_(currentPositions.center, candidates, direction);
  11973. if (bestCandidate) {
  11974. this.focus(bestCandidate);
  11975. } else {
  11976. this.trigger({
  11977. type: 'endOfFocusableComponents',
  11978. direction,
  11979. focusedComponent: currentFocusedComponent
  11980. });
  11981. }
  11982. }
  11983. /**
  11984. * Finds the best candidate on the current center position,
  11985. * the list of candidates, and the specified navigation direction.
  11986. *
  11987. * @param {Object} currentCenter The center position of the current focused component element.
  11988. * @param {Array} candidates An array of candidate components to receive focus.
  11989. * @param {string} direction The direction of navigation ('up', 'down', 'left', 'right').
  11990. * @return {Object|null} The component that is the best candidate for receiving focus.
  11991. */
  11992. findBestCandidate_(currentCenter, candidates, direction) {
  11993. let minDistance = Infinity;
  11994. let bestCandidate = null;
  11995. for (const candidate of candidates) {
  11996. const candidateCenter = candidate.getPositions().center;
  11997. const distance = this.calculateDistance_(currentCenter, candidateCenter, direction);
  11998. if (distance < minDistance) {
  11999. minDistance = distance;
  12000. bestCandidate = candidate;
  12001. }
  12002. }
  12003. return bestCandidate;
  12004. }
  12005. /**
  12006. * Determines if a target rectangle is in the specified navigation direction
  12007. * relative to a source rectangle.
  12008. *
  12009. * @param {Object} srcRect The bounding rectangle of the source element.
  12010. * @param {Object} targetRect The bounding rectangle of the target element.
  12011. * @param {string} direction The navigation direction ('up', 'down', 'left', 'right').
  12012. * @return {boolean} True if the target is in the specified direction relative to the source.
  12013. */
  12014. isInDirection_(srcRect, targetRect, direction) {
  12015. switch (direction) {
  12016. case 'right':
  12017. return targetRect.left >= srcRect.right;
  12018. case 'left':
  12019. return targetRect.right <= srcRect.left;
  12020. case 'down':
  12021. return targetRect.top >= srcRect.bottom;
  12022. case 'up':
  12023. return targetRect.bottom <= srcRect.top;
  12024. default:
  12025. return false;
  12026. }
  12027. }
  12028. /**
  12029. * Focus the last focused component saved before blur on player.
  12030. */
  12031. refocusComponent() {
  12032. if (this.lastFocusedComponent_) {
  12033. // If user is not active, set it to active.
  12034. if (!this.player_.userActive()) {
  12035. this.player_.userActive(true);
  12036. }
  12037. this.updateFocusableComponents();
  12038. // Search inside array of 'focusableComponents' for a match of name of
  12039. // the last focused component.
  12040. for (let i = 0; i < this.focusableComponents.length; i++) {
  12041. if (this.focusableComponents[i].name() === this.lastFocusedComponent_.name()) {
  12042. this.focus(this.focusableComponents[i]);
  12043. return;
  12044. }
  12045. }
  12046. } else {
  12047. this.focus(this.updateFocusableComponents()[0]);
  12048. }
  12049. }
  12050. /**
  12051. * Focuses on a given component.
  12052. * If the component is available to be focused, it focuses on the component.
  12053. * If not, it attempts to find a suitable DOM child within the component and focuses on it.
  12054. *
  12055. * @param {Component} component - The component to be focused.
  12056. */
  12057. focus(component) {
  12058. if (typeof component !== 'object') {
  12059. return;
  12060. }
  12061. if (component.getIsAvailableToBeFocused(component.el())) {
  12062. component.focus();
  12063. } else if (this.findSuitableDOMChild(component)) {
  12064. this.findSuitableDOMChild(component).focus();
  12065. }
  12066. }
  12067. /**
  12068. * Calculates the distance between two points, adjusting the calculation based on
  12069. * the specified navigation direction.
  12070. *
  12071. * @param {Object} center1 The center point of the first element.
  12072. * @param {Object} center2 The center point of the second element.
  12073. * @param {string} direction The direction of navigation ('up', 'down', 'left', 'right').
  12074. * @return {number} The calculated distance between the two centers.
  12075. */
  12076. calculateDistance_(center1, center2, direction) {
  12077. const dx = Math.abs(center1.x - center2.x);
  12078. const dy = Math.abs(center1.y - center2.y);
  12079. let distance;
  12080. switch (direction) {
  12081. case 'right':
  12082. case 'left':
  12083. // Higher weight for vertical distance in horizontal navigation.
  12084. distance = dx + dy * 100;
  12085. break;
  12086. case 'up':
  12087. // Strongly prioritize vertical proximity for UP navigation.
  12088. // Adjust the weight to ensure that elements directly above are favored.
  12089. distance = dy * 2 + dx * 0.5;
  12090. break;
  12091. case 'down':
  12092. // More balanced weight for vertical and horizontal distances.
  12093. // Adjust the weights here to find the best balance.
  12094. distance = dy * 5 + dx;
  12095. break;
  12096. default:
  12097. distance = dx + dy;
  12098. }
  12099. return distance;
  12100. }
  12101. /**
  12102. * This gets called by 'handlePlayerBlur_' if 'spatialNavigation' is enabled.
  12103. * Searches for the first 'TextTrackSelect' inside of modal to focus.
  12104. *
  12105. * @private
  12106. */
  12107. searchForTrackSelect_() {
  12108. const spatialNavigation = this;
  12109. for (const component of spatialNavigation.updateFocusableComponents()) {
  12110. if (component.constructor.name === 'TextTrackSelect') {
  12111. spatialNavigation.focus(component);
  12112. break;
  12113. }
  12114. }
  12115. }
  12116. }
  12117. /**
  12118. * @file loader.js
  12119. */
  12120. /** @import Player from '../player' */
  12121. /**
  12122. * The `MediaLoader` is the `Component` that decides which playback technology to load
  12123. * when a player is initialized.
  12124. *
  12125. * @extends Component
  12126. */
  12127. class MediaLoader extends Component {
  12128. /**
  12129. * Create an instance of this class.
  12130. *
  12131. * @param {Player} player
  12132. * The `Player` that this class should attach to.
  12133. *
  12134. * @param {Object} [options]
  12135. * The key/value store of player options.
  12136. *
  12137. * @param {Function} [ready]
  12138. * The function that is run when this component is ready.
  12139. */
  12140. constructor(player, options, ready) {
  12141. // MediaLoader has no element
  12142. const options_ = merge({
  12143. createEl: false
  12144. }, options);
  12145. super(player, options_, ready);
  12146. // If there are no sources when the player is initialized,
  12147. // load the first supported playback technology.
  12148. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  12149. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  12150. const techName = toTitleCase(j[i]);
  12151. let tech = Tech.getTech(techName);
  12152. // Support old behavior of techs being registered as components.
  12153. // Remove once that deprecated behavior is removed.
  12154. if (!techName) {
  12155. tech = Component.getComponent(techName);
  12156. }
  12157. // Check if the browser supports this technology
  12158. if (tech && tech.isSupported()) {
  12159. player.loadTech_(techName);
  12160. break;
  12161. }
  12162. }
  12163. } else {
  12164. // Loop through playback technologies (e.g. HTML5) and check for support.
  12165. // Then load the best source.
  12166. // A few assumptions here:
  12167. // All playback technologies respect preload false.
  12168. player.src(options.playerOptions.sources);
  12169. }
  12170. }
  12171. }
  12172. Component.registerComponent('MediaLoader', MediaLoader);
  12173. /**
  12174. * @file clickable-component.js
  12175. */
  12176. /** @import Player from './player' */
  12177. /**
  12178. * Component which is clickable or keyboard actionable, but is not a
  12179. * native HTML button.
  12180. *
  12181. * @extends Component
  12182. */
  12183. class ClickableComponent extends Component {
  12184. /**
  12185. * Creates an instance of this class.
  12186. *
  12187. * @param {Player} player
  12188. * The `Player` that this class should be attached to.
  12189. *
  12190. * @param {Object} [options]
  12191. * The key/value store of component options.
  12192. *
  12193. * @param {function} [options.clickHandler]
  12194. * The function to call when the button is clicked / activated
  12195. *
  12196. * @param {string} [options.controlText]
  12197. * The text to set on the button
  12198. *
  12199. * @param {string} [options.className]
  12200. * A class or space separated list of classes to add the component
  12201. *
  12202. */
  12203. constructor(player, options) {
  12204. super(player, options);
  12205. if (this.options_.controlText) {
  12206. this.controlText(this.options_.controlText);
  12207. }
  12208. this.handleMouseOver_ = e => this.handleMouseOver(e);
  12209. this.handleMouseOut_ = e => this.handleMouseOut(e);
  12210. this.handleClick_ = e => this.handleClick(e);
  12211. this.handleKeyDown_ = e => this.handleKeyDown(e);
  12212. this.emitTapEvents();
  12213. this.enable();
  12214. }
  12215. /**
  12216. * Create the `ClickableComponent`s DOM element.
  12217. *
  12218. * @param {string} [tag=div]
  12219. * The element's node type.
  12220. *
  12221. * @param {Object} [props={}]
  12222. * An object of properties that should be set on the element.
  12223. *
  12224. * @param {Object} [attributes={}]
  12225. * An object of attributes that should be set on the element.
  12226. *
  12227. * @return {Element}
  12228. * The element that gets created.
  12229. */
  12230. createEl(tag = 'div', props = {}, attributes = {}) {
  12231. props = Object.assign({
  12232. className: this.buildCSSClass(),
  12233. tabIndex: 0
  12234. }, props);
  12235. if (tag === 'button') {
  12236. log.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  12237. }
  12238. // Add ARIA attributes for clickable element which is not a native HTML button
  12239. attributes = Object.assign({
  12240. role: 'button'
  12241. }, attributes);
  12242. this.tabIndex_ = props.tabIndex;
  12243. const el = createEl(tag, props, attributes);
  12244. if (!this.player_.options_.experimentalSvgIcons) {
  12245. el.appendChild(createEl('span', {
  12246. className: 'vjs-icon-placeholder'
  12247. }, {
  12248. 'aria-hidden': true
  12249. }));
  12250. }
  12251. this.createControlTextEl(el);
  12252. return el;
  12253. }
  12254. dispose() {
  12255. // remove controlTextEl_ on dispose
  12256. this.controlTextEl_ = null;
  12257. super.dispose();
  12258. }
  12259. /**
  12260. * Create a control text element on this `ClickableComponent`
  12261. *
  12262. * @param {Element} [el]
  12263. * Parent element for the control text.
  12264. *
  12265. * @return {Element}
  12266. * The control text element that gets created.
  12267. */
  12268. createControlTextEl(el) {
  12269. this.controlTextEl_ = createEl('span', {
  12270. className: 'vjs-control-text'
  12271. }, {
  12272. // let the screen reader user know that the text of the element may change
  12273. 'aria-live': 'polite'
  12274. });
  12275. if (el) {
  12276. el.appendChild(this.controlTextEl_);
  12277. }
  12278. this.controlText(this.controlText_, el);
  12279. return this.controlTextEl_;
  12280. }
  12281. /**
  12282. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  12283. *
  12284. * @param {string} [text]
  12285. * Control text for element.
  12286. *
  12287. * @param {Element} [el=this.el()]
  12288. * Element to set the title on.
  12289. *
  12290. * @return {string}
  12291. * - The control text when getting
  12292. */
  12293. controlText(text, el = this.el()) {
  12294. if (text === undefined) {
  12295. return this.controlText_ || 'Need Text';
  12296. }
  12297. const localizedText = this.localize(text);
  12298. /** @protected */
  12299. this.controlText_ = text;
  12300. textContent(this.controlTextEl_, localizedText);
  12301. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  12302. // Set title attribute if only an icon is shown
  12303. el.setAttribute('title', localizedText);
  12304. }
  12305. }
  12306. /**
  12307. * Builds the default DOM `className`.
  12308. *
  12309. * @return {string}
  12310. * The DOM `className` for this object.
  12311. */
  12312. buildCSSClass() {
  12313. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  12314. }
  12315. /**
  12316. * Enable this `ClickableComponent`
  12317. */
  12318. enable() {
  12319. if (!this.enabled_) {
  12320. this.enabled_ = true;
  12321. this.removeClass('vjs-disabled');
  12322. this.el_.setAttribute('aria-disabled', 'false');
  12323. if (typeof this.tabIndex_ !== 'undefined') {
  12324. this.el_.setAttribute('tabIndex', this.tabIndex_);
  12325. }
  12326. this.on(['tap', 'click'], this.handleClick_);
  12327. this.on('keydown', this.handleKeyDown_);
  12328. }
  12329. }
  12330. /**
  12331. * Disable this `ClickableComponent`
  12332. */
  12333. disable() {
  12334. this.enabled_ = false;
  12335. this.addClass('vjs-disabled');
  12336. this.el_.setAttribute('aria-disabled', 'true');
  12337. if (typeof this.tabIndex_ !== 'undefined') {
  12338. this.el_.removeAttribute('tabIndex');
  12339. }
  12340. this.off('mouseover', this.handleMouseOver_);
  12341. this.off('mouseout', this.handleMouseOut_);
  12342. this.off(['tap', 'click'], this.handleClick_);
  12343. this.off('keydown', this.handleKeyDown_);
  12344. }
  12345. /**
  12346. * Handles language change in ClickableComponent for the player in components
  12347. *
  12348. *
  12349. */
  12350. handleLanguagechange() {
  12351. this.controlText(this.controlText_);
  12352. }
  12353. /**
  12354. * Event handler that is called when a `ClickableComponent` receives a
  12355. * `click` or `tap` event.
  12356. *
  12357. * @param {Event} event
  12358. * The `tap` or `click` event that caused this function to be called.
  12359. *
  12360. * @listens tap
  12361. * @listens click
  12362. * @abstract
  12363. */
  12364. handleClick(event) {
  12365. if (this.options_.clickHandler) {
  12366. this.options_.clickHandler.call(this, arguments);
  12367. }
  12368. }
  12369. /**
  12370. * Event handler that is called when a `ClickableComponent` receives a
  12371. * `keydown` event.
  12372. *
  12373. * By default, if the key is Space or Enter, it will trigger a `click` event.
  12374. *
  12375. * @param {KeyboardEvent} event
  12376. * The `keydown` event that caused this function to be called.
  12377. *
  12378. * @listens keydown
  12379. */
  12380. handleKeyDown(event) {
  12381. // Support Space or Enter key operation to fire a click event. Also,
  12382. // prevent the event from propagating through the DOM and triggering
  12383. // Player hotkeys.
  12384. if (event.key === ' ' || event.key === 'Enter') {
  12385. event.preventDefault();
  12386. event.stopPropagation();
  12387. this.trigger('click');
  12388. } else {
  12389. // Pass keypress handling up for unsupported keys
  12390. super.handleKeyDown(event);
  12391. }
  12392. }
  12393. }
  12394. Component.registerComponent('ClickableComponent', ClickableComponent);
  12395. /**
  12396. * @file poster-image.js
  12397. */
  12398. /** @import Player from './player' */
  12399. /**
  12400. * A `ClickableComponent` that handles showing the poster image for the player.
  12401. *
  12402. * @extends ClickableComponent
  12403. */
  12404. class PosterImage extends ClickableComponent {
  12405. /**
  12406. * Create an instance of this class.
  12407. *
  12408. * @param {Player} player
  12409. * The `Player` that this class should attach to.
  12410. *
  12411. * @param {Object} [options]
  12412. * The key/value store of player options.
  12413. */
  12414. constructor(player, options) {
  12415. super(player, options);
  12416. this.update();
  12417. this.update_ = e => this.update(e);
  12418. player.on('posterchange', this.update_);
  12419. }
  12420. /**
  12421. * Clean up and dispose of the `PosterImage`.
  12422. */
  12423. dispose() {
  12424. this.player().off('posterchange', this.update_);
  12425. super.dispose();
  12426. }
  12427. /**
  12428. * Create the `PosterImage`s DOM element.
  12429. *
  12430. * @return {Element}
  12431. * The element that gets created.
  12432. */
  12433. createEl() {
  12434. // The el is an empty div to keep position in the DOM
  12435. // A picture and img el will be inserted when a source is set
  12436. return createEl('div', {
  12437. className: 'vjs-poster'
  12438. });
  12439. }
  12440. /**
  12441. * Get or set the `PosterImage`'s crossOrigin option.
  12442. *
  12443. * @param {string|null} [value]
  12444. * The value to set the crossOrigin to. If an argument is
  12445. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  12446. *
  12447. * @return {string|null}
  12448. * - The current crossOrigin value of the `Player` when getting.
  12449. * - undefined when setting
  12450. */
  12451. crossOrigin(value) {
  12452. // `null` can be set to unset a value
  12453. if (typeof value === 'undefined') {
  12454. if (this.$('img')) {
  12455. // If the poster's element exists, give its value
  12456. return this.$('img').crossOrigin;
  12457. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  12458. // If not but the tech is ready, query the tech
  12459. return this.player_.crossOrigin();
  12460. }
  12461. // Otherwise check options as the poster is usually set before the state of crossorigin
  12462. // can be retrieved by the getter
  12463. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  12464. }
  12465. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  12466. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  12467. return;
  12468. }
  12469. if (this.$('img')) {
  12470. this.$('img').crossOrigin = value;
  12471. }
  12472. return;
  12473. }
  12474. /**
  12475. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  12476. *
  12477. * @listens Player#posterchange
  12478. *
  12479. * @param {Event} [event]
  12480. * The `Player#posterchange` event that triggered this function.
  12481. */
  12482. update(event) {
  12483. const url = this.player().poster();
  12484. this.setSrc(url);
  12485. // If there's no poster source we should display:none on this component
  12486. // so it's not still clickable or right-clickable
  12487. if (url) {
  12488. this.show();
  12489. } else {
  12490. this.hide();
  12491. }
  12492. }
  12493. /**
  12494. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  12495. * the inner picture and img elementss when needed.
  12496. *
  12497. * @param {string} [url]
  12498. * The URL to the source for the `PosterImage`. If not specified or falsy,
  12499. * any source and ant inner picture/img are removed.
  12500. */
  12501. setSrc(url) {
  12502. if (!url) {
  12503. this.el_.textContent = '';
  12504. return;
  12505. }
  12506. if (!this.$('img')) {
  12507. this.el_.appendChild(createEl('picture', {
  12508. className: 'vjs-poster',
  12509. // Don't want poster to be tabbable.
  12510. tabIndex: -1
  12511. }, {}, createEl('img', {
  12512. loading: 'lazy',
  12513. crossOrigin: this.crossOrigin()
  12514. }, {
  12515. alt: ''
  12516. })));
  12517. }
  12518. this.$('img').src = url;
  12519. }
  12520. /**
  12521. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  12522. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  12523. *
  12524. * @listens tap
  12525. * @listens click
  12526. * @listens keydown
  12527. *
  12528. * @param {Event} event
  12529. + The `click`, `tap` or `keydown` event that caused this function to be called.
  12530. */
  12531. handleClick(event) {
  12532. // We don't want a click to trigger playback when controls are disabled
  12533. if (!this.player_.controls()) {
  12534. return;
  12535. }
  12536. if (this.player_.tech(true)) {
  12537. this.player_.tech(true).focus();
  12538. }
  12539. if (this.player_.paused()) {
  12540. silencePromise(this.player_.play());
  12541. } else {
  12542. this.player_.pause();
  12543. }
  12544. }
  12545. }
  12546. /**
  12547. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  12548. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  12549. * behavior.
  12550. *
  12551. * @param {string|null} [value]
  12552. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  12553. * given, must be one of `anonymous` or `use-credentials`.
  12554. *
  12555. * @return {string|null|undefined}
  12556. * - The current crossorigin value of the `Player` when getting.
  12557. * - undefined when setting
  12558. */
  12559. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  12560. Component.registerComponent('PosterImage', PosterImage);
  12561. /**
  12562. * @file text-track-display.js
  12563. */
  12564. /** @import Player from '../player' */
  12565. const darkGray = '#222';
  12566. const lightGray = '#ccc';
  12567. const fontMap = {
  12568. monospace: 'monospace',
  12569. sansSerif: 'sans-serif',
  12570. serif: 'serif',
  12571. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  12572. monospaceSerif: '"Courier New", monospace',
  12573. proportionalSansSerif: 'sans-serif',
  12574. proportionalSerif: 'serif',
  12575. casual: '"Comic Sans MS", Impact, fantasy',
  12576. script: '"Monotype Corsiva", cursive',
  12577. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  12578. };
  12579. /**
  12580. * Construct an rgba color from a given hex color code.
  12581. *
  12582. * @param {number} color
  12583. * Hex number for color, like #f0e or #f604e2.
  12584. *
  12585. * @param {number} opacity
  12586. * Value for opacity, 0.0 - 1.0.
  12587. *
  12588. * @return {string}
  12589. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  12590. */
  12591. function constructColor(color, opacity) {
  12592. let hex;
  12593. if (color.length === 4) {
  12594. // color looks like "#f0e"
  12595. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  12596. } else if (color.length === 7) {
  12597. // color looks like "#f604e2"
  12598. hex = color.slice(1);
  12599. } else {
  12600. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  12601. }
  12602. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  12603. }
  12604. /**
  12605. * Try to update the style of a DOM element. Some style changes will throw an error,
  12606. * particularly in IE8. Those should be noops.
  12607. *
  12608. * @param {Element} el
  12609. * The DOM element to be styled.
  12610. *
  12611. * @param {string} style
  12612. * The CSS property on the element that should be styled.
  12613. *
  12614. * @param {string} rule
  12615. * The style rule that should be applied to the property.
  12616. *
  12617. * @private
  12618. */
  12619. function tryUpdateStyle(el, style, rule) {
  12620. try {
  12621. el.style[style] = rule;
  12622. } catch (e) {
  12623. // Satisfies linter.
  12624. return;
  12625. }
  12626. }
  12627. /**
  12628. * Converts the CSS top/right/bottom/left property numeric value to string in pixels.
  12629. *
  12630. * @param {number} position
  12631. * The CSS top/right/bottom/left property value.
  12632. *
  12633. * @return {string}
  12634. * The CSS property value that was created, like '10px'.
  12635. *
  12636. * @private
  12637. */
  12638. function getCSSPositionValue(position) {
  12639. return position ? `${position}px` : '';
  12640. }
  12641. /**
  12642. * The component for displaying text track cues.
  12643. *
  12644. * @extends Component
  12645. */
  12646. class TextTrackDisplay extends Component {
  12647. /**
  12648. * Creates an instance of this class.
  12649. *
  12650. * @param {Player} player
  12651. * The `Player` that this class should be attached to.
  12652. *
  12653. * @param {Object} [options]
  12654. * The key/value store of player options.
  12655. *
  12656. * @param {Function} [ready]
  12657. * The function to call when `TextTrackDisplay` is ready.
  12658. */
  12659. constructor(player, options, ready) {
  12660. super(player, options, ready);
  12661. const updateDisplayTextHandler = e => this.updateDisplay(e);
  12662. const updateDisplayHandler = e => {
  12663. this.updateDisplayOverlay();
  12664. this.updateDisplay(e);
  12665. };
  12666. player.on('loadstart', e => this.toggleDisplay(e));
  12667. player.on('texttrackchange', updateDisplayTextHandler);
  12668. player.on('loadedmetadata', e => {
  12669. this.updateDisplayOverlay();
  12670. this.preselectTrack(e);
  12671. });
  12672. // This used to be called during player init, but was causing an error
  12673. // if a track should show by default and the display hadn't loaded yet.
  12674. // Should probably be moved to an external track loader when we support
  12675. // tracks that don't need a display.
  12676. player.ready(bind_(this, function () {
  12677. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  12678. this.hide();
  12679. return;
  12680. }
  12681. player.on('fullscreenchange', updateDisplayHandler);
  12682. player.on('playerresize', updateDisplayHandler);
  12683. const screenOrientation = window.screen.orientation || window;
  12684. const changeOrientationEvent = window.screen.orientation ? 'change' : 'orientationchange';
  12685. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  12686. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  12687. const tracks = this.options_.playerOptions.tracks || [];
  12688. for (let i = 0; i < tracks.length; i++) {
  12689. this.player_.addRemoteTextTrack(tracks[i], true);
  12690. }
  12691. this.preselectTrack();
  12692. }));
  12693. }
  12694. /**
  12695. * Preselect a track following this precedence:
  12696. * - matches the previously selected {@link TextTrack}'s language and kind
  12697. * - matches the previously selected {@link TextTrack}'s language only
  12698. * - is the first default captions track
  12699. * - is the first default descriptions track
  12700. *
  12701. * @listens Player#loadstart
  12702. */
  12703. preselectTrack() {
  12704. const modes = {
  12705. captions: 1,
  12706. subtitles: 1
  12707. };
  12708. const trackList = this.player_.textTracks();
  12709. const userPref = this.player_.cache_.selectedLanguage;
  12710. let firstDesc;
  12711. let firstCaptions;
  12712. let preferredTrack;
  12713. for (let i = 0; i < trackList.length; i++) {
  12714. const track = trackList[i];
  12715. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  12716. // Always choose the track that matches both language and kind
  12717. if (track.kind === userPref.kind) {
  12718. preferredTrack = track;
  12719. // or choose the first track that matches language
  12720. } else if (!preferredTrack) {
  12721. preferredTrack = track;
  12722. }
  12723. // clear everything if offTextTrackMenuItem was clicked
  12724. } else if (userPref && !userPref.enabled) {
  12725. preferredTrack = null;
  12726. firstDesc = null;
  12727. firstCaptions = null;
  12728. } else if (track.default) {
  12729. if (track.kind === 'descriptions' && !firstDesc) {
  12730. firstDesc = track;
  12731. } else if (track.kind in modes && !firstCaptions) {
  12732. firstCaptions = track;
  12733. }
  12734. }
  12735. }
  12736. // The preferredTrack matches the user preference and takes
  12737. // precedence over all the other tracks.
  12738. // So, display the preferredTrack before the first default track
  12739. // and the subtitles/captions track before the descriptions track
  12740. if (preferredTrack) {
  12741. preferredTrack.mode = 'showing';
  12742. } else if (firstCaptions) {
  12743. firstCaptions.mode = 'showing';
  12744. } else if (firstDesc) {
  12745. firstDesc.mode = 'showing';
  12746. }
  12747. }
  12748. /**
  12749. * Turn display of {@link TextTrack}'s from the current state into the other state.
  12750. * There are only two states:
  12751. * - 'shown'
  12752. * - 'hidden'
  12753. *
  12754. * @listens Player#loadstart
  12755. */
  12756. toggleDisplay() {
  12757. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  12758. this.hide();
  12759. } else {
  12760. this.show();
  12761. }
  12762. }
  12763. /**
  12764. * Create the {@link Component}'s DOM element.
  12765. *
  12766. * @return {Element}
  12767. * The element that was created.
  12768. */
  12769. createEl() {
  12770. return super.createEl('div', {
  12771. className: 'vjs-text-track-display'
  12772. }, {
  12773. 'translate': 'yes',
  12774. 'aria-live': 'off',
  12775. 'aria-atomic': 'true'
  12776. });
  12777. }
  12778. /**
  12779. * Clear all displayed {@link TextTrack}s.
  12780. */
  12781. clearDisplay() {
  12782. if (typeof window.WebVTT === 'function') {
  12783. window.WebVTT.processCues(window, [], this.el_);
  12784. }
  12785. }
  12786. /**
  12787. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  12788. * a {@link Player#fullscreenchange} is fired.
  12789. *
  12790. * @listens Player#texttrackchange
  12791. * @listens Player#fullscreenchange
  12792. */
  12793. updateDisplay() {
  12794. const tracks = this.player_.textTracks();
  12795. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  12796. this.clearDisplay();
  12797. if (allowMultipleShowingTracks) {
  12798. const showingTracks = [];
  12799. for (let i = 0; i < tracks.length; ++i) {
  12800. const track = tracks[i];
  12801. if (track.mode !== 'showing') {
  12802. continue;
  12803. }
  12804. showingTracks.push(track);
  12805. }
  12806. this.updateForTrack(showingTracks);
  12807. return;
  12808. }
  12809. // Track display prioritization model: if multiple tracks are 'showing',
  12810. // display the first 'subtitles' or 'captions' track which is 'showing',
  12811. // otherwise display the first 'descriptions' track which is 'showing'
  12812. let descriptionsTrack = null;
  12813. let captionsSubtitlesTrack = null;
  12814. let i = tracks.length;
  12815. while (i--) {
  12816. const track = tracks[i];
  12817. if (track.mode === 'showing') {
  12818. if (track.kind === 'descriptions') {
  12819. descriptionsTrack = track;
  12820. } else {
  12821. captionsSubtitlesTrack = track;
  12822. }
  12823. }
  12824. }
  12825. if (captionsSubtitlesTrack) {
  12826. if (this.getAttribute('aria-live') !== 'off') {
  12827. this.setAttribute('aria-live', 'off');
  12828. }
  12829. this.updateForTrack(captionsSubtitlesTrack);
  12830. } else if (descriptionsTrack) {
  12831. if (this.getAttribute('aria-live') !== 'assertive') {
  12832. this.setAttribute('aria-live', 'assertive');
  12833. }
  12834. this.updateForTrack(descriptionsTrack);
  12835. }
  12836. if (!window.CSS.supports('inset', '10px')) {
  12837. const textTrackDisplay = this.el_;
  12838. const vjsTextTrackCues = textTrackDisplay.querySelectorAll('.vjs-text-track-cue');
  12839. const controlBarHeight = this.player_.controlBar.el_.getBoundingClientRect().height;
  12840. const playerHeight = this.player_.el_.getBoundingClientRect().height;
  12841. // Clear inline style before getting actual height of textTrackDisplay
  12842. textTrackDisplay.style = '';
  12843. // textrack style updates, this styles are required to be inline
  12844. tryUpdateStyle(textTrackDisplay, 'position', 'relative');
  12845. tryUpdateStyle(textTrackDisplay, 'height', playerHeight - controlBarHeight + 'px');
  12846. tryUpdateStyle(textTrackDisplay, 'top', 'unset');
  12847. if (IS_SMART_TV) {
  12848. tryUpdateStyle(textTrackDisplay, 'bottom', playerHeight + 'px');
  12849. } else {
  12850. tryUpdateStyle(textTrackDisplay, 'bottom', '0px');
  12851. }
  12852. // vjsTextTrackCue style updates
  12853. if (vjsTextTrackCues.length > 0) {
  12854. vjsTextTrackCues.forEach(vjsTextTrackCue => {
  12855. // verify if inset styles are inline
  12856. if (vjsTextTrackCue.style.inset) {
  12857. const insetStyles = vjsTextTrackCue.style.inset.split(' ');
  12858. // expected value is always 3
  12859. if (insetStyles.length === 3) {
  12860. Object.assign(vjsTextTrackCue.style, {
  12861. top: insetStyles[0],
  12862. right: insetStyles[1],
  12863. bottom: insetStyles[2],
  12864. left: 'unset'
  12865. });
  12866. }
  12867. }
  12868. });
  12869. }
  12870. }
  12871. }
  12872. /**
  12873. * Updates the displayed TextTrack to be sure it overlays the video when a either
  12874. * a {@link Player#texttrackchange} or a {@link Player#fullscreenchange} is fired.
  12875. */
  12876. updateDisplayOverlay() {
  12877. // inset-inline and inset-block are not supprted on old chrome, but these are
  12878. // only likely to be used on TV devices
  12879. if (!this.player_.videoHeight() || !window.CSS.supports('inset-inline: 10px')) {
  12880. return;
  12881. }
  12882. const playerWidth = this.player_.currentWidth();
  12883. const playerHeight = this.player_.currentHeight();
  12884. const playerAspectRatio = playerWidth / playerHeight;
  12885. const videoAspectRatio = this.player_.videoWidth() / this.player_.videoHeight();
  12886. let insetInlineMatch = 0;
  12887. let insetBlockMatch = 0;
  12888. if (Math.abs(playerAspectRatio - videoAspectRatio) > 0.1) {
  12889. if (playerAspectRatio > videoAspectRatio) {
  12890. insetInlineMatch = Math.round((playerWidth - playerHeight * videoAspectRatio) / 2);
  12891. } else {
  12892. insetBlockMatch = Math.round((playerHeight - playerWidth / videoAspectRatio) / 2);
  12893. }
  12894. }
  12895. tryUpdateStyle(this.el_, 'insetInline', getCSSPositionValue(insetInlineMatch));
  12896. tryUpdateStyle(this.el_, 'insetBlock', getCSSPositionValue(insetBlockMatch));
  12897. }
  12898. /**
  12899. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  12900. *
  12901. * @param {TextTrack} track
  12902. * Text track object containing active cues to style.
  12903. */
  12904. updateDisplayState(track) {
  12905. const overrides = this.player_.textTrackSettings.getValues();
  12906. const cues = track.activeCues;
  12907. let i = cues.length;
  12908. while (i--) {
  12909. const cue = cues[i];
  12910. if (!cue) {
  12911. continue;
  12912. }
  12913. const cueDiv = cue.displayState;
  12914. if (overrides.color) {
  12915. cueDiv.firstChild.style.color = overrides.color;
  12916. }
  12917. if (overrides.textOpacity) {
  12918. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  12919. }
  12920. if (overrides.backgroundColor) {
  12921. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  12922. }
  12923. if (overrides.backgroundOpacity) {
  12924. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  12925. }
  12926. if (overrides.windowColor) {
  12927. if (overrides.windowOpacity) {
  12928. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  12929. } else {
  12930. cueDiv.style.backgroundColor = overrides.windowColor;
  12931. }
  12932. }
  12933. if (overrides.edgeStyle) {
  12934. if (overrides.edgeStyle === 'dropshadow') {
  12935. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  12936. } else if (overrides.edgeStyle === 'raised') {
  12937. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  12938. } else if (overrides.edgeStyle === 'depressed') {
  12939. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  12940. } else if (overrides.edgeStyle === 'uniform') {
  12941. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  12942. }
  12943. }
  12944. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  12945. const fontSize = window.parseFloat(cueDiv.style.fontSize);
  12946. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  12947. cueDiv.style.height = 'auto';
  12948. cueDiv.style.top = 'auto';
  12949. }
  12950. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  12951. if (overrides.fontFamily === 'small-caps') {
  12952. cueDiv.firstChild.style.fontVariant = 'small-caps';
  12953. } else {
  12954. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  12955. }
  12956. }
  12957. }
  12958. }
  12959. /**
  12960. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  12961. *
  12962. * @param {TextTrack|TextTrack[]} tracks
  12963. * Text track object or text track array to be added to the list.
  12964. */
  12965. updateForTrack(tracks) {
  12966. if (!Array.isArray(tracks)) {
  12967. tracks = [tracks];
  12968. }
  12969. if (typeof window.WebVTT !== 'function' || tracks.every(track => {
  12970. return !track.activeCues;
  12971. })) {
  12972. return;
  12973. }
  12974. const cues = [];
  12975. // push all active track cues
  12976. for (let i = 0; i < tracks.length; ++i) {
  12977. const track = tracks[i];
  12978. for (let j = 0; j < track.activeCues.length; ++j) {
  12979. cues.push(track.activeCues[j]);
  12980. }
  12981. }
  12982. // removes all cues before it processes new ones
  12983. window.WebVTT.processCues(window, cues, this.el_);
  12984. // add unique class to each language text track & add settings styling if necessary
  12985. for (let i = 0; i < tracks.length; ++i) {
  12986. const track = tracks[i];
  12987. for (let j = 0; j < track.activeCues.length; ++j) {
  12988. const cueEl = track.activeCues[j].displayState;
  12989. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  12990. if (track.language) {
  12991. setAttribute(cueEl, 'lang', track.language);
  12992. }
  12993. }
  12994. if (this.player_.textTrackSettings) {
  12995. this.updateDisplayState(track);
  12996. }
  12997. }
  12998. }
  12999. }
  13000. Component.registerComponent('TextTrackDisplay', TextTrackDisplay);
  13001. /**
  13002. * @file loading-spinner.js
  13003. */
  13004. /**
  13005. * A loading spinner for use during waiting/loading events.
  13006. *
  13007. * @extends Component
  13008. */
  13009. class LoadingSpinner extends Component {
  13010. /**
  13011. * Create the `LoadingSpinner`s DOM element.
  13012. *
  13013. * @return {Element}
  13014. * The dom element that gets created.
  13015. */
  13016. createEl() {
  13017. const isAudio = this.player_.isAudio();
  13018. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  13019. const controlText = createEl('span', {
  13020. className: 'vjs-control-text',
  13021. textContent: this.localize('{1} is loading.', [playerType])
  13022. });
  13023. const el = super.createEl('div', {
  13024. className: 'vjs-loading-spinner',
  13025. dir: 'ltr'
  13026. });
  13027. el.appendChild(controlText);
  13028. return el;
  13029. }
  13030. /**
  13031. * Update control text on languagechange
  13032. */
  13033. handleLanguagechange() {
  13034. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  13035. }
  13036. }
  13037. Component.registerComponent('LoadingSpinner', LoadingSpinner);
  13038. /**
  13039. * @file button.js
  13040. */
  13041. /**
  13042. * Base class for all buttons.
  13043. *
  13044. * @extends ClickableComponent
  13045. */
  13046. class Button extends ClickableComponent {
  13047. /**
  13048. * Create the `Button`s DOM element.
  13049. *
  13050. * @param {string} [tag="button"]
  13051. * The element's node type. This argument is IGNORED: no matter what
  13052. * is passed, it will always create a `button` element.
  13053. *
  13054. * @param {Object} [props={}]
  13055. * An object of properties that should be set on the element.
  13056. *
  13057. * @param {Object} [attributes={}]
  13058. * An object of attributes that should be set on the element.
  13059. *
  13060. * @return {Element}
  13061. * The element that gets created.
  13062. */
  13063. createEl(tag, props = {}, attributes = {}) {
  13064. tag = 'button';
  13065. props = Object.assign({
  13066. className: this.buildCSSClass()
  13067. }, props);
  13068. // Add attributes for button element
  13069. attributes = Object.assign({
  13070. // Necessary since the default button type is "submit"
  13071. type: 'button'
  13072. }, attributes);
  13073. const el = createEl(tag, props, attributes);
  13074. if (!this.player_.options_.experimentalSvgIcons) {
  13075. el.appendChild(createEl('span', {
  13076. className: 'vjs-icon-placeholder'
  13077. }, {
  13078. 'aria-hidden': true
  13079. }));
  13080. }
  13081. this.createControlTextEl(el);
  13082. return el;
  13083. }
  13084. /**
  13085. * Add a child `Component` inside of this `Button`.
  13086. *
  13087. * @param {string|Component} child
  13088. * The name or instance of a child to add.
  13089. *
  13090. * @param {Object} [options={}]
  13091. * The key/value store of options that will get passed to children of
  13092. * the child.
  13093. *
  13094. * @return {Component}
  13095. * The `Component` that gets added as a child. When using a string the
  13096. * `Component` will get created by this process.
  13097. *
  13098. * @deprecated since version 5
  13099. */
  13100. addChild(child, options = {}) {
  13101. const className = this.constructor.name;
  13102. log.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  13103. // Avoid the error message generated by ClickableComponent's addChild method
  13104. return Component.prototype.addChild.call(this, child, options);
  13105. }
  13106. /**
  13107. * Enable the `Button` element so that it can be activated or clicked. Use this with
  13108. * {@link Button#disable}.
  13109. */
  13110. enable() {
  13111. super.enable();
  13112. this.el_.removeAttribute('disabled');
  13113. }
  13114. /**
  13115. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  13116. * {@link Button#enable}.
  13117. */
  13118. disable() {
  13119. super.disable();
  13120. this.el_.setAttribute('disabled', 'disabled');
  13121. }
  13122. /**
  13123. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  13124. * press.
  13125. *
  13126. * @param {KeyboardEvent} event
  13127. * The event that caused this function to get called.
  13128. *
  13129. * @listens keydown
  13130. */
  13131. handleKeyDown(event) {
  13132. // Ignore Space or Enter key operation, which is handled by the browser for
  13133. // a button - though not for its super class, ClickableComponent. Also,
  13134. // prevent the event from propagating through the DOM and triggering Player
  13135. // hotkeys. We do not preventDefault here because we _want_ the browser to
  13136. // handle it.
  13137. if (event.key === ' ' || event.key === 'Enter') {
  13138. event.stopPropagation();
  13139. return;
  13140. }
  13141. // Pass keypress handling up for unsupported keys
  13142. super.handleKeyDown(event);
  13143. }
  13144. }
  13145. Component.registerComponent('Button', Button);
  13146. /**
  13147. * @file big-play-button.js
  13148. */
  13149. /**
  13150. * The initial play button that shows before the video has played. The hiding of the
  13151. * `BigPlayButton` get done via CSS and `Player` states.
  13152. *
  13153. * @extends Button
  13154. */
  13155. class BigPlayButton extends Button {
  13156. constructor(player, options) {
  13157. super(player, options);
  13158. this.mouseused_ = false;
  13159. this.setIcon('play');
  13160. this.on('mousedown', e => this.handleMouseDown(e));
  13161. }
  13162. /**
  13163. * Builds the default DOM `className`.
  13164. *
  13165. * @return {string}
  13166. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  13167. */
  13168. buildCSSClass() {
  13169. return 'vjs-big-play-button';
  13170. }
  13171. /**
  13172. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  13173. * for more detailed information on what a click can be.
  13174. *
  13175. * @param {KeyboardEvent|MouseEvent|TouchEvent} event
  13176. * The `keydown`, `tap`, or `click` event that caused this function to be
  13177. * called.
  13178. *
  13179. * @listens tap
  13180. * @listens click
  13181. */
  13182. handleClick(event) {
  13183. const playPromise = this.player_.play();
  13184. // exit early if clicked via the mouse
  13185. if (this.mouseused_ && 'clientX' in event && 'clientY' in event) {
  13186. silencePromise(playPromise);
  13187. if (this.player_.tech(true)) {
  13188. this.player_.tech(true).focus();
  13189. }
  13190. return;
  13191. }
  13192. const cb = this.player_.getChild('controlBar');
  13193. const playToggle = cb && cb.getChild('playToggle');
  13194. if (!playToggle) {
  13195. this.player_.tech(true).focus();
  13196. return;
  13197. }
  13198. const playFocus = () => playToggle.focus();
  13199. if (isPromise(playPromise)) {
  13200. playPromise.then(playFocus, () => {});
  13201. } else {
  13202. this.setTimeout(playFocus, 1);
  13203. }
  13204. }
  13205. /**
  13206. * Event handler that is called when a `BigPlayButton` receives a
  13207. * `keydown` event.
  13208. *
  13209. * @param {KeyboardEvent} event
  13210. * The `keydown` event that caused this function to be called.
  13211. *
  13212. * @listens keydown
  13213. */
  13214. handleKeyDown(event) {
  13215. this.mouseused_ = false;
  13216. super.handleKeyDown(event);
  13217. }
  13218. /**
  13219. * Handle `mousedown` events on the `BigPlayButton`.
  13220. *
  13221. * @param {MouseEvent} event
  13222. * `mousedown` or `touchstart` event that triggered this function
  13223. *
  13224. * @listens mousedown
  13225. */
  13226. handleMouseDown(event) {
  13227. this.mouseused_ = true;
  13228. }
  13229. }
  13230. /**
  13231. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  13232. *
  13233. * @type {string}
  13234. * @protected
  13235. */
  13236. BigPlayButton.prototype.controlText_ = 'Play Video';
  13237. Component.registerComponent('BigPlayButton', BigPlayButton);
  13238. /**
  13239. * @file close-button.js
  13240. */
  13241. /** @import Player from './player' */
  13242. /**
  13243. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  13244. * it gets clicked.
  13245. *
  13246. * @extends Button
  13247. */
  13248. class CloseButton extends Button {
  13249. /**
  13250. * Creates an instance of the this class.
  13251. *
  13252. * @param {Player} player
  13253. * The `Player` that this class should be attached to.
  13254. *
  13255. * @param {Object} [options]
  13256. * The key/value store of player options.
  13257. */
  13258. constructor(player, options) {
  13259. super(player, options);
  13260. this.setIcon('cancel');
  13261. this.controlText(options && options.controlText || this.localize('Close'));
  13262. }
  13263. /**
  13264. * Builds the default DOM `className`.
  13265. *
  13266. * @return {string}
  13267. * The DOM `className` for this object.
  13268. */
  13269. buildCSSClass() {
  13270. return `vjs-close-button ${super.buildCSSClass()}`;
  13271. }
  13272. /**
  13273. * This gets called when a `CloseButton` gets clicked. See
  13274. * {@link ClickableComponent#handleClick} for more information on when
  13275. * this will be triggered
  13276. *
  13277. * @param {Event} event
  13278. * The `keydown`, `tap`, or `click` event that caused this function to be
  13279. * called.
  13280. *
  13281. * @listens tap
  13282. * @listens click
  13283. * @fires CloseButton#close
  13284. */
  13285. handleClick(event) {
  13286. /**
  13287. * Triggered when the a `CloseButton` is clicked.
  13288. *
  13289. * @event CloseButton#close
  13290. * @type {Event}
  13291. *
  13292. * @property {boolean} [bubbles=false]
  13293. * set to false so that the close event does not
  13294. * bubble up to parents if there is no listener
  13295. */
  13296. this.trigger({
  13297. type: 'close',
  13298. bubbles: false
  13299. });
  13300. }
  13301. /**
  13302. * Event handler that is called when a `CloseButton` receives a
  13303. * `keydown` event.
  13304. *
  13305. * By default, if the key is Esc, it will trigger a `click` event.
  13306. *
  13307. * @param {KeyboardEvent} event
  13308. * The `keydown` event that caused this function to be called.
  13309. *
  13310. * @listens keydown
  13311. */
  13312. handleKeyDown(event) {
  13313. // Esc button will trigger `click` event
  13314. if (event.key === 'Escape') {
  13315. event.preventDefault();
  13316. event.stopPropagation();
  13317. this.trigger('click');
  13318. } else {
  13319. // Pass keypress handling up for unsupported keys
  13320. super.handleKeyDown(event);
  13321. }
  13322. }
  13323. }
  13324. Component.registerComponent('CloseButton', CloseButton);
  13325. /**
  13326. * @file play-toggle.js
  13327. */
  13328. /** @import Player from './player' */
  13329. /**
  13330. * Button to toggle between play and pause.
  13331. *
  13332. * @extends Button
  13333. */
  13334. class PlayToggle extends Button {
  13335. /**
  13336. * Creates an instance of this class.
  13337. *
  13338. * @param {Player} player
  13339. * The `Player` that this class should be attached to.
  13340. *
  13341. * @param {Object} [options={}]
  13342. * The key/value store of player options.
  13343. */
  13344. constructor(player, options = {}) {
  13345. super(player, options);
  13346. // show or hide replay icon
  13347. options.replay = options.replay === undefined || options.replay;
  13348. this.setIcon('play');
  13349. this.on(player, 'play', e => this.handlePlay(e));
  13350. this.on(player, 'pause', e => this.handlePause(e));
  13351. if (options.replay) {
  13352. this.on(player, 'ended', e => this.handleEnded(e));
  13353. }
  13354. }
  13355. /**
  13356. * Builds the default DOM `className`.
  13357. *
  13358. * @return {string}
  13359. * The DOM `className` for this object.
  13360. */
  13361. buildCSSClass() {
  13362. return `vjs-play-control ${super.buildCSSClass()}`;
  13363. }
  13364. /**
  13365. * This gets called when an `PlayToggle` is "clicked". See
  13366. * {@link ClickableComponent} for more detailed information on what a click can be.
  13367. *
  13368. * @param {Event} [event]
  13369. * The `keydown`, `tap`, or `click` event that caused this function to be
  13370. * called.
  13371. *
  13372. * @listens tap
  13373. * @listens click
  13374. */
  13375. handleClick(event) {
  13376. if (this.player_.paused()) {
  13377. silencePromise(this.player_.play());
  13378. } else {
  13379. this.player_.pause();
  13380. }
  13381. }
  13382. /**
  13383. * This gets called once after the video has ended and the user seeks so that
  13384. * we can change the replay button back to a play button.
  13385. *
  13386. * @param {Event} [event]
  13387. * The event that caused this function to run.
  13388. *
  13389. * @listens Player#seeked
  13390. */
  13391. handleSeeked(event) {
  13392. this.removeClass('vjs-ended');
  13393. if (this.player_.paused()) {
  13394. this.handlePause(event);
  13395. } else {
  13396. this.handlePlay(event);
  13397. }
  13398. }
  13399. /**
  13400. * Add the vjs-playing class to the element so it can change appearance.
  13401. *
  13402. * @param {Event} [event]
  13403. * The event that caused this function to run.
  13404. *
  13405. * @listens Player#play
  13406. */
  13407. handlePlay(event) {
  13408. this.removeClass('vjs-ended', 'vjs-paused');
  13409. this.addClass('vjs-playing');
  13410. // change the button text to "Pause"
  13411. this.setIcon('pause');
  13412. this.controlText('Pause');
  13413. }
  13414. /**
  13415. * Add the vjs-paused class to the element so it can change appearance.
  13416. *
  13417. * @param {Event} [event]
  13418. * The event that caused this function to run.
  13419. *
  13420. * @listens Player#pause
  13421. */
  13422. handlePause(event) {
  13423. this.removeClass('vjs-playing');
  13424. this.addClass('vjs-paused');
  13425. // change the button text to "Play"
  13426. this.setIcon('play');
  13427. this.controlText('Play');
  13428. }
  13429. /**
  13430. * Add the vjs-ended class to the element so it can change appearance
  13431. *
  13432. * @param {Event} [event]
  13433. * The event that caused this function to run.
  13434. *
  13435. * @listens Player#ended
  13436. */
  13437. handleEnded(event) {
  13438. this.removeClass('vjs-playing');
  13439. this.addClass('vjs-ended');
  13440. // change the button text to "Replay"
  13441. this.setIcon('replay');
  13442. this.controlText('Replay');
  13443. // on the next seek remove the replay button
  13444. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  13445. }
  13446. }
  13447. /**
  13448. * The text that should display over the `PlayToggle`s controls. Added for localization.
  13449. *
  13450. * @type {string}
  13451. * @protected
  13452. */
  13453. PlayToggle.prototype.controlText_ = 'Play';
  13454. Component.registerComponent('PlayToggle', PlayToggle);
  13455. /**
  13456. * @file time-display.js
  13457. */
  13458. /** @import Player from '../../player' */
  13459. /**
  13460. * Displays time information about the video
  13461. *
  13462. * @extends Component
  13463. */
  13464. class TimeDisplay extends Component {
  13465. /**
  13466. * Creates an instance of this class.
  13467. *
  13468. * @param {Player} player
  13469. * The `Player` that this class should be attached to.
  13470. *
  13471. * @param {Object} [options]
  13472. * The key/value store of player options.
  13473. */
  13474. constructor(player, options) {
  13475. super(player, options);
  13476. this.on(player, ['timeupdate', 'ended', 'seeking'], e => this.update(e));
  13477. this.updateTextNode_();
  13478. }
  13479. /**
  13480. * Create the `Component`'s DOM element
  13481. *
  13482. * @return {Element}
  13483. * The element that was created.
  13484. */
  13485. createEl() {
  13486. const className = this.buildCSSClass();
  13487. const el = super.createEl('div', {
  13488. className: `${className} vjs-time-control vjs-control`
  13489. });
  13490. const span = createEl('span', {
  13491. className: 'vjs-control-text',
  13492. textContent: `${this.localize(this.labelText_)}\u00a0`
  13493. }, {
  13494. role: 'presentation'
  13495. });
  13496. el.appendChild(span);
  13497. this.contentEl_ = createEl('span', {
  13498. className: `${className}-display`
  13499. }, {
  13500. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  13501. // treat them as a break between items in the DOM when using arrow keys
  13502. // (or left-to-right swipes on iOS) to read contents of a page. Using
  13503. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  13504. role: 'presentation'
  13505. });
  13506. el.appendChild(this.contentEl_);
  13507. return el;
  13508. }
  13509. dispose() {
  13510. this.contentEl_ = null;
  13511. this.textNode_ = null;
  13512. super.dispose();
  13513. }
  13514. /**
  13515. * Updates the displayed time according to the `updateContent` function which is defined in the child class.
  13516. *
  13517. * @param {Event} [event]
  13518. * The `timeupdate`, `ended` or `seeking` (if enableSmoothSeeking is true) event that caused this function to be called.
  13519. */
  13520. update(event) {
  13521. if (!this.player_.options_.enableSmoothSeeking && event.type === 'seeking') {
  13522. return;
  13523. }
  13524. this.updateContent(event);
  13525. }
  13526. /**
  13527. * Updates the time display text node with a new time
  13528. *
  13529. * @param {number} [time=0] the time to update to
  13530. *
  13531. * @private
  13532. */
  13533. updateTextNode_(time = 0) {
  13534. time = formatTime(time);
  13535. if (this.formattedTime_ === time) {
  13536. return;
  13537. }
  13538. this.formattedTime_ = time;
  13539. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  13540. if (!this.contentEl_) {
  13541. return;
  13542. }
  13543. let oldNode = this.textNode_;
  13544. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  13545. oldNode = null;
  13546. log.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.');
  13547. }
  13548. this.textNode_ = document.createTextNode(this.formattedTime_);
  13549. if (!this.textNode_) {
  13550. return;
  13551. }
  13552. if (oldNode) {
  13553. this.contentEl_.replaceChild(this.textNode_, oldNode);
  13554. } else {
  13555. this.contentEl_.appendChild(this.textNode_);
  13556. }
  13557. });
  13558. }
  13559. /**
  13560. * To be filled out in the child class, should update the displayed time
  13561. * in accordance with the fact that the current time has changed.
  13562. *
  13563. * @param {Event} [event]
  13564. * The `timeupdate` event that caused this to run.
  13565. *
  13566. * @listens Player#timeupdate
  13567. */
  13568. updateContent(event) {}
  13569. }
  13570. /**
  13571. * The text that is added to the `TimeDisplay` for screen reader users.
  13572. *
  13573. * @type {string}
  13574. * @private
  13575. */
  13576. TimeDisplay.prototype.labelText_ = 'Time';
  13577. /**
  13578. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  13579. *
  13580. * @type {string}
  13581. * @protected
  13582. *
  13583. * @deprecated in v7; controlText_ is not used in non-active display Components
  13584. */
  13585. TimeDisplay.prototype.controlText_ = 'Time';
  13586. Component.registerComponent('TimeDisplay', TimeDisplay);
  13587. /**
  13588. * @file current-time-display.js
  13589. */
  13590. /**
  13591. * Displays the current time
  13592. *
  13593. * @extends Component
  13594. */
  13595. class CurrentTimeDisplay extends TimeDisplay {
  13596. /**
  13597. * Builds the default DOM `className`.
  13598. *
  13599. * @return {string}
  13600. * The DOM `className` for this object.
  13601. */
  13602. buildCSSClass() {
  13603. return 'vjs-current-time';
  13604. }
  13605. /**
  13606. * Update current time display
  13607. *
  13608. * @param {Event} [event]
  13609. * The `timeupdate` event that caused this function to run.
  13610. *
  13611. * @listens Player#timeupdate
  13612. */
  13613. updateContent(event) {
  13614. // Allows for smooth scrubbing, when player can't keep up.
  13615. let time;
  13616. if (this.player_.ended()) {
  13617. time = this.player_.duration();
  13618. } else {
  13619. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13620. }
  13621. this.updateTextNode_(time);
  13622. }
  13623. }
  13624. /**
  13625. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  13626. *
  13627. * @type {string}
  13628. * @private
  13629. */
  13630. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  13631. /**
  13632. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  13633. *
  13634. * @type {string}
  13635. * @protected
  13636. *
  13637. * @deprecated in v7; controlText_ is not used in non-active display Components
  13638. */
  13639. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  13640. Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  13641. /**
  13642. * @file duration-display.js
  13643. */
  13644. /** @import Player from '../../player' */
  13645. /**
  13646. * Displays the duration
  13647. *
  13648. * @extends Component
  13649. */
  13650. class DurationDisplay extends TimeDisplay {
  13651. /**
  13652. * Creates an instance of this class.
  13653. *
  13654. * @param {Player} player
  13655. * The `Player` that this class should be attached to.
  13656. *
  13657. * @param {Object} [options]
  13658. * The key/value store of player options.
  13659. */
  13660. constructor(player, options) {
  13661. super(player, options);
  13662. const updateContent = e => this.updateContent(e);
  13663. // we do not want to/need to throttle duration changes,
  13664. // as they should always display the changed duration as
  13665. // it has changed
  13666. this.on(player, 'durationchange', updateContent);
  13667. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  13668. // but the durationchange on the user agent will not fire.
  13669. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  13670. this.on(player, 'loadstart', updateContent);
  13671. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  13672. // listeners could have broken dependent applications/libraries. These
  13673. // can likely be removed for 7.0.
  13674. this.on(player, 'loadedmetadata', updateContent);
  13675. }
  13676. /**
  13677. * Builds the default DOM `className`.
  13678. *
  13679. * @return {string}
  13680. * The DOM `className` for this object.
  13681. */
  13682. buildCSSClass() {
  13683. return 'vjs-duration';
  13684. }
  13685. /**
  13686. * Update duration time display.
  13687. *
  13688. * @param {Event} [event]
  13689. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  13690. * this function to be called.
  13691. *
  13692. * @listens Player#durationchange
  13693. * @listens Player#timeupdate
  13694. * @listens Player#loadedmetadata
  13695. */
  13696. updateContent(event) {
  13697. const duration = this.player_.duration();
  13698. this.updateTextNode_(duration);
  13699. }
  13700. }
  13701. /**
  13702. * The text that is added to the `DurationDisplay` for screen reader users.
  13703. *
  13704. * @type {string}
  13705. * @private
  13706. */
  13707. DurationDisplay.prototype.labelText_ = 'Duration';
  13708. /**
  13709. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  13710. *
  13711. * @type {string}
  13712. * @protected
  13713. *
  13714. * @deprecated in v7; controlText_ is not used in non-active display Components
  13715. */
  13716. DurationDisplay.prototype.controlText_ = 'Duration';
  13717. Component.registerComponent('DurationDisplay', DurationDisplay);
  13718. /**
  13719. * @file time-divider.js
  13720. */
  13721. /**
  13722. * The separator between the current time and duration.
  13723. * Can be hidden if it's not needed in the design.
  13724. *
  13725. * @extends Component
  13726. */
  13727. class TimeDivider extends Component {
  13728. /**
  13729. * Create the component's DOM element
  13730. *
  13731. * @return {Element}
  13732. * The element that was created.
  13733. */
  13734. createEl() {
  13735. const el = super.createEl('div', {
  13736. className: 'vjs-time-control vjs-time-divider'
  13737. }, {
  13738. // this element and its contents can be hidden from assistive techs since
  13739. // it is made extraneous by the announcement of the control text
  13740. // for the current time and duration displays
  13741. 'aria-hidden': true
  13742. });
  13743. const div = super.createEl('div');
  13744. const span = super.createEl('span', {
  13745. textContent: '/'
  13746. });
  13747. div.appendChild(span);
  13748. el.appendChild(div);
  13749. return el;
  13750. }
  13751. }
  13752. Component.registerComponent('TimeDivider', TimeDivider);
  13753. /**
  13754. * @file remaining-time-display.js
  13755. */
  13756. /** @import Player from '../../player' */
  13757. /**
  13758. * Displays the time left in the video
  13759. *
  13760. * @extends Component
  13761. */
  13762. class RemainingTimeDisplay extends TimeDisplay {
  13763. /**
  13764. * Creates an instance of this class.
  13765. *
  13766. * @param {Player} player
  13767. * The `Player` that this class should be attached to.
  13768. *
  13769. * @param {Object} [options]
  13770. * The key/value store of player options.
  13771. */
  13772. constructor(player, options) {
  13773. super(player, options);
  13774. this.on(player, 'durationchange', e => this.updateContent(e));
  13775. }
  13776. /**
  13777. * Builds the default DOM `className`.
  13778. *
  13779. * @return {string}
  13780. * The DOM `className` for this object.
  13781. */
  13782. buildCSSClass() {
  13783. return 'vjs-remaining-time';
  13784. }
  13785. /**
  13786. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  13787. *
  13788. * @return {Element}
  13789. * The element that was created.
  13790. */
  13791. createEl() {
  13792. const el = super.createEl();
  13793. if (this.options_.displayNegative !== false) {
  13794. el.insertBefore(createEl('span', {}, {
  13795. 'aria-hidden': true
  13796. }, '-'), this.contentEl_);
  13797. }
  13798. return el;
  13799. }
  13800. /**
  13801. * Update remaining time display.
  13802. *
  13803. * @param {Event} [event]
  13804. * The `timeupdate` or `durationchange` event that caused this to run.
  13805. *
  13806. * @listens Player#timeupdate
  13807. * @listens Player#durationchange
  13808. */
  13809. updateContent(event) {
  13810. if (typeof this.player_.duration() !== 'number') {
  13811. return;
  13812. }
  13813. let time;
  13814. // @deprecated We should only use remainingTimeDisplay
  13815. // as of video.js 7
  13816. if (this.player_.ended()) {
  13817. time = 0;
  13818. } else if (this.player_.remainingTimeDisplay) {
  13819. time = this.player_.remainingTimeDisplay();
  13820. } else {
  13821. time = this.player_.remainingTime();
  13822. }
  13823. this.updateTextNode_(time);
  13824. }
  13825. }
  13826. /**
  13827. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  13828. *
  13829. * @type {string}
  13830. * @private
  13831. */
  13832. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  13833. /**
  13834. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  13835. *
  13836. * @type {string}
  13837. * @protected
  13838. *
  13839. * @deprecated in v7; controlText_ is not used in non-active display Components
  13840. */
  13841. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  13842. Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  13843. /**
  13844. * @file live-display.js
  13845. */
  13846. /** @import Player from './player' */
  13847. // TODO - Future make it click to snap to live
  13848. /**
  13849. * Displays the live indicator when duration is Infinity.
  13850. *
  13851. * @extends Component
  13852. */
  13853. class LiveDisplay extends Component {
  13854. /**
  13855. * Creates an instance of this class.
  13856. *
  13857. * @param {Player} player
  13858. * The `Player` that this class should be attached to.
  13859. *
  13860. * @param {Object} [options]
  13861. * The key/value store of player options.
  13862. */
  13863. constructor(player, options) {
  13864. super(player, options);
  13865. this.updateShowing();
  13866. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  13867. }
  13868. /**
  13869. * Create the `Component`'s DOM element
  13870. *
  13871. * @return {Element}
  13872. * The element that was created.
  13873. */
  13874. createEl() {
  13875. const el = super.createEl('div', {
  13876. className: 'vjs-live-control vjs-control'
  13877. });
  13878. this.contentEl_ = createEl('div', {
  13879. className: 'vjs-live-display'
  13880. }, {
  13881. 'aria-live': 'off'
  13882. });
  13883. this.contentEl_.appendChild(createEl('span', {
  13884. className: 'vjs-control-text',
  13885. textContent: `${this.localize('Stream Type')}\u00a0`
  13886. }));
  13887. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  13888. el.appendChild(this.contentEl_);
  13889. return el;
  13890. }
  13891. dispose() {
  13892. this.contentEl_ = null;
  13893. super.dispose();
  13894. }
  13895. /**
  13896. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  13897. * it accordingly
  13898. *
  13899. * @param {Event} [event]
  13900. * The {@link Player#durationchange} event that caused this function to run.
  13901. *
  13902. * @listens Player#durationchange
  13903. */
  13904. updateShowing(event) {
  13905. if (this.player().duration() === Infinity) {
  13906. this.show();
  13907. } else {
  13908. this.hide();
  13909. }
  13910. }
  13911. }
  13912. Component.registerComponent('LiveDisplay', LiveDisplay);
  13913. /**
  13914. * @file seek-to-live.js
  13915. */
  13916. /** @import Player from './player' */
  13917. /**
  13918. * Displays the live indicator when duration is Infinity.
  13919. *
  13920. * @extends Component
  13921. */
  13922. class SeekToLive extends Button {
  13923. /**
  13924. * Creates an instance of this class.
  13925. *
  13926. * @param {Player} player
  13927. * The `Player` that this class should be attached to.
  13928. *
  13929. * @param {Object} [options]
  13930. * The key/value store of player options.
  13931. */
  13932. constructor(player, options) {
  13933. super(player, options);
  13934. this.updateLiveEdgeStatus();
  13935. if (this.player_.liveTracker) {
  13936. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  13937. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  13938. }
  13939. }
  13940. /**
  13941. * Create the `Component`'s DOM element
  13942. *
  13943. * @return {Element}
  13944. * The element that was created.
  13945. */
  13946. createEl() {
  13947. const el = super.createEl('button', {
  13948. className: 'vjs-seek-to-live-control vjs-control'
  13949. });
  13950. this.setIcon('circle', el);
  13951. this.textEl_ = createEl('span', {
  13952. className: 'vjs-seek-to-live-text',
  13953. textContent: this.localize('LIVE')
  13954. }, {
  13955. 'aria-hidden': 'true'
  13956. });
  13957. el.appendChild(this.textEl_);
  13958. return el;
  13959. }
  13960. /**
  13961. * Update the state of this button if we are at the live edge
  13962. * or not
  13963. */
  13964. updateLiveEdgeStatus() {
  13965. // default to live edge
  13966. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  13967. this.setAttribute('aria-disabled', true);
  13968. this.addClass('vjs-at-live-edge');
  13969. this.controlText('Seek to live, currently playing live');
  13970. } else {
  13971. this.setAttribute('aria-disabled', false);
  13972. this.removeClass('vjs-at-live-edge');
  13973. this.controlText('Seek to live, currently behind live');
  13974. }
  13975. }
  13976. /**
  13977. * On click bring us as near to the live point as possible.
  13978. * This requires that we wait for the next `live-seekable-change`
  13979. * event which will happen every segment length seconds.
  13980. */
  13981. handleClick() {
  13982. this.player_.liveTracker.seekToLiveEdge();
  13983. }
  13984. /**
  13985. * Dispose of the element and stop tracking
  13986. */
  13987. dispose() {
  13988. if (this.player_.liveTracker) {
  13989. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  13990. }
  13991. this.textEl_ = null;
  13992. super.dispose();
  13993. }
  13994. }
  13995. /**
  13996. * The text that should display over the `SeekToLive`s control. Added for localization.
  13997. *
  13998. * @type {string}
  13999. * @protected
  14000. */
  14001. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  14002. Component.registerComponent('SeekToLive', SeekToLive);
  14003. /**
  14004. * @file num.js
  14005. * @module num
  14006. */
  14007. /**
  14008. * Keep a number between a min and a max value
  14009. *
  14010. * @param {number} number
  14011. * The number to clamp
  14012. *
  14013. * @param {number} min
  14014. * The minimum value
  14015. * @param {number} max
  14016. * The maximum value
  14017. *
  14018. * @return {number}
  14019. * the clamped number
  14020. */
  14021. function clamp(number, min, max) {
  14022. number = Number(number);
  14023. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  14024. }
  14025. var Num = /*#__PURE__*/Object.freeze({
  14026. __proto__: null,
  14027. clamp: clamp
  14028. });
  14029. /**
  14030. * @file slider.js
  14031. */
  14032. /** @import Player from '../player' */
  14033. /**
  14034. * The base functionality for a slider. Can be vertical or horizontal.
  14035. * For instance the volume bar or the seek bar on a video is a slider.
  14036. *
  14037. * @extends Component
  14038. */
  14039. class Slider extends Component {
  14040. /**
  14041. * Create an instance of this class
  14042. *
  14043. * @param {Player} player
  14044. * The `Player` that this class should be attached to.
  14045. *
  14046. * @param {Object} [options]
  14047. * The key/value store of player options.
  14048. */
  14049. constructor(player, options) {
  14050. super(player, options);
  14051. this.handleMouseDown_ = e => this.handleMouseDown(e);
  14052. this.handleMouseUp_ = e => this.handleMouseUp(e);
  14053. this.handleKeyDown_ = e => this.handleKeyDown(e);
  14054. this.handleClick_ = e => this.handleClick(e);
  14055. this.handleMouseMove_ = e => this.handleMouseMove(e);
  14056. this.update_ = e => this.update(e);
  14057. // Set property names to bar to match with the child Slider class is looking for
  14058. this.bar = this.getChild(this.options_.barName);
  14059. // Set a horizontal or vertical class on the slider depending on the slider type
  14060. this.vertical(!!this.options_.vertical);
  14061. this.enable();
  14062. }
  14063. /**
  14064. * Are controls are currently enabled for this slider or not.
  14065. *
  14066. * @return {boolean}
  14067. * true if controls are enabled, false otherwise
  14068. */
  14069. enabled() {
  14070. return this.enabled_;
  14071. }
  14072. /**
  14073. * Enable controls for this slider if they are disabled
  14074. */
  14075. enable() {
  14076. if (this.enabled()) {
  14077. return;
  14078. }
  14079. this.on('mousedown', this.handleMouseDown_);
  14080. this.on('touchstart', this.handleMouseDown_);
  14081. this.on('keydown', this.handleKeyDown_);
  14082. this.on('click', this.handleClick_);
  14083. // TODO: deprecated, controlsvisible does not seem to be fired
  14084. this.on(this.player_, 'controlsvisible', this.update);
  14085. if (this.playerEvent) {
  14086. this.on(this.player_, this.playerEvent, this.update);
  14087. }
  14088. this.removeClass('disabled');
  14089. this.setAttribute('tabindex', 0);
  14090. this.enabled_ = true;
  14091. }
  14092. /**
  14093. * Disable controls for this slider if they are enabled
  14094. */
  14095. disable() {
  14096. if (!this.enabled()) {
  14097. return;
  14098. }
  14099. const doc = this.bar.el_.ownerDocument;
  14100. this.off('mousedown', this.handleMouseDown_);
  14101. this.off('touchstart', this.handleMouseDown_);
  14102. this.off('keydown', this.handleKeyDown_);
  14103. this.off('click', this.handleClick_);
  14104. this.off(this.player_, 'controlsvisible', this.update_);
  14105. this.off(doc, 'mousemove', this.handleMouseMove_);
  14106. this.off(doc, 'mouseup', this.handleMouseUp_);
  14107. this.off(doc, 'touchmove', this.handleMouseMove_);
  14108. this.off(doc, 'touchend', this.handleMouseUp_);
  14109. this.removeAttribute('tabindex');
  14110. this.addClass('disabled');
  14111. if (this.playerEvent) {
  14112. this.off(this.player_, this.playerEvent, this.update);
  14113. }
  14114. this.enabled_ = false;
  14115. }
  14116. /**
  14117. * Create the `Slider`s DOM element.
  14118. *
  14119. * @param {string} type
  14120. * Type of element to create.
  14121. *
  14122. * @param {Object} [props={}]
  14123. * List of properties in Object form.
  14124. *
  14125. * @param {Object} [attributes={}]
  14126. * list of attributes in Object form.
  14127. *
  14128. * @return {Element}
  14129. * The element that gets created.
  14130. */
  14131. createEl(type, props = {}, attributes = {}) {
  14132. // Add the slider element class to all sub classes
  14133. props.className = props.className + ' vjs-slider';
  14134. props = Object.assign({
  14135. tabIndex: 0
  14136. }, props);
  14137. attributes = Object.assign({
  14138. 'role': 'slider',
  14139. 'aria-valuenow': 0,
  14140. 'aria-valuemin': 0,
  14141. 'aria-valuemax': 100
  14142. }, attributes);
  14143. return super.createEl(type, props, attributes);
  14144. }
  14145. /**
  14146. * Handle `mousedown` or `touchstart` events on the `Slider`.
  14147. *
  14148. * @param {MouseEvent} event
  14149. * `mousedown` or `touchstart` event that triggered this function
  14150. *
  14151. * @listens mousedown
  14152. * @listens touchstart
  14153. * @fires Slider#slideractive
  14154. */
  14155. handleMouseDown(event) {
  14156. const doc = this.bar.el_.ownerDocument;
  14157. if (event.type === 'mousedown') {
  14158. event.preventDefault();
  14159. }
  14160. // Do not call preventDefault() on touchstart in Chrome
  14161. // to avoid console warnings. Use a 'touch-action: none' style
  14162. // instead to prevent unintended scrolling.
  14163. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  14164. if (event.type === 'touchstart' && !IS_CHROME) {
  14165. event.preventDefault();
  14166. }
  14167. blockTextSelection();
  14168. this.addClass('vjs-sliding');
  14169. /**
  14170. * Triggered when the slider is in an active state
  14171. *
  14172. * @event Slider#slideractive
  14173. * @type {MouseEvent}
  14174. */
  14175. this.trigger('slideractive');
  14176. this.on(doc, 'mousemove', this.handleMouseMove_);
  14177. this.on(doc, 'mouseup', this.handleMouseUp_);
  14178. this.on(doc, 'touchmove', this.handleMouseMove_);
  14179. this.on(doc, 'touchend', this.handleMouseUp_);
  14180. this.handleMouseMove(event, true);
  14181. }
  14182. /**
  14183. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  14184. * The `mousemove` and `touchmove` events will only only trigger this function during
  14185. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  14186. * {@link Slider#handleMouseUp}.
  14187. *
  14188. * @param {MouseEvent} event
  14189. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  14190. * this function
  14191. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false.
  14192. *
  14193. * @listens mousemove
  14194. * @listens touchmove
  14195. */
  14196. handleMouseMove(event) {}
  14197. /**
  14198. * Handle `mouseup` or `touchend` events on the `Slider`.
  14199. *
  14200. * @param {MouseEvent} event
  14201. * `mouseup` or `touchend` event that triggered this function.
  14202. *
  14203. * @listens touchend
  14204. * @listens mouseup
  14205. * @fires Slider#sliderinactive
  14206. */
  14207. handleMouseUp(event) {
  14208. const doc = this.bar.el_.ownerDocument;
  14209. unblockTextSelection();
  14210. this.removeClass('vjs-sliding');
  14211. /**
  14212. * Triggered when the slider is no longer in an active state.
  14213. *
  14214. * @event Slider#sliderinactive
  14215. * @type {Event}
  14216. */
  14217. this.trigger('sliderinactive');
  14218. this.off(doc, 'mousemove', this.handleMouseMove_);
  14219. this.off(doc, 'mouseup', this.handleMouseUp_);
  14220. this.off(doc, 'touchmove', this.handleMouseMove_);
  14221. this.off(doc, 'touchend', this.handleMouseUp_);
  14222. this.update();
  14223. }
  14224. /**
  14225. * Update the progress bar of the `Slider`.
  14226. *
  14227. * @return {number}
  14228. * The percentage of progress the progress bar represents as a
  14229. * number from 0 to 1.
  14230. */
  14231. update() {
  14232. // In VolumeBar init we have a setTimeout for update that pops and update
  14233. // to the end of the execution stack. The player is destroyed before then
  14234. // update will cause an error
  14235. // If there's no bar...
  14236. if (!this.el_ || !this.bar) {
  14237. return;
  14238. }
  14239. // clamp progress between 0 and 1
  14240. // and only round to four decimal places, as we round to two below
  14241. const progress = this.getProgress();
  14242. if (progress === this.progress_) {
  14243. return progress;
  14244. }
  14245. this.progress_ = progress;
  14246. this.requestNamedAnimationFrame('Slider#update', () => {
  14247. // Set the new bar width or height
  14248. const sizeKey = this.vertical() ? 'height' : 'width';
  14249. // Convert to a percentage for css value
  14250. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  14251. });
  14252. return progress;
  14253. }
  14254. /**
  14255. * Get the percentage of the bar that should be filled
  14256. * but clamped and rounded.
  14257. *
  14258. * @return {number}
  14259. * percentage filled that the slider is
  14260. */
  14261. getProgress() {
  14262. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  14263. }
  14264. /**
  14265. * Calculate distance for slider
  14266. *
  14267. * @param {Event} event
  14268. * The event that caused this function to run.
  14269. *
  14270. * @return {number}
  14271. * The current position of the Slider.
  14272. * - position.x for vertical `Slider`s
  14273. * - position.y for horizontal `Slider`s
  14274. */
  14275. calculateDistance(event) {
  14276. const position = getPointerPosition(this.el_, event);
  14277. if (this.vertical()) {
  14278. return position.y;
  14279. }
  14280. return position.x;
  14281. }
  14282. /**
  14283. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  14284. * arrow keys. This function will only be called when the slider has focus. See
  14285. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  14286. *
  14287. * @param {KeyboardEvent} event
  14288. * the `keydown` event that caused this function to run.
  14289. *
  14290. * @listens keydown
  14291. */
  14292. handleKeyDown(event) {
  14293. const spatialNavOptions = this.options_.playerOptions.spatialNavigation;
  14294. const spatialNavEnabled = spatialNavOptions && spatialNavOptions.enabled;
  14295. const horizontalSeek = spatialNavOptions && spatialNavOptions.horizontalSeek;
  14296. if (spatialNavEnabled) {
  14297. if (horizontalSeek && event.key === 'ArrowLeft' || !horizontalSeek && event.key === 'ArrowDown') {
  14298. event.preventDefault();
  14299. event.stopPropagation();
  14300. this.stepBack();
  14301. } else if (horizontalSeek && event.key === 'ArrowRight' || !horizontalSeek && event.key === 'ArrowUp') {
  14302. event.preventDefault();
  14303. event.stopPropagation();
  14304. this.stepForward();
  14305. } else {
  14306. super.handleKeyDown(event);
  14307. }
  14308. // Left and Down Arrows
  14309. } else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {
  14310. event.preventDefault();
  14311. event.stopPropagation();
  14312. this.stepBack();
  14313. // Up and Right Arrows
  14314. } else if (event.key === 'ArrowUp' || event.key === 'ArrowRight') {
  14315. event.preventDefault();
  14316. event.stopPropagation();
  14317. this.stepForward();
  14318. } else {
  14319. // Pass keydown handling up for unsupported keys
  14320. super.handleKeyDown(event);
  14321. }
  14322. }
  14323. /**
  14324. * Listener for click events on slider, used to prevent clicks
  14325. * from bubbling up to parent elements like button menus.
  14326. *
  14327. * @param {Object} event
  14328. * Event that caused this object to run
  14329. */
  14330. handleClick(event) {
  14331. event.stopPropagation();
  14332. event.preventDefault();
  14333. }
  14334. /**
  14335. * Get/set if slider is horizontal for vertical
  14336. *
  14337. * @param {boolean} [bool]
  14338. * - true if slider is vertical,
  14339. * - false is horizontal
  14340. *
  14341. * @return {boolean}
  14342. * - true if slider is vertical, and getting
  14343. * - false if the slider is horizontal, and getting
  14344. */
  14345. vertical(bool) {
  14346. if (bool === undefined) {
  14347. return this.vertical_ || false;
  14348. }
  14349. this.vertical_ = !!bool;
  14350. if (this.vertical_) {
  14351. this.addClass('vjs-slider-vertical');
  14352. } else {
  14353. this.addClass('vjs-slider-horizontal');
  14354. }
  14355. }
  14356. }
  14357. Component.registerComponent('Slider', Slider);
  14358. /**
  14359. * @file load-progress-bar.js
  14360. */
  14361. /** @import Player from '../../player' */
  14362. // get the percent width of a time compared to the total end
  14363. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  14364. /**
  14365. * Shows loading progress
  14366. *
  14367. * @extends Component
  14368. */
  14369. class LoadProgressBar extends Component {
  14370. /**
  14371. * Creates an instance of this class.
  14372. *
  14373. * @param {Player} player
  14374. * The `Player` that this class should be attached to.
  14375. *
  14376. * @param {Object} [options]
  14377. * The key/value store of player options.
  14378. */
  14379. constructor(player, options) {
  14380. super(player, options);
  14381. this.partEls_ = [];
  14382. this.on(player, 'progress', e => this.update(e));
  14383. }
  14384. /**
  14385. * Create the `Component`'s DOM element
  14386. *
  14387. * @return {Element}
  14388. * The element that was created.
  14389. */
  14390. createEl() {
  14391. const el = super.createEl('div', {
  14392. className: 'vjs-load-progress'
  14393. });
  14394. const wrapper = createEl('span', {
  14395. className: 'vjs-control-text'
  14396. });
  14397. const loadedText = createEl('span', {
  14398. textContent: this.localize('Loaded')
  14399. });
  14400. const separator = document.createTextNode(': ');
  14401. this.percentageEl_ = createEl('span', {
  14402. className: 'vjs-control-text-loaded-percentage',
  14403. textContent: '0%'
  14404. });
  14405. el.appendChild(wrapper);
  14406. wrapper.appendChild(loadedText);
  14407. wrapper.appendChild(separator);
  14408. wrapper.appendChild(this.percentageEl_);
  14409. return el;
  14410. }
  14411. dispose() {
  14412. this.partEls_ = null;
  14413. this.percentageEl_ = null;
  14414. super.dispose();
  14415. }
  14416. /**
  14417. * Update progress bar
  14418. *
  14419. * @param {Event} [event]
  14420. * The `progress` event that caused this function to run.
  14421. *
  14422. * @listens Player#progress
  14423. */
  14424. update(event) {
  14425. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  14426. const liveTracker = this.player_.liveTracker;
  14427. const buffered = this.player_.buffered();
  14428. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  14429. const bufferedEnd = this.player_.bufferedEnd();
  14430. const children = this.partEls_;
  14431. const percent = percentify(bufferedEnd, duration);
  14432. if (this.percent_ !== percent) {
  14433. // update the width of the progress bar
  14434. this.el_.style.width = percent;
  14435. // update the control-text
  14436. textContent(this.percentageEl_, percent);
  14437. this.percent_ = percent;
  14438. }
  14439. // add child elements to represent the individual buffered time ranges
  14440. for (let i = 0; i < buffered.length; i++) {
  14441. const start = buffered.start(i);
  14442. const end = buffered.end(i);
  14443. let part = children[i];
  14444. if (!part) {
  14445. part = this.el_.appendChild(createEl());
  14446. children[i] = part;
  14447. }
  14448. // only update if changed
  14449. if (part.dataset.start === start && part.dataset.end === end) {
  14450. continue;
  14451. }
  14452. part.dataset.start = start;
  14453. part.dataset.end = end;
  14454. // set the percent based on the width of the progress bar (bufferedEnd)
  14455. part.style.left = percentify(start, bufferedEnd);
  14456. part.style.width = percentify(end - start, bufferedEnd);
  14457. }
  14458. // remove unused buffered range elements
  14459. for (let i = children.length; i > buffered.length; i--) {
  14460. this.el_.removeChild(children[i - 1]);
  14461. }
  14462. children.length = buffered.length;
  14463. });
  14464. }
  14465. }
  14466. Component.registerComponent('LoadProgressBar', LoadProgressBar);
  14467. /**
  14468. * @file time-tooltip.js
  14469. */
  14470. /** @import Player from '../../player' */
  14471. /**
  14472. * Time tooltips display a time above the progress bar.
  14473. *
  14474. * @extends Component
  14475. */
  14476. class TimeTooltip extends Component {
  14477. /**
  14478. * Creates an instance of this class.
  14479. *
  14480. * @param {Player} player
  14481. * The {@link Player} that this class should be attached to.
  14482. *
  14483. * @param {Object} [options]
  14484. * The key/value store of player options.
  14485. */
  14486. constructor(player, options) {
  14487. super(player, options);
  14488. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14489. }
  14490. /**
  14491. * Create the time tooltip DOM element
  14492. *
  14493. * @return {Element}
  14494. * The element that was created.
  14495. */
  14496. createEl() {
  14497. return super.createEl('div', {
  14498. className: 'vjs-time-tooltip'
  14499. }, {
  14500. 'aria-hidden': 'true'
  14501. });
  14502. }
  14503. /**
  14504. * Updates the position of the time tooltip relative to the `SeekBar`.
  14505. *
  14506. * @param {Object} seekBarRect
  14507. * The `ClientRect` for the {@link SeekBar} element.
  14508. *
  14509. * @param {number} seekBarPoint
  14510. * A number from 0 to 1, representing a horizontal reference point
  14511. * from the left edge of the {@link SeekBar}
  14512. */
  14513. update(seekBarRect, seekBarPoint, content) {
  14514. const tooltipRect = findPosition(this.el_);
  14515. const playerRect = getBoundingClientRect(this.player_.el());
  14516. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  14517. // do nothing if either rect isn't available
  14518. // for example, if the player isn't in the DOM for testing
  14519. if (!playerRect || !tooltipRect) {
  14520. return;
  14521. }
  14522. // This is the space left of the `seekBarPoint` available within the bounds
  14523. // of the player. We calculate any gap between the left edge of the player
  14524. // and the left edge of the `SeekBar` and add the number of pixels in the
  14525. // `SeekBar` before hitting the `seekBarPoint`
  14526. let spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  14527. // This is the space right of the `seekBarPoint` available within the bounds
  14528. // of the player. We calculate the number of pixels from the `seekBarPoint`
  14529. // to the right edge of the `SeekBar` and add to that any gap between the
  14530. // right edge of the `SeekBar` and the player.
  14531. let spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  14532. // spaceRightOfPoint is always NaN for mouse time display
  14533. // because the seekbarRect does not have a right property. This causes
  14534. // the mouse tool tip to be truncated when it's close to the right edge of the player.
  14535. // In such cases, we ignore the `playerRect.right - seekBarRect.right` value when calculating.
  14536. // For the sake of consistency, we ignore seekBarRect.left - playerRect.left for the left edge.
  14537. if (!spaceRightOfPoint) {
  14538. spaceRightOfPoint = seekBarRect.width - seekBarPointPx;
  14539. spaceLeftOfPoint = seekBarPointPx;
  14540. }
  14541. // This is the number of pixels by which the tooltip will need to be pulled
  14542. // further to the right to center it over the `seekBarPoint`.
  14543. let pullTooltipBy = tooltipRect.width / 2;
  14544. // Adjust the `pullTooltipBy` distance to the left or right depending on
  14545. // the results of the space calculations above.
  14546. if (spaceLeftOfPoint < pullTooltipBy) {
  14547. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  14548. } else if (spaceRightOfPoint < pullTooltipBy) {
  14549. pullTooltipBy = spaceRightOfPoint;
  14550. }
  14551. // Due to the imprecision of decimal/ratio based calculations and varying
  14552. // rounding behaviors, there are cases where the spacing adjustment is off
  14553. // by a pixel or two. This adds insurance to these calculations.
  14554. if (pullTooltipBy < 0) {
  14555. pullTooltipBy = 0;
  14556. } else if (pullTooltipBy > tooltipRect.width) {
  14557. pullTooltipBy = tooltipRect.width;
  14558. }
  14559. // prevent small width fluctuations within 0.4px from
  14560. // changing the value below.
  14561. // This really helps for live to prevent the play
  14562. // progress time tooltip from jittering
  14563. pullTooltipBy = Math.round(pullTooltipBy);
  14564. this.el_.style.right = `-${pullTooltipBy}px`;
  14565. this.write(content);
  14566. }
  14567. /**
  14568. * Write the time to the tooltip DOM element.
  14569. *
  14570. * @param {string} content
  14571. * The formatted time for the tooltip.
  14572. */
  14573. write(content) {
  14574. textContent(this.el_, content);
  14575. }
  14576. /**
  14577. * Updates the position of the time tooltip relative to the `SeekBar`.
  14578. *
  14579. * @param {Object} seekBarRect
  14580. * The `ClientRect` for the {@link SeekBar} element.
  14581. *
  14582. * @param {number} seekBarPoint
  14583. * A number from 0 to 1, representing a horizontal reference point
  14584. * from the left edge of the {@link SeekBar}
  14585. *
  14586. * @param {number} time
  14587. * The time to update the tooltip to, not used during live playback
  14588. *
  14589. * @param {Function} cb
  14590. * A function that will be called during the request animation frame
  14591. * for tooltips that need to do additional animations from the default
  14592. */
  14593. updateTime(seekBarRect, seekBarPoint, time, cb) {
  14594. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  14595. let content;
  14596. const duration = this.player_.duration();
  14597. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  14598. const liveWindow = this.player_.liveTracker.liveWindow();
  14599. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  14600. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  14601. } else {
  14602. content = formatTime(time, duration);
  14603. }
  14604. this.update(seekBarRect, seekBarPoint, content);
  14605. if (cb) {
  14606. cb();
  14607. }
  14608. });
  14609. }
  14610. }
  14611. Component.registerComponent('TimeTooltip', TimeTooltip);
  14612. /**
  14613. * @file play-progress-bar.js
  14614. */
  14615. /**
  14616. * Used by {@link SeekBar} to display media playback progress as part of the
  14617. * {@link ProgressControl}.
  14618. *
  14619. * @extends Component
  14620. */
  14621. class PlayProgressBar extends Component {
  14622. /**
  14623. * Creates an instance of this class.
  14624. *
  14625. * @param {Player} player
  14626. * The {@link Player} that this class should be attached to.
  14627. *
  14628. * @param {Object} [options]
  14629. * The key/value store of player options.
  14630. */
  14631. constructor(player, options) {
  14632. super(player, options);
  14633. this.setIcon('circle');
  14634. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14635. }
  14636. /**
  14637. * Create the the DOM element for this class.
  14638. *
  14639. * @return {Element}
  14640. * The element that was created.
  14641. */
  14642. createEl() {
  14643. return super.createEl('div', {
  14644. className: 'vjs-play-progress vjs-slider-bar'
  14645. }, {
  14646. 'aria-hidden': 'true'
  14647. });
  14648. }
  14649. /**
  14650. * Enqueues updates to its own DOM as well as the DOM of its
  14651. * {@link TimeTooltip} child.
  14652. *
  14653. * @param {Object} seekBarRect
  14654. * The `ClientRect` for the {@link SeekBar} element.
  14655. *
  14656. * @param {number} seekBarPoint
  14657. * A number from 0 to 1, representing a horizontal reference point
  14658. * from the left edge of the {@link SeekBar}
  14659. */
  14660. update(seekBarRect, seekBarPoint) {
  14661. const timeTooltip = this.getChild('timeTooltip');
  14662. if (!timeTooltip) {
  14663. return;
  14664. }
  14665. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  14666. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  14667. }
  14668. }
  14669. /**
  14670. * Default options for {@link PlayProgressBar}.
  14671. *
  14672. * @type {Object}
  14673. * @private
  14674. */
  14675. PlayProgressBar.prototype.options_ = {
  14676. children: []
  14677. };
  14678. // Time tooltips should not be added to a player on mobile devices
  14679. if (!IS_IOS && !IS_ANDROID) {
  14680. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  14681. }
  14682. Component.registerComponent('PlayProgressBar', PlayProgressBar);
  14683. /**
  14684. * @file mouse-time-display.js
  14685. */
  14686. /**
  14687. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  14688. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  14689. * indicating the time which is represented by a given point in the
  14690. * {@link ProgressControl}.
  14691. *
  14692. * @extends Component
  14693. */
  14694. class MouseTimeDisplay extends Component {
  14695. /**
  14696. * Creates an instance of this class.
  14697. *
  14698. * @param {Player} player
  14699. * The {@link Player} that this class should be attached to.
  14700. *
  14701. * @param {Object} [options]
  14702. * The key/value store of player options.
  14703. */
  14704. constructor(player, options) {
  14705. super(player, options);
  14706. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14707. }
  14708. /**
  14709. * Create the DOM element for this class.
  14710. *
  14711. * @return {Element}
  14712. * The element that was created.
  14713. */
  14714. createEl() {
  14715. return super.createEl('div', {
  14716. className: 'vjs-mouse-display'
  14717. });
  14718. }
  14719. /**
  14720. * Enqueues updates to its own DOM as well as the DOM of its
  14721. * {@link TimeTooltip} child.
  14722. *
  14723. * @param {Object} seekBarRect
  14724. * The `ClientRect` for the {@link SeekBar} element.
  14725. *
  14726. * @param {number} seekBarPoint
  14727. * A number from 0 to 1, representing a horizontal reference point
  14728. * from the left edge of the {@link SeekBar}
  14729. */
  14730. update(seekBarRect, seekBarPoint) {
  14731. const time = seekBarPoint * this.player_.duration();
  14732. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  14733. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  14734. });
  14735. }
  14736. }
  14737. /**
  14738. * Default options for `MouseTimeDisplay`
  14739. *
  14740. * @type {Object}
  14741. * @private
  14742. */
  14743. MouseTimeDisplay.prototype.options_ = {
  14744. children: ['timeTooltip']
  14745. };
  14746. Component.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  14747. /**
  14748. * @file seek-bar.js
  14749. */
  14750. // The number of seconds the `step*` functions move the timeline.
  14751. const STEP_SECONDS = 5;
  14752. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  14753. const PAGE_KEY_MULTIPLIER = 12;
  14754. /**
  14755. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  14756. * as its `bar`.
  14757. *
  14758. * @extends Slider
  14759. */
  14760. class SeekBar extends Slider {
  14761. /**
  14762. * Creates an instance of this class.
  14763. *
  14764. * @param {Player} player
  14765. * The `Player` that this class should be attached to.
  14766. *
  14767. * @param {Object} [options]
  14768. * The key/value store of player options.
  14769. */
  14770. constructor(player, options) {
  14771. options = merge(SeekBar.prototype.options_, options);
  14772. // Avoid mutating the prototype's `children` array by creating a copy
  14773. options.children = [...options.children];
  14774. const shouldDisableSeekWhileScrubbingOnMobile = player.options_.disableSeekWhileScrubbingOnMobile && (IS_IOS || IS_ANDROID);
  14775. // Add the TimeTooltip as a child if we are on desktop, or on mobile with `disableSeekWhileScrubbingOnMobile: true`
  14776. if (!IS_IOS && !IS_ANDROID || shouldDisableSeekWhileScrubbingOnMobile) {
  14777. options.children.splice(1, 0, 'mouseTimeDisplay');
  14778. }
  14779. super(player, options);
  14780. this.shouldDisableSeekWhileScrubbingOnMobile_ = shouldDisableSeekWhileScrubbingOnMobile;
  14781. this.pendingSeekTime_ = null;
  14782. this.setEventHandlers_();
  14783. }
  14784. /**
  14785. * Sets the event handlers
  14786. *
  14787. * @private
  14788. */
  14789. setEventHandlers_() {
  14790. this.update_ = bind_(this, this.update);
  14791. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  14792. this.on(this.player_, ['durationchange', 'timeupdate'], this.update);
  14793. this.on(this.player_, ['ended'], this.update_);
  14794. if (this.player_.liveTracker) {
  14795. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  14796. }
  14797. // when playing, let's ensure we smoothly update the play progress bar
  14798. // via an interval
  14799. this.updateInterval = null;
  14800. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  14801. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  14802. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  14803. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  14804. // we don't need to update the play progress if the document is hidden,
  14805. // also, this causes the CPU to spike and eventually crash the page on IE11.
  14806. if ('hidden' in document && 'visibilityState' in document) {
  14807. this.on(document, 'visibilitychange', this.toggleVisibility_);
  14808. }
  14809. }
  14810. toggleVisibility_(e) {
  14811. if (document.visibilityState === 'hidden') {
  14812. this.cancelNamedAnimationFrame('SeekBar#update');
  14813. this.cancelNamedAnimationFrame('Slider#update');
  14814. this.disableInterval_(e);
  14815. } else {
  14816. if (!this.player_.ended() && !this.player_.paused()) {
  14817. this.enableInterval_();
  14818. }
  14819. // we just switched back to the page and someone may be looking, so, update ASAP
  14820. this.update();
  14821. }
  14822. }
  14823. enableInterval_() {
  14824. if (this.updateInterval) {
  14825. return;
  14826. }
  14827. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  14828. }
  14829. disableInterval_(e) {
  14830. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  14831. return;
  14832. }
  14833. if (!this.updateInterval) {
  14834. return;
  14835. }
  14836. this.clearInterval(this.updateInterval);
  14837. this.updateInterval = null;
  14838. }
  14839. /**
  14840. * Create the `Component`'s DOM element
  14841. *
  14842. * @return {Element}
  14843. * The element that was created.
  14844. */
  14845. createEl() {
  14846. return super.createEl('div', {
  14847. className: 'vjs-progress-holder'
  14848. }, {
  14849. 'aria-label': this.localize('Progress Bar')
  14850. });
  14851. }
  14852. /**
  14853. * This function updates the play progress bar and accessibility
  14854. * attributes to whatever is passed in.
  14855. *
  14856. * @param {Event} [event]
  14857. * The `timeupdate` or `ended` event that caused this to run.
  14858. *
  14859. * @listens Player#timeupdate
  14860. *
  14861. * @return {number}
  14862. * The current percent at a number from 0-1
  14863. */
  14864. update(event) {
  14865. // ignore updates while the tab is hidden
  14866. if (document.visibilityState === 'hidden') {
  14867. return;
  14868. }
  14869. const percent = super.update();
  14870. this.requestNamedAnimationFrame('SeekBar#update', () => {
  14871. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  14872. const liveTracker = this.player_.liveTracker;
  14873. let duration = this.player_.duration();
  14874. if (liveTracker && liveTracker.isLive()) {
  14875. duration = this.player_.liveTracker.liveCurrentTime();
  14876. }
  14877. if (this.percent_ !== percent) {
  14878. // machine readable value of progress bar (percentage complete)
  14879. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  14880. this.percent_ = percent;
  14881. }
  14882. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  14883. // human readable value of progress bar (time complete)
  14884. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  14885. this.currentTime_ = currentTime;
  14886. this.duration_ = duration;
  14887. }
  14888. // update the progress bar time tooltip with the current time
  14889. if (this.bar) {
  14890. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  14891. }
  14892. });
  14893. return percent;
  14894. }
  14895. /**
  14896. * Prevent liveThreshold from causing seeks to seem like they
  14897. * are not happening from a user perspective.
  14898. *
  14899. * @param {number} ct
  14900. * current time to seek to
  14901. */
  14902. userSeek_(ct) {
  14903. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  14904. this.player_.liveTracker.nextSeekedFromUser();
  14905. }
  14906. this.player_.currentTime(ct);
  14907. }
  14908. /**
  14909. * Get the value of current time but allows for smooth scrubbing,
  14910. * when player can't keep up.
  14911. *
  14912. * @return {number}
  14913. * The current time value to display
  14914. *
  14915. * @private
  14916. */
  14917. getCurrentTime_() {
  14918. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  14919. }
  14920. /**
  14921. * Get the percentage of media played so far.
  14922. *
  14923. * @return {number}
  14924. * The percentage of media played so far (0 to 1).
  14925. */
  14926. getPercent() {
  14927. // If we have a pending seek time, we are scrubbing on mobile and should set the slider percent
  14928. // to reflect the current scrub location.
  14929. if (this.pendingSeekTime_) {
  14930. return this.pendingSeekTime_ / this.player_.duration();
  14931. }
  14932. const currentTime = this.getCurrentTime_();
  14933. let percent;
  14934. const liveTracker = this.player_.liveTracker;
  14935. if (liveTracker && liveTracker.isLive()) {
  14936. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  14937. // prevent the percent from changing at the live edge
  14938. if (liveTracker.atLiveEdge()) {
  14939. percent = 1;
  14940. }
  14941. } else {
  14942. percent = currentTime / this.player_.duration();
  14943. }
  14944. return percent;
  14945. }
  14946. /**
  14947. * Handle mouse down on seek bar
  14948. *
  14949. * @param {MouseEvent} event
  14950. * The `mousedown` event that caused this to run.
  14951. *
  14952. * @listens mousedown
  14953. */
  14954. handleMouseDown(event) {
  14955. if (!isSingleLeftClick(event)) {
  14956. return;
  14957. }
  14958. // Stop event propagation to prevent double fire in progress-control.js
  14959. event.stopPropagation();
  14960. this.videoWasPlaying = !this.player_.paused();
  14961. // Don't pause if we are on mobile and `disableSeekWhileScrubbingOnMobile: true`.
  14962. // In that case, playback should continue while the player scrubs to a new location.
  14963. if (!this.shouldDisableSeekWhileScrubbingOnMobile_) {
  14964. this.player_.pause();
  14965. }
  14966. super.handleMouseDown(event);
  14967. }
  14968. /**
  14969. * Handle mouse move on seek bar
  14970. *
  14971. * @param {MouseEvent} event
  14972. * The `mousemove` event that caused this to run.
  14973. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false
  14974. *
  14975. * @listens mousemove
  14976. */
  14977. handleMouseMove(event, mouseDown = false) {
  14978. if (!isSingleLeftClick(event) || isNaN(this.player_.duration())) {
  14979. return;
  14980. }
  14981. if (!mouseDown && !this.player_.scrubbing()) {
  14982. this.player_.scrubbing(true);
  14983. }
  14984. let newTime;
  14985. const distance = this.calculateDistance(event);
  14986. const liveTracker = this.player_.liveTracker;
  14987. if (!liveTracker || !liveTracker.isLive()) {
  14988. newTime = distance * this.player_.duration();
  14989. // Don't let video end while scrubbing.
  14990. if (newTime === this.player_.duration()) {
  14991. newTime = newTime - 0.1;
  14992. }
  14993. } else {
  14994. if (distance >= 0.99) {
  14995. liveTracker.seekToLiveEdge();
  14996. return;
  14997. }
  14998. const seekableStart = liveTracker.seekableStart();
  14999. const seekableEnd = liveTracker.liveCurrentTime();
  15000. newTime = seekableStart + distance * liveTracker.liveWindow();
  15001. // Don't let video end while scrubbing.
  15002. if (newTime >= seekableEnd) {
  15003. newTime = seekableEnd;
  15004. }
  15005. // Compensate for precision differences so that currentTime is not less
  15006. // than seekable start
  15007. if (newTime <= seekableStart) {
  15008. newTime = seekableStart + 0.1;
  15009. }
  15010. // On android seekableEnd can be Infinity sometimes,
  15011. // this will cause newTime to be Infinity, which is
  15012. // not a valid currentTime.
  15013. if (newTime === Infinity) {
  15014. return;
  15015. }
  15016. }
  15017. // if on mobile and `disableSeekWhileScrubbingOnMobile: true`, keep track of the desired seek point but we won't initiate the seek until 'touchend'
  15018. if (this.shouldDisableSeekWhileScrubbingOnMobile_) {
  15019. this.pendingSeekTime_ = newTime;
  15020. } else {
  15021. this.userSeek_(newTime);
  15022. }
  15023. if (this.player_.options_.enableSmoothSeeking) {
  15024. this.update();
  15025. }
  15026. }
  15027. enable() {
  15028. super.enable();
  15029. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  15030. if (!mouseTimeDisplay) {
  15031. return;
  15032. }
  15033. mouseTimeDisplay.show();
  15034. }
  15035. disable() {
  15036. super.disable();
  15037. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  15038. if (!mouseTimeDisplay) {
  15039. return;
  15040. }
  15041. mouseTimeDisplay.hide();
  15042. }
  15043. /**
  15044. * Handle mouse up on seek bar
  15045. *
  15046. * @param {MouseEvent} event
  15047. * The `mouseup` event that caused this to run.
  15048. *
  15049. * @listens mouseup
  15050. */
  15051. handleMouseUp(event) {
  15052. super.handleMouseUp(event);
  15053. // Stop event propagation to prevent double fire in progress-control.js
  15054. if (event) {
  15055. event.stopPropagation();
  15056. }
  15057. this.player_.scrubbing(false);
  15058. // If we have a pending seek time, then we have finished scrubbing on mobile and should initiate a seek.
  15059. if (this.pendingSeekTime_) {
  15060. this.userSeek_(this.pendingSeekTime_);
  15061. this.pendingSeekTime_ = null;
  15062. }
  15063. /**
  15064. * Trigger timeupdate because we're done seeking and the time has changed.
  15065. * This is particularly useful for if the player is paused to time the time displays.
  15066. *
  15067. * @event Tech#timeupdate
  15068. * @type {Event}
  15069. */
  15070. this.player_.trigger({
  15071. type: 'timeupdate',
  15072. target: this,
  15073. manuallyTriggered: true
  15074. });
  15075. if (this.videoWasPlaying) {
  15076. silencePromise(this.player_.play());
  15077. } else {
  15078. // We're done seeking and the time has changed.
  15079. // If the player is paused, make sure we display the correct time on the seek bar.
  15080. this.update_();
  15081. }
  15082. }
  15083. /**
  15084. * Move more quickly fast forward for keyboard-only users
  15085. */
  15086. stepForward() {
  15087. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  15088. }
  15089. /**
  15090. * Move more quickly rewind for keyboard-only users
  15091. */
  15092. stepBack() {
  15093. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  15094. }
  15095. /**
  15096. * Toggles the playback state of the player
  15097. * This gets called when enter or space is used on the seekbar
  15098. *
  15099. * @param {KeyboardEvent} event
  15100. * The `keydown` event that caused this function to be called
  15101. *
  15102. */
  15103. handleAction(event) {
  15104. if (this.player_.paused()) {
  15105. this.player_.play();
  15106. } else {
  15107. this.player_.pause();
  15108. }
  15109. }
  15110. /**
  15111. * Called when this SeekBar has focus and a key gets pressed down.
  15112. * Supports the following keys:
  15113. *
  15114. * Space or Enter key fire a click event
  15115. * Home key moves to start of the timeline
  15116. * End key moves to end of the timeline
  15117. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  15118. * PageDown key moves back a larger step than ArrowDown
  15119. * PageUp key moves forward a large step
  15120. *
  15121. * @param {KeyboardEvent} event
  15122. * The `keydown` event that caused this function to be called.
  15123. *
  15124. * @listens keydown
  15125. */
  15126. handleKeyDown(event) {
  15127. const liveTracker = this.player_.liveTracker;
  15128. if (event.key === ' ' || event.key === 'Enter') {
  15129. event.preventDefault();
  15130. event.stopPropagation();
  15131. this.handleAction(event);
  15132. } else if (event.key === 'Home') {
  15133. event.preventDefault();
  15134. event.stopPropagation();
  15135. this.userSeek_(0);
  15136. } else if (event.key === 'End') {
  15137. event.preventDefault();
  15138. event.stopPropagation();
  15139. if (liveTracker && liveTracker.isLive()) {
  15140. this.userSeek_(liveTracker.liveCurrentTime());
  15141. } else {
  15142. this.userSeek_(this.player_.duration());
  15143. }
  15144. } else if (/^[0-9]$/.test(event.key)) {
  15145. event.preventDefault();
  15146. event.stopPropagation();
  15147. const gotoFraction = parseInt(event.key, 10) * 0.1;
  15148. if (liveTracker && liveTracker.isLive()) {
  15149. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  15150. } else {
  15151. this.userSeek_(this.player_.duration() * gotoFraction);
  15152. }
  15153. } else if (event.key === 'PageDown') {
  15154. event.preventDefault();
  15155. event.stopPropagation();
  15156. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  15157. } else if (event.key === 'PageUp') {
  15158. event.preventDefault();
  15159. event.stopPropagation();
  15160. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  15161. } else {
  15162. // Pass keydown handling up for unsupported keys
  15163. super.handleKeyDown(event);
  15164. }
  15165. }
  15166. dispose() {
  15167. this.disableInterval_();
  15168. this.off(this.player_, ['durationchange', 'timeupdate'], this.update);
  15169. this.off(this.player_, ['ended'], this.update_);
  15170. if (this.player_.liveTracker) {
  15171. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  15172. }
  15173. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  15174. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  15175. // we don't need to update the play progress if the document is hidden,
  15176. // also, this causes the CPU to spike and eventually crash the page on IE11.
  15177. if ('hidden' in document && 'visibilityState' in document) {
  15178. this.off(document, 'visibilitychange', this.toggleVisibility_);
  15179. }
  15180. super.dispose();
  15181. }
  15182. }
  15183. /**
  15184. * Default options for the `SeekBar`
  15185. *
  15186. * @type {Object}
  15187. * @private
  15188. */
  15189. SeekBar.prototype.options_ = {
  15190. children: ['loadProgressBar', 'playProgressBar'],
  15191. barName: 'playProgressBar'
  15192. };
  15193. Component.registerComponent('SeekBar', SeekBar);
  15194. /**
  15195. * @file progress-control.js
  15196. */
  15197. /**
  15198. * The Progress Control component contains the seek bar, load progress,
  15199. * and play progress.
  15200. *
  15201. * @extends Component
  15202. */
  15203. class ProgressControl extends Component {
  15204. /**
  15205. * Creates an instance of this class.
  15206. *
  15207. * @param {Player} player
  15208. * The `Player` that this class should be attached to.
  15209. *
  15210. * @param {Object} [options]
  15211. * The key/value store of player options.
  15212. */
  15213. constructor(player, options) {
  15214. super(player, options);
  15215. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  15216. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  15217. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  15218. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  15219. this.enable();
  15220. }
  15221. /**
  15222. * Create the `Component`'s DOM element
  15223. *
  15224. * @return {Element}
  15225. * The element that was created.
  15226. */
  15227. createEl() {
  15228. return super.createEl('div', {
  15229. className: 'vjs-progress-control vjs-control'
  15230. });
  15231. }
  15232. /**
  15233. * When the mouse moves over the `ProgressControl`, the pointer position
  15234. * gets passed down to the `MouseTimeDisplay` component.
  15235. *
  15236. * @param {Event} event
  15237. * The `mousemove` event that caused this function to run.
  15238. *
  15239. * @listen mousemove
  15240. */
  15241. handleMouseMove(event) {
  15242. const seekBar = this.getChild('seekBar');
  15243. if (!seekBar) {
  15244. return;
  15245. }
  15246. const playProgressBar = seekBar.getChild('playProgressBar');
  15247. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  15248. if (!playProgressBar && !mouseTimeDisplay) {
  15249. return;
  15250. }
  15251. const seekBarEl = seekBar.el();
  15252. const seekBarRect = findPosition(seekBarEl);
  15253. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  15254. // The default skin has a gap on either side of the `SeekBar`. This means
  15255. // that it's possible to trigger this behavior outside the boundaries of
  15256. // the `SeekBar`. This ensures we stay within it at all times.
  15257. seekBarPoint = clamp(seekBarPoint, 0, 1);
  15258. if (mouseTimeDisplay) {
  15259. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  15260. }
  15261. if (playProgressBar) {
  15262. playProgressBar.update(seekBarRect, seekBar.getProgress());
  15263. }
  15264. }
  15265. /**
  15266. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  15267. *
  15268. * @method ProgressControl#throttledHandleMouseSeek
  15269. * @param {Event} event
  15270. * The `mousemove` event that caused this function to run.
  15271. *
  15272. * @listen mousemove
  15273. * @listen touchmove
  15274. */
  15275. /**
  15276. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  15277. *
  15278. * @param {Event} event
  15279. * `mousedown` or `touchstart` event that triggered this function
  15280. *
  15281. * @listens mousemove
  15282. * @listens touchmove
  15283. */
  15284. handleMouseSeek(event) {
  15285. const seekBar = this.getChild('seekBar');
  15286. if (seekBar) {
  15287. seekBar.handleMouseMove(event);
  15288. }
  15289. }
  15290. /**
  15291. * Are controls are currently enabled for this progress control.
  15292. *
  15293. * @return {boolean}
  15294. * true if controls are enabled, false otherwise
  15295. */
  15296. enabled() {
  15297. return this.enabled_;
  15298. }
  15299. /**
  15300. * Disable all controls on the progress control and its children
  15301. */
  15302. disable() {
  15303. this.children().forEach(child => child.disable && child.disable());
  15304. if (!this.enabled()) {
  15305. return;
  15306. }
  15307. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  15308. this.off(this.el_, ['mousemove', 'touchmove'], this.handleMouseMove);
  15309. this.removeListenersAddedOnMousedownAndTouchstart();
  15310. this.addClass('disabled');
  15311. this.enabled_ = false;
  15312. // Restore normal playback state if controls are disabled while scrubbing
  15313. if (this.player_.scrubbing()) {
  15314. const seekBar = this.getChild('seekBar');
  15315. this.player_.scrubbing(false);
  15316. if (seekBar.videoWasPlaying) {
  15317. silencePromise(this.player_.play());
  15318. }
  15319. }
  15320. }
  15321. /**
  15322. * Enable all controls on the progress control and its children
  15323. */
  15324. enable() {
  15325. this.children().forEach(child => child.enable && child.enable());
  15326. if (this.enabled()) {
  15327. return;
  15328. }
  15329. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  15330. this.on(this.el_, ['mousemove', 'touchmove'], this.handleMouseMove);
  15331. this.removeClass('disabled');
  15332. this.enabled_ = true;
  15333. }
  15334. /**
  15335. * Cleanup listeners after the user finishes interacting with the progress controls
  15336. */
  15337. removeListenersAddedOnMousedownAndTouchstart() {
  15338. const doc = this.el_.ownerDocument;
  15339. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  15340. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  15341. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  15342. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  15343. }
  15344. /**
  15345. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  15346. *
  15347. * @param {Event} event
  15348. * `mousedown` or `touchstart` event that triggered this function
  15349. *
  15350. * @listens mousedown
  15351. * @listens touchstart
  15352. */
  15353. handleMouseDown(event) {
  15354. const doc = this.el_.ownerDocument;
  15355. const seekBar = this.getChild('seekBar');
  15356. if (seekBar) {
  15357. seekBar.handleMouseDown(event);
  15358. }
  15359. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  15360. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  15361. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  15362. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  15363. }
  15364. /**
  15365. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  15366. *
  15367. * @param {Event} event
  15368. * `mouseup` or `touchend` event that triggered this function.
  15369. *
  15370. * @listens touchend
  15371. * @listens mouseup
  15372. */
  15373. handleMouseUp(event) {
  15374. const seekBar = this.getChild('seekBar');
  15375. if (seekBar) {
  15376. seekBar.handleMouseUp(event);
  15377. }
  15378. this.removeListenersAddedOnMousedownAndTouchstart();
  15379. }
  15380. }
  15381. /**
  15382. * Default options for `ProgressControl`
  15383. *
  15384. * @type {Object}
  15385. * @private
  15386. */
  15387. ProgressControl.prototype.options_ = {
  15388. children: ['seekBar']
  15389. };
  15390. Component.registerComponent('ProgressControl', ProgressControl);
  15391. /**
  15392. * @file picture-in-picture-toggle.js
  15393. */
  15394. /** @import Player from './player' */
  15395. /**
  15396. * Toggle Picture-in-Picture mode
  15397. *
  15398. * @extends Button
  15399. */
  15400. class PictureInPictureToggle extends Button {
  15401. /**
  15402. * Creates an instance of this class.
  15403. *
  15404. * @param {Player} player
  15405. * The `Player` that this class should be attached to.
  15406. *
  15407. * @param {Object} [options]
  15408. * The key/value store of player options.
  15409. *
  15410. * @listens Player#enterpictureinpicture
  15411. * @listens Player#leavepictureinpicture
  15412. */
  15413. constructor(player, options) {
  15414. super(player, options);
  15415. this.setIcon('picture-in-picture-enter');
  15416. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  15417. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  15418. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => this.handlePictureInPictureAudioModeChange());
  15419. // TODO: Deactivate button on player emptied event.
  15420. this.disable();
  15421. }
  15422. /**
  15423. * Builds the default DOM `className`.
  15424. *
  15425. * @return {string}
  15426. * The DOM `className` for this object.
  15427. */
  15428. buildCSSClass() {
  15429. return `vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`;
  15430. }
  15431. /**
  15432. * Displays or hides the button depending on the audio mode detection.
  15433. * Exits picture-in-picture if it is enabled when switching to audio mode.
  15434. */
  15435. handlePictureInPictureAudioModeChange() {
  15436. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  15437. const isSourceAudio = this.player_.currentType().substring(0, 5) === 'audio';
  15438. const isAudioMode = isSourceAudio || this.player_.audioPosterMode() || this.player_.audioOnlyMode();
  15439. if (!isAudioMode) {
  15440. this.show();
  15441. return;
  15442. }
  15443. if (this.player_.isInPictureInPicture()) {
  15444. this.player_.exitPictureInPicture();
  15445. }
  15446. this.hide();
  15447. }
  15448. /**
  15449. * Enables or disables button based on availability of a Picture-In-Picture mode.
  15450. *
  15451. * Enabled if
  15452. * - `player.options().enableDocumentPictureInPicture` is true and
  15453. * window.documentPictureInPicture is available; or
  15454. * - `player.disablePictureInPicture()` is false and
  15455. * element.requestPictureInPicture is available
  15456. */
  15457. handlePictureInPictureEnabledChange() {
  15458. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window) {
  15459. this.enable();
  15460. } else {
  15461. this.disable();
  15462. }
  15463. }
  15464. /**
  15465. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  15466. *
  15467. * @param {Event} [event]
  15468. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  15469. * called.
  15470. *
  15471. * @listens Player#enterpictureinpicture
  15472. * @listens Player#leavepictureinpicture
  15473. */
  15474. handlePictureInPictureChange(event) {
  15475. if (this.player_.isInPictureInPicture()) {
  15476. this.setIcon('picture-in-picture-exit');
  15477. this.controlText('Exit Picture-in-Picture');
  15478. } else {
  15479. this.setIcon('picture-in-picture-enter');
  15480. this.controlText('Picture-in-Picture');
  15481. }
  15482. this.handlePictureInPictureEnabledChange();
  15483. }
  15484. /**
  15485. * This gets called when an `PictureInPictureToggle` is "clicked". See
  15486. * {@link ClickableComponent} for more detailed information on what a click can be.
  15487. *
  15488. * @param {Event} [event]
  15489. * The `keydown`, `tap`, or `click` event that caused this function to be
  15490. * called.
  15491. *
  15492. * @listens tap
  15493. * @listens click
  15494. */
  15495. handleClick(event) {
  15496. if (!this.player_.isInPictureInPicture()) {
  15497. this.player_.requestPictureInPicture();
  15498. } else {
  15499. this.player_.exitPictureInPicture();
  15500. }
  15501. }
  15502. /**
  15503. * Show the `Component`s element if it is hidden by removing the
  15504. * 'vjs-hidden' class name from it only in browsers that support the Picture-in-Picture API.
  15505. */
  15506. show() {
  15507. // Does not allow to display the pictureInPictureToggle in browsers that do not support the Picture-in-Picture API, e.g. Firefox.
  15508. if (typeof document.exitPictureInPicture !== 'function') {
  15509. return;
  15510. }
  15511. super.show();
  15512. }
  15513. }
  15514. /**
  15515. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  15516. *
  15517. * @type {string}
  15518. * @protected
  15519. */
  15520. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  15521. Component.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  15522. /**
  15523. * @file fullscreen-toggle.js
  15524. */
  15525. /** @import Player from './player' */
  15526. /**
  15527. * Toggle fullscreen video
  15528. *
  15529. * @extends Button
  15530. */
  15531. class FullscreenToggle extends Button {
  15532. /**
  15533. * Creates an instance of this class.
  15534. *
  15535. * @param {Player} player
  15536. * The `Player` that this class should be attached to.
  15537. *
  15538. * @param {Object} [options]
  15539. * The key/value store of player options.
  15540. */
  15541. constructor(player, options) {
  15542. super(player, options);
  15543. this.setIcon('fullscreen-enter');
  15544. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  15545. if (document[player.fsApi_.fullscreenEnabled] === false) {
  15546. this.disable();
  15547. }
  15548. }
  15549. /**
  15550. * Builds the default DOM `className`.
  15551. *
  15552. * @return {string}
  15553. * The DOM `className` for this object.
  15554. */
  15555. buildCSSClass() {
  15556. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  15557. }
  15558. /**
  15559. * Handles fullscreenchange on the player and change control text accordingly.
  15560. *
  15561. * @param {Event} [event]
  15562. * The {@link Player#fullscreenchange} event that caused this function to be
  15563. * called.
  15564. *
  15565. * @listens Player#fullscreenchange
  15566. */
  15567. handleFullscreenChange(event) {
  15568. if (this.player_.isFullscreen()) {
  15569. this.controlText('Exit Fullscreen');
  15570. this.setIcon('fullscreen-exit');
  15571. } else {
  15572. this.controlText('Fullscreen');
  15573. this.setIcon('fullscreen-enter');
  15574. }
  15575. }
  15576. /**
  15577. * This gets called when an `FullscreenToggle` is "clicked". See
  15578. * {@link ClickableComponent} for more detailed information on what a click can be.
  15579. *
  15580. * @param {Event} [event]
  15581. * The `keydown`, `tap`, or `click` event that caused this function to be
  15582. * called.
  15583. *
  15584. * @listens tap
  15585. * @listens click
  15586. */
  15587. handleClick(event) {
  15588. if (!this.player_.isFullscreen()) {
  15589. this.player_.requestFullscreen();
  15590. } else {
  15591. this.player_.exitFullscreen();
  15592. }
  15593. }
  15594. }
  15595. /**
  15596. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  15597. *
  15598. * @type {string}
  15599. * @protected
  15600. */
  15601. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  15602. Component.registerComponent('FullscreenToggle', FullscreenToggle);
  15603. /** @import Component from '../../component' */
  15604. /** @import Player from '../../player' */
  15605. /**
  15606. * Check if volume control is supported and if it isn't hide the
  15607. * `Component` that was passed using the `vjs-hidden` class.
  15608. *
  15609. * @param {Component} self
  15610. * The component that should be hidden if volume is unsupported
  15611. *
  15612. * @param {Player} player
  15613. * A reference to the player
  15614. *
  15615. * @private
  15616. */
  15617. const checkVolumeSupport = function (self, player) {
  15618. // hide volume controls when they're not supported by the current tech
  15619. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  15620. self.addClass('vjs-hidden');
  15621. }
  15622. self.on(player, 'loadstart', function () {
  15623. if (!player.tech_.featuresVolumeControl) {
  15624. self.addClass('vjs-hidden');
  15625. } else {
  15626. self.removeClass('vjs-hidden');
  15627. }
  15628. });
  15629. };
  15630. /**
  15631. * @file volume-level.js
  15632. */
  15633. /**
  15634. * Shows volume level
  15635. *
  15636. * @extends Component
  15637. */
  15638. class VolumeLevel extends Component {
  15639. /**
  15640. * Create the `Component`'s DOM element
  15641. *
  15642. * @return {Element}
  15643. * The element that was created.
  15644. */
  15645. createEl() {
  15646. const el = super.createEl('div', {
  15647. className: 'vjs-volume-level'
  15648. });
  15649. this.setIcon('circle', el);
  15650. el.appendChild(super.createEl('span', {
  15651. className: 'vjs-control-text'
  15652. }));
  15653. return el;
  15654. }
  15655. }
  15656. Component.registerComponent('VolumeLevel', VolumeLevel);
  15657. /**
  15658. * @file volume-level-tooltip.js
  15659. */
  15660. /** @import Player from '../../player' */
  15661. /**
  15662. * Volume level tooltips display a volume above or side by side the volume bar.
  15663. *
  15664. * @extends Component
  15665. */
  15666. class VolumeLevelTooltip extends Component {
  15667. /**
  15668. * Creates an instance of this class.
  15669. *
  15670. * @param {Player} player
  15671. * The {@link Player} that this class should be attached to.
  15672. *
  15673. * @param {Object} [options]
  15674. * The key/value store of player options.
  15675. */
  15676. constructor(player, options) {
  15677. super(player, options);
  15678. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  15679. }
  15680. /**
  15681. * Create the volume tooltip DOM element
  15682. *
  15683. * @return {Element}
  15684. * The element that was created.
  15685. */
  15686. createEl() {
  15687. return super.createEl('div', {
  15688. className: 'vjs-volume-tooltip'
  15689. }, {
  15690. 'aria-hidden': 'true'
  15691. });
  15692. }
  15693. /**
  15694. * Updates the position of the tooltip relative to the `VolumeBar` and
  15695. * its content text.
  15696. *
  15697. * @param {Object} rangeBarRect
  15698. * The `ClientRect` for the {@link VolumeBar} element.
  15699. *
  15700. * @param {number} rangeBarPoint
  15701. * A number from 0 to 1, representing a horizontal/vertical reference point
  15702. * from the left edge of the {@link VolumeBar}
  15703. *
  15704. * @param {boolean} vertical
  15705. * Referees to the Volume control position
  15706. * in the control bar{@link VolumeControl}
  15707. *
  15708. */
  15709. update(rangeBarRect, rangeBarPoint, vertical, content) {
  15710. if (!vertical) {
  15711. const tooltipRect = getBoundingClientRect(this.el_);
  15712. const playerRect = getBoundingClientRect(this.player_.el());
  15713. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  15714. if (!playerRect || !tooltipRect) {
  15715. return;
  15716. }
  15717. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  15718. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  15719. let pullTooltipBy = tooltipRect.width / 2;
  15720. if (spaceLeftOfPoint < pullTooltipBy) {
  15721. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  15722. } else if (spaceRightOfPoint < pullTooltipBy) {
  15723. pullTooltipBy = spaceRightOfPoint;
  15724. }
  15725. if (pullTooltipBy < 0) {
  15726. pullTooltipBy = 0;
  15727. } else if (pullTooltipBy > tooltipRect.width) {
  15728. pullTooltipBy = tooltipRect.width;
  15729. }
  15730. this.el_.style.right = `-${pullTooltipBy}px`;
  15731. }
  15732. this.write(`${content}%`);
  15733. }
  15734. /**
  15735. * Write the volume to the tooltip DOM element.
  15736. *
  15737. * @param {string} content
  15738. * The formatted volume for the tooltip.
  15739. */
  15740. write(content) {
  15741. textContent(this.el_, content);
  15742. }
  15743. /**
  15744. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  15745. *
  15746. * @param {Object} rangeBarRect
  15747. * The `ClientRect` for the {@link VolumeBar} element.
  15748. *
  15749. * @param {number} rangeBarPoint
  15750. * A number from 0 to 1, representing a horizontal/vertical reference point
  15751. * from the left edge of the {@link VolumeBar}
  15752. *
  15753. * @param {boolean} vertical
  15754. * Referees to the Volume control position
  15755. * in the control bar{@link VolumeControl}
  15756. *
  15757. * @param {number} volume
  15758. * The volume level to update the tooltip to
  15759. *
  15760. * @param {Function} cb
  15761. * A function that will be called during the request animation frame
  15762. * for tooltips that need to do additional animations from the default
  15763. */
  15764. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  15765. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  15766. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  15767. if (cb) {
  15768. cb();
  15769. }
  15770. });
  15771. }
  15772. }
  15773. Component.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  15774. /**
  15775. * @file mouse-volume-level-display.js
  15776. */
  15777. /**
  15778. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  15779. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  15780. * indicating the volume level which is represented by a given point in the
  15781. * {@link VolumeBar}.
  15782. *
  15783. * @extends Component
  15784. */
  15785. class MouseVolumeLevelDisplay extends Component {
  15786. /**
  15787. * Creates an instance of this class.
  15788. *
  15789. * @param {Player} player
  15790. * The {@link Player} that this class should be attached to.
  15791. *
  15792. * @param {Object} [options]
  15793. * The key/value store of player options.
  15794. */
  15795. constructor(player, options) {
  15796. super(player, options);
  15797. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  15798. }
  15799. /**
  15800. * Create the DOM element for this class.
  15801. *
  15802. * @return {Element}
  15803. * The element that was created.
  15804. */
  15805. createEl() {
  15806. return super.createEl('div', {
  15807. className: 'vjs-mouse-display'
  15808. });
  15809. }
  15810. /**
  15811. * Enquires updates to its own DOM as well as the DOM of its
  15812. * {@link VolumeLevelTooltip} child.
  15813. *
  15814. * @param {Object} rangeBarRect
  15815. * The `ClientRect` for the {@link VolumeBar} element.
  15816. *
  15817. * @param {number} rangeBarPoint
  15818. * A number from 0 to 1, representing a horizontal/vertical reference point
  15819. * from the left edge of the {@link VolumeBar}
  15820. *
  15821. * @param {boolean} vertical
  15822. * Referees to the Volume control position
  15823. * in the control bar{@link VolumeControl}
  15824. *
  15825. */
  15826. update(rangeBarRect, rangeBarPoint, vertical) {
  15827. const volume = 100 * rangeBarPoint;
  15828. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  15829. if (vertical) {
  15830. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  15831. } else {
  15832. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  15833. }
  15834. });
  15835. }
  15836. }
  15837. /**
  15838. * Default options for `MouseVolumeLevelDisplay`
  15839. *
  15840. * @type {Object}
  15841. * @private
  15842. */
  15843. MouseVolumeLevelDisplay.prototype.options_ = {
  15844. children: ['volumeLevelTooltip']
  15845. };
  15846. Component.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  15847. /**
  15848. * @file volume-bar.js
  15849. */
  15850. /**
  15851. * The bar that contains the volume level and can be clicked on to adjust the level
  15852. *
  15853. * @extends Slider
  15854. */
  15855. class VolumeBar extends Slider {
  15856. /**
  15857. * Creates an instance of this class.
  15858. *
  15859. * @param {Player} player
  15860. * The `Player` that this class should be attached to.
  15861. *
  15862. * @param {Object} [options]
  15863. * The key/value store of player options.
  15864. */
  15865. constructor(player, options) {
  15866. super(player, options);
  15867. this.on('slideractive', e => this.updateLastVolume_(e));
  15868. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  15869. player.ready(() => this.updateARIAAttributes());
  15870. }
  15871. /**
  15872. * Create the `Component`'s DOM element
  15873. *
  15874. * @return {Element}
  15875. * The element that was created.
  15876. */
  15877. createEl() {
  15878. return super.createEl('div', {
  15879. className: 'vjs-volume-bar vjs-slider-bar'
  15880. }, {
  15881. 'aria-label': this.localize('Volume Level'),
  15882. 'aria-live': 'polite'
  15883. });
  15884. }
  15885. /**
  15886. * Handle mouse down on volume bar
  15887. *
  15888. * @param {Event} event
  15889. * The `mousedown` event that caused this to run.
  15890. *
  15891. * @listens mousedown
  15892. */
  15893. handleMouseDown(event) {
  15894. if (!isSingleLeftClick(event)) {
  15895. return;
  15896. }
  15897. super.handleMouseDown(event);
  15898. }
  15899. /**
  15900. * Handle movement events on the {@link VolumeMenuButton}.
  15901. *
  15902. * @param {Event} event
  15903. * The event that caused this function to run.
  15904. *
  15905. * @listens mousemove
  15906. */
  15907. handleMouseMove(event) {
  15908. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  15909. if (mouseVolumeLevelDisplay) {
  15910. const volumeBarEl = this.el();
  15911. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  15912. const vertical = this.vertical();
  15913. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  15914. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  15915. // The default skin has a gap on either side of the `VolumeBar`. This means
  15916. // that it's possible to trigger this behavior outside the boundaries of
  15917. // the `VolumeBar`. This ensures we stay within it at all times.
  15918. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  15919. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  15920. }
  15921. if (!isSingleLeftClick(event)) {
  15922. return;
  15923. }
  15924. this.checkMuted();
  15925. this.player_.volume(this.calculateDistance(event));
  15926. }
  15927. /**
  15928. * If the player is muted unmute it.
  15929. */
  15930. checkMuted() {
  15931. if (this.player_.muted()) {
  15932. this.player_.muted(false);
  15933. }
  15934. }
  15935. /**
  15936. * Get percent of volume level
  15937. *
  15938. * @return {number}
  15939. * Volume level percent as a decimal number.
  15940. */
  15941. getPercent() {
  15942. if (this.player_.muted()) {
  15943. return 0;
  15944. }
  15945. return this.player_.volume();
  15946. }
  15947. /**
  15948. * Increase volume level for keyboard users
  15949. */
  15950. stepForward() {
  15951. this.checkMuted();
  15952. this.player_.volume(this.player_.volume() + 0.1);
  15953. }
  15954. /**
  15955. * Decrease volume level for keyboard users
  15956. */
  15957. stepBack() {
  15958. this.checkMuted();
  15959. this.player_.volume(this.player_.volume() - 0.1);
  15960. }
  15961. /**
  15962. * Update ARIA accessibility attributes
  15963. *
  15964. * @param {Event} [event]
  15965. * The `volumechange` event that caused this function to run.
  15966. *
  15967. * @listens Player#volumechange
  15968. */
  15969. updateARIAAttributes(event) {
  15970. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  15971. this.el_.setAttribute('aria-valuenow', ariaValue);
  15972. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  15973. }
  15974. /**
  15975. * Returns the current value of the player volume as a percentage
  15976. *
  15977. * @private
  15978. */
  15979. volumeAsPercentage_() {
  15980. return Math.round(this.player_.volume() * 100);
  15981. }
  15982. /**
  15983. * When user starts dragging the VolumeBar, store the volume and listen for
  15984. * the end of the drag. When the drag ends, if the volume was set to zero,
  15985. * set lastVolume to the stored volume.
  15986. *
  15987. * @listens slideractive
  15988. * @private
  15989. */
  15990. updateLastVolume_() {
  15991. const volumeBeforeDrag = this.player_.volume();
  15992. this.one('sliderinactive', () => {
  15993. if (this.player_.volume() === 0) {
  15994. this.player_.lastVolume_(volumeBeforeDrag);
  15995. }
  15996. });
  15997. }
  15998. }
  15999. /**
  16000. * Default options for the `VolumeBar`
  16001. *
  16002. * @type {Object}
  16003. * @private
  16004. */
  16005. VolumeBar.prototype.options_ = {
  16006. children: ['volumeLevel'],
  16007. barName: 'volumeLevel'
  16008. };
  16009. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  16010. if (!IS_IOS && !IS_ANDROID) {
  16011. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  16012. }
  16013. /**
  16014. * Call the update event for this Slider when this event happens on the player.
  16015. *
  16016. * @type {string}
  16017. */
  16018. VolumeBar.prototype.playerEvent = 'volumechange';
  16019. Component.registerComponent('VolumeBar', VolumeBar);
  16020. /**
  16021. * @file volume-control.js
  16022. */
  16023. /**
  16024. * The component for controlling the volume level
  16025. *
  16026. * @extends Component
  16027. */
  16028. class VolumeControl extends Component {
  16029. /**
  16030. * Creates an instance of this class.
  16031. *
  16032. * @param {Player} player
  16033. * The `Player` that this class should be attached to.
  16034. *
  16035. * @param {Object} [options={}]
  16036. * The key/value store of player options.
  16037. */
  16038. constructor(player, options = {}) {
  16039. options.vertical = options.vertical || false;
  16040. // Pass the vertical option down to the VolumeBar if
  16041. // the VolumeBar is turned on.
  16042. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  16043. options.volumeBar = options.volumeBar || {};
  16044. options.volumeBar.vertical = options.vertical;
  16045. }
  16046. super(player, options);
  16047. // hide this control if volume support is missing
  16048. checkVolumeSupport(this, player);
  16049. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  16050. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  16051. this.on('mousedown', e => this.handleMouseDown(e));
  16052. this.on('touchstart', e => this.handleMouseDown(e));
  16053. this.on('mousemove', e => this.handleMouseMove(e));
  16054. // while the slider is active (the mouse has been pressed down and
  16055. // is dragging) or in focus we do not want to hide the VolumeBar
  16056. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  16057. this.volumeBar.addClass('vjs-slider-active');
  16058. this.addClass('vjs-slider-active');
  16059. this.trigger('slideractive');
  16060. });
  16061. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  16062. this.volumeBar.removeClass('vjs-slider-active');
  16063. this.removeClass('vjs-slider-active');
  16064. this.trigger('sliderinactive');
  16065. });
  16066. }
  16067. /**
  16068. * Create the `Component`'s DOM element
  16069. *
  16070. * @return {Element}
  16071. * The element that was created.
  16072. */
  16073. createEl() {
  16074. let orientationClass = 'vjs-volume-horizontal';
  16075. if (this.options_.vertical) {
  16076. orientationClass = 'vjs-volume-vertical';
  16077. }
  16078. return super.createEl('div', {
  16079. className: `vjs-volume-control vjs-control ${orientationClass}`
  16080. });
  16081. }
  16082. /**
  16083. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  16084. *
  16085. * @param {Event} event
  16086. * `mousedown` or `touchstart` event that triggered this function
  16087. *
  16088. * @listens mousedown
  16089. * @listens touchstart
  16090. */
  16091. handleMouseDown(event) {
  16092. const doc = this.el_.ownerDocument;
  16093. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  16094. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  16095. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  16096. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  16097. }
  16098. /**
  16099. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  16100. *
  16101. * @param {Event} event
  16102. * `mouseup` or `touchend` event that triggered this function.
  16103. *
  16104. * @listens touchend
  16105. * @listens mouseup
  16106. */
  16107. handleMouseUp(event) {
  16108. const doc = this.el_.ownerDocument;
  16109. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  16110. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  16111. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  16112. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  16113. }
  16114. /**
  16115. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  16116. *
  16117. * @param {Event} event
  16118. * `mousedown` or `touchstart` event that triggered this function
  16119. *
  16120. * @listens mousedown
  16121. * @listens touchstart
  16122. */
  16123. handleMouseMove(event) {
  16124. this.volumeBar.handleMouseMove(event);
  16125. }
  16126. }
  16127. /**
  16128. * Default options for the `VolumeControl`
  16129. *
  16130. * @type {Object}
  16131. * @private
  16132. */
  16133. VolumeControl.prototype.options_ = {
  16134. children: ['volumeBar']
  16135. };
  16136. Component.registerComponent('VolumeControl', VolumeControl);
  16137. /** @import Component from '../../component' */
  16138. /** @import Player from '../../player' */
  16139. /**
  16140. * Check if muting volume is supported and if it isn't hide the mute toggle
  16141. * button.
  16142. *
  16143. * @param {Component} self
  16144. * A reference to the mute toggle button
  16145. *
  16146. * @param {Player} player
  16147. * A reference to the player
  16148. *
  16149. * @private
  16150. */
  16151. const checkMuteSupport = function (self, player) {
  16152. // hide mute toggle button if it's not supported by the current tech
  16153. if (player.tech_ && !player.tech_.featuresMuteControl) {
  16154. self.addClass('vjs-hidden');
  16155. }
  16156. self.on(player, 'loadstart', function () {
  16157. if (!player.tech_.featuresMuteControl) {
  16158. self.addClass('vjs-hidden');
  16159. } else {
  16160. self.removeClass('vjs-hidden');
  16161. }
  16162. });
  16163. };
  16164. /**
  16165. * @file mute-toggle.js
  16166. */
  16167. /** @import Player from './player' */
  16168. /**
  16169. * A button component for muting the audio.
  16170. *
  16171. * @extends Button
  16172. */
  16173. class MuteToggle extends Button {
  16174. /**
  16175. * Creates an instance of this class.
  16176. *
  16177. * @param {Player} player
  16178. * The `Player` that this class should be attached to.
  16179. *
  16180. * @param {Object} [options]
  16181. * The key/value store of player options.
  16182. */
  16183. constructor(player, options) {
  16184. super(player, options);
  16185. // hide this control if volume support is missing
  16186. checkMuteSupport(this, player);
  16187. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  16188. }
  16189. /**
  16190. * Builds the default DOM `className`.
  16191. *
  16192. * @return {string}
  16193. * The DOM `className` for this object.
  16194. */
  16195. buildCSSClass() {
  16196. return `vjs-mute-control ${super.buildCSSClass()}`;
  16197. }
  16198. /**
  16199. * This gets called when an `MuteToggle` is "clicked". See
  16200. * {@link ClickableComponent} for more detailed information on what a click can be.
  16201. *
  16202. * @param {Event} [event]
  16203. * The `keydown`, `tap`, or `click` event that caused this function to be
  16204. * called.
  16205. *
  16206. * @listens tap
  16207. * @listens click
  16208. */
  16209. handleClick(event) {
  16210. const vol = this.player_.volume();
  16211. const lastVolume = this.player_.lastVolume_();
  16212. if (vol === 0) {
  16213. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  16214. this.player_.volume(volumeToSet);
  16215. this.player_.muted(false);
  16216. } else {
  16217. this.player_.muted(this.player_.muted() ? false : true);
  16218. }
  16219. }
  16220. /**
  16221. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  16222. * on the player.
  16223. *
  16224. * @param {Event} [event]
  16225. * The {@link Player#loadstart} event if this function was called
  16226. * through an event.
  16227. *
  16228. * @listens Player#loadstart
  16229. * @listens Player#volumechange
  16230. */
  16231. update(event) {
  16232. this.updateIcon_();
  16233. this.updateControlText_();
  16234. }
  16235. /**
  16236. * Update the appearance of the `MuteToggle` icon.
  16237. *
  16238. * Possible states (given `level` variable below):
  16239. * - 0: crossed out
  16240. * - 1: zero bars of volume
  16241. * - 2: one bar of volume
  16242. * - 3: two bars of volume
  16243. *
  16244. * @private
  16245. */
  16246. updateIcon_() {
  16247. const vol = this.player_.volume();
  16248. let level = 3;
  16249. this.setIcon('volume-high');
  16250. // in iOS when a player is loaded with muted attribute
  16251. // and volume is changed with a native mute button
  16252. // we want to make sure muted state is updated
  16253. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  16254. this.player_.muted(this.player_.tech_.el_.muted);
  16255. }
  16256. if (vol === 0 || this.player_.muted()) {
  16257. this.setIcon('volume-mute');
  16258. level = 0;
  16259. } else if (vol < 0.33) {
  16260. this.setIcon('volume-low');
  16261. level = 1;
  16262. } else if (vol < 0.67) {
  16263. this.setIcon('volume-medium');
  16264. level = 2;
  16265. }
  16266. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  16267. addClass(this.el_, `vjs-vol-${level}`);
  16268. }
  16269. /**
  16270. * If `muted` has changed on the player, update the control text
  16271. * (`title` attribute on `vjs-mute-control` element and content of
  16272. * `vjs-control-text` element).
  16273. *
  16274. * @private
  16275. */
  16276. updateControlText_() {
  16277. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  16278. const text = soundOff ? 'Unmute' : 'Mute';
  16279. if (this.controlText() !== text) {
  16280. this.controlText(text);
  16281. }
  16282. }
  16283. }
  16284. /**
  16285. * The text that should display over the `MuteToggle`s controls. Added for localization.
  16286. *
  16287. * @type {string}
  16288. * @protected
  16289. */
  16290. MuteToggle.prototype.controlText_ = 'Mute';
  16291. Component.registerComponent('MuteToggle', MuteToggle);
  16292. /**
  16293. * @file volume-control.js
  16294. */
  16295. /**
  16296. * A Component to contain the MuteToggle and VolumeControl so that
  16297. * they can work together.
  16298. *
  16299. * @extends Component
  16300. */
  16301. class VolumePanel extends Component {
  16302. /**
  16303. * Creates an instance of this class.
  16304. *
  16305. * @param {Player} player
  16306. * The `Player` that this class should be attached to.
  16307. *
  16308. * @param {Object} [options={}]
  16309. * The key/value store of player options.
  16310. */
  16311. constructor(player, options = {}) {
  16312. if (typeof options.inline !== 'undefined') {
  16313. options.inline = options.inline;
  16314. } else {
  16315. options.inline = true;
  16316. }
  16317. // pass the inline option down to the VolumeControl as vertical if
  16318. // the VolumeControl is on.
  16319. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  16320. options.volumeControl = options.volumeControl || {};
  16321. options.volumeControl.vertical = !options.inline;
  16322. }
  16323. super(player, options);
  16324. // this handler is used by mouse handler methods below
  16325. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  16326. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  16327. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  16328. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  16329. this.on('keydown', e => this.handleKeyPress(e));
  16330. this.on('mouseover', e => this.handleMouseOver(e));
  16331. this.on('mouseout', e => this.handleMouseOut(e));
  16332. // while the slider is active (the mouse has been pressed down and
  16333. // is dragging) we do not want to hide the VolumeBar
  16334. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  16335. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  16336. }
  16337. /**
  16338. * Add vjs-slider-active class to the VolumePanel
  16339. *
  16340. * @listens VolumeControl#slideractive
  16341. * @private
  16342. */
  16343. sliderActive_() {
  16344. this.addClass('vjs-slider-active');
  16345. }
  16346. /**
  16347. * Removes vjs-slider-active class to the VolumePanel
  16348. *
  16349. * @listens VolumeControl#sliderinactive
  16350. * @private
  16351. */
  16352. sliderInactive_() {
  16353. this.removeClass('vjs-slider-active');
  16354. }
  16355. /**
  16356. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  16357. * depending on MuteToggle and VolumeControl state
  16358. *
  16359. * @listens Player#loadstart
  16360. * @private
  16361. */
  16362. volumePanelState_() {
  16363. // hide volume panel if neither volume control or mute toggle
  16364. // are displayed
  16365. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  16366. this.addClass('vjs-hidden');
  16367. }
  16368. // if only mute toggle is visible we don't want
  16369. // volume panel expanding when hovered or active
  16370. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  16371. this.addClass('vjs-mute-toggle-only');
  16372. }
  16373. }
  16374. /**
  16375. * Create the `Component`'s DOM element
  16376. *
  16377. * @return {Element}
  16378. * The element that was created.
  16379. */
  16380. createEl() {
  16381. let orientationClass = 'vjs-volume-panel-horizontal';
  16382. if (!this.options_.inline) {
  16383. orientationClass = 'vjs-volume-panel-vertical';
  16384. }
  16385. return super.createEl('div', {
  16386. className: `vjs-volume-panel vjs-control ${orientationClass}`
  16387. });
  16388. }
  16389. /**
  16390. * Dispose of the `volume-panel` and all child components.
  16391. */
  16392. dispose() {
  16393. this.handleMouseOut();
  16394. super.dispose();
  16395. }
  16396. /**
  16397. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  16398. * the volume panel and sets focus on `MuteToggle`.
  16399. *
  16400. * @param {Event} event
  16401. * The `keyup` event that caused this function to be called.
  16402. *
  16403. * @listens keyup
  16404. */
  16405. handleVolumeControlKeyUp(event) {
  16406. if (event.key === 'Escape') {
  16407. this.muteToggle.focus();
  16408. }
  16409. }
  16410. /**
  16411. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  16412. * Turns on listening for `mouseover` event. When they happen it
  16413. * calls `this.handleMouseOver`.
  16414. *
  16415. * @param {Event} event
  16416. * The `mouseover` event that caused this function to be called.
  16417. *
  16418. * @listens mouseover
  16419. */
  16420. handleMouseOver(event) {
  16421. this.addClass('vjs-hover');
  16422. on(document, 'keyup', this.handleKeyPressHandler_);
  16423. }
  16424. /**
  16425. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  16426. * Turns on listening for `mouseout` event. When they happen it
  16427. * calls `this.handleMouseOut`.
  16428. *
  16429. * @param {Event} event
  16430. * The `mouseout` event that caused this function to be called.
  16431. *
  16432. * @listens mouseout
  16433. */
  16434. handleMouseOut(event) {
  16435. this.removeClass('vjs-hover');
  16436. off(document, 'keyup', this.handleKeyPressHandler_);
  16437. }
  16438. /**
  16439. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  16440. * looking for ESC, which hides the `VolumeControl`.
  16441. *
  16442. * @param {Event} event
  16443. * The keypress that triggered this event.
  16444. *
  16445. * @listens keydown | keyup
  16446. */
  16447. handleKeyPress(event) {
  16448. if (event.key === 'Escape') {
  16449. this.handleMouseOut();
  16450. }
  16451. }
  16452. }
  16453. /**
  16454. * Default options for the `VolumeControl`
  16455. *
  16456. * @type {Object}
  16457. * @private
  16458. */
  16459. VolumePanel.prototype.options_ = {
  16460. children: ['muteToggle', 'volumeControl']
  16461. };
  16462. Component.registerComponent('VolumePanel', VolumePanel);
  16463. /**
  16464. * Button to skip forward a configurable amount of time
  16465. * through a video. Renders in the control bar.
  16466. *
  16467. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  16468. *
  16469. * @extends Button
  16470. */
  16471. class SkipForward extends Button {
  16472. constructor(player, options) {
  16473. super(player, options);
  16474. this.validOptions = [5, 10, 30];
  16475. this.skipTime = this.getSkipForwardTime();
  16476. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  16477. this.setIcon(`forward-${this.skipTime}`);
  16478. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime.toLocaleString(player.language())]));
  16479. this.show();
  16480. } else {
  16481. this.hide();
  16482. }
  16483. }
  16484. getSkipForwardTime() {
  16485. const playerOptions = this.options_.playerOptions;
  16486. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  16487. }
  16488. buildCSSClass() {
  16489. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  16490. }
  16491. /**
  16492. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  16493. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  16494. * skips to end of duration/seekable range.
  16495. *
  16496. * Handle a click on a `SkipForward` button
  16497. *
  16498. * @param {EventTarget~Event} event
  16499. * The `click` event that caused this function
  16500. * to be called
  16501. */
  16502. handleClick(event) {
  16503. if (isNaN(this.player_.duration())) {
  16504. return;
  16505. }
  16506. const currentVideoTime = this.player_.currentTime();
  16507. const liveTracker = this.player_.liveTracker;
  16508. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  16509. let newTime;
  16510. if (currentVideoTime + this.skipTime <= duration) {
  16511. newTime = currentVideoTime + this.skipTime;
  16512. } else {
  16513. newTime = duration;
  16514. }
  16515. this.player_.currentTime(newTime);
  16516. }
  16517. /**
  16518. * Update control text on languagechange
  16519. */
  16520. handleLanguagechange() {
  16521. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  16522. }
  16523. }
  16524. SkipForward.prototype.controlText_ = 'Skip Forward';
  16525. Component.registerComponent('SkipForward', SkipForward);
  16526. /**
  16527. * Button to skip backward a configurable amount of time
  16528. * through a video. Renders in the control bar.
  16529. *
  16530. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  16531. *
  16532. * @extends Button
  16533. */
  16534. class SkipBackward extends Button {
  16535. constructor(player, options) {
  16536. super(player, options);
  16537. this.validOptions = [5, 10, 30];
  16538. this.skipTime = this.getSkipBackwardTime();
  16539. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  16540. this.setIcon(`replay-${this.skipTime}`);
  16541. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime.toLocaleString(player.language())]));
  16542. this.show();
  16543. } else {
  16544. this.hide();
  16545. }
  16546. }
  16547. getSkipBackwardTime() {
  16548. const playerOptions = this.options_.playerOptions;
  16549. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  16550. }
  16551. buildCSSClass() {
  16552. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  16553. }
  16554. /**
  16555. * On click, skips backward in the video by a configurable amount of seconds.
  16556. * If the current time in the video is less than the configured 'skip backward' time,
  16557. * skips to beginning of video or seekable range.
  16558. *
  16559. * Handle a click on a `SkipBackward` button
  16560. *
  16561. * @param {EventTarget~Event} event
  16562. * The `click` event that caused this function
  16563. * to be called
  16564. */
  16565. handleClick(event) {
  16566. const currentVideoTime = this.player_.currentTime();
  16567. const liveTracker = this.player_.liveTracker;
  16568. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  16569. let newTime;
  16570. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  16571. newTime = seekableStart;
  16572. } else if (currentVideoTime >= this.skipTime) {
  16573. newTime = currentVideoTime - this.skipTime;
  16574. } else {
  16575. newTime = 0;
  16576. }
  16577. this.player_.currentTime(newTime);
  16578. }
  16579. /**
  16580. * Update control text on languagechange
  16581. */
  16582. handleLanguagechange() {
  16583. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  16584. }
  16585. }
  16586. SkipBackward.prototype.controlText_ = 'Skip Backward';
  16587. Component.registerComponent('SkipBackward', SkipBackward);
  16588. /**
  16589. * @file menu.js
  16590. */
  16591. /** @import Player from '../player' */
  16592. /**
  16593. * The Menu component is used to build popup menus, including subtitle and
  16594. * captions selection menus.
  16595. *
  16596. * @extends Component
  16597. */
  16598. class Menu extends Component {
  16599. /**
  16600. * Create an instance of this class.
  16601. *
  16602. * @param {Player} player
  16603. * the player that this component should attach to
  16604. *
  16605. * @param {Object} [options]
  16606. * Object of option names and values
  16607. *
  16608. */
  16609. constructor(player, options) {
  16610. super(player, options);
  16611. if (options) {
  16612. this.menuButton_ = options.menuButton;
  16613. }
  16614. this.focusedChild_ = -1;
  16615. this.on('keydown', e => this.handleKeyDown(e));
  16616. // All the menu item instances share the same blur handler provided by the menu container.
  16617. this.boundHandleBlur_ = e => this.handleBlur(e);
  16618. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  16619. }
  16620. /**
  16621. * Add event listeners to the {@link MenuItem}.
  16622. *
  16623. * @param {Object} component
  16624. * The instance of the `MenuItem` to add listeners to.
  16625. *
  16626. */
  16627. addEventListenerForItem(component) {
  16628. if (!(component instanceof Component)) {
  16629. return;
  16630. }
  16631. this.on(component, 'blur', this.boundHandleBlur_);
  16632. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  16633. }
  16634. /**
  16635. * Remove event listeners from the {@link MenuItem}.
  16636. *
  16637. * @param {Object} component
  16638. * The instance of the `MenuItem` to remove listeners.
  16639. *
  16640. */
  16641. removeEventListenerForItem(component) {
  16642. if (!(component instanceof Component)) {
  16643. return;
  16644. }
  16645. this.off(component, 'blur', this.boundHandleBlur_);
  16646. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  16647. }
  16648. /**
  16649. * This method will be called indirectly when the component has been added
  16650. * before the component adds to the new menu instance by `addItem`.
  16651. * In this case, the original menu instance will remove the component
  16652. * by calling `removeChild`.
  16653. *
  16654. * @param {Object} component
  16655. * The instance of the `MenuItem`
  16656. */
  16657. removeChild(component) {
  16658. if (typeof component === 'string') {
  16659. component = this.getChild(component);
  16660. }
  16661. this.removeEventListenerForItem(component);
  16662. super.removeChild(component);
  16663. }
  16664. /**
  16665. * Add a {@link MenuItem} to the menu.
  16666. *
  16667. * @param {Object|string} component
  16668. * The name or instance of the `MenuItem` to add.
  16669. *
  16670. */
  16671. addItem(component) {
  16672. const childComponent = this.addChild(component);
  16673. if (childComponent) {
  16674. this.addEventListenerForItem(childComponent);
  16675. }
  16676. }
  16677. /**
  16678. * Create the `Menu`s DOM element.
  16679. *
  16680. * @return {Element}
  16681. * the element that was created
  16682. */
  16683. createEl() {
  16684. const contentElType = this.options_.contentElType || 'ul';
  16685. this.contentEl_ = createEl(contentElType, {
  16686. className: 'vjs-menu-content'
  16687. });
  16688. this.contentEl_.setAttribute('role', 'menu');
  16689. const el = super.createEl('div', {
  16690. append: this.contentEl_,
  16691. className: 'vjs-menu'
  16692. });
  16693. el.appendChild(this.contentEl_);
  16694. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  16695. // where a click on the parent is significant
  16696. on(el, 'click', function (event) {
  16697. event.preventDefault();
  16698. event.stopImmediatePropagation();
  16699. });
  16700. return el;
  16701. }
  16702. dispose() {
  16703. this.contentEl_ = null;
  16704. this.boundHandleBlur_ = null;
  16705. this.boundHandleTapClick_ = null;
  16706. super.dispose();
  16707. }
  16708. /**
  16709. * Called when a `MenuItem` loses focus.
  16710. *
  16711. * @param {Event} event
  16712. * The `blur` event that caused this function to be called.
  16713. *
  16714. * @listens blur
  16715. */
  16716. handleBlur(event) {
  16717. const relatedTarget = event.relatedTarget || document.activeElement;
  16718. // Close menu popup when a user clicks outside the menu
  16719. if (!this.children().some(element => {
  16720. return element.el() === relatedTarget;
  16721. })) {
  16722. const btn = this.menuButton_;
  16723. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  16724. btn.unpressButton();
  16725. }
  16726. }
  16727. }
  16728. /**
  16729. * Called when a `MenuItem` gets clicked or tapped.
  16730. *
  16731. * @param {Event} event
  16732. * The `click` or `tap` event that caused this function to be called.
  16733. *
  16734. * @listens click,tap
  16735. */
  16736. handleTapClick(event) {
  16737. // Unpress the associated MenuButton, and move focus back to it
  16738. if (this.menuButton_) {
  16739. this.menuButton_.unpressButton();
  16740. const childComponents = this.children();
  16741. if (!Array.isArray(childComponents)) {
  16742. return;
  16743. }
  16744. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  16745. if (!foundComponent) {
  16746. return;
  16747. }
  16748. // don't focus menu button if item is a caption settings item
  16749. // because focus will move elsewhere
  16750. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  16751. this.menuButton_.focus();
  16752. }
  16753. }
  16754. }
  16755. /**
  16756. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  16757. *
  16758. * @param {KeyboardEvent} event
  16759. * A `keydown` event that happened on the menu.
  16760. *
  16761. * @listens keydown
  16762. */
  16763. handleKeyDown(event) {
  16764. // Left and Down Arrows
  16765. if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {
  16766. event.preventDefault();
  16767. event.stopPropagation();
  16768. this.stepForward();
  16769. // Up and Right Arrows
  16770. } else if (event.key === 'ArrowRight' || event.key === 'ArrowUp') {
  16771. event.preventDefault();
  16772. event.stopPropagation();
  16773. this.stepBack();
  16774. }
  16775. }
  16776. /**
  16777. * Move to next (lower) menu item for keyboard users.
  16778. */
  16779. stepForward() {
  16780. let stepChild = 0;
  16781. if (this.focusedChild_ !== undefined) {
  16782. stepChild = this.focusedChild_ + 1;
  16783. }
  16784. this.focus(stepChild);
  16785. }
  16786. /**
  16787. * Move to previous (higher) menu item for keyboard users.
  16788. */
  16789. stepBack() {
  16790. let stepChild = 0;
  16791. if (this.focusedChild_ !== undefined) {
  16792. stepChild = this.focusedChild_ - 1;
  16793. }
  16794. this.focus(stepChild);
  16795. }
  16796. /**
  16797. * Set focus on a {@link MenuItem} in the `Menu`.
  16798. *
  16799. * @param {Object|string} [item=0]
  16800. * Index of child item set focus on.
  16801. */
  16802. focus(item = 0) {
  16803. const children = this.children().slice();
  16804. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  16805. if (haveTitle) {
  16806. children.shift();
  16807. }
  16808. if (children.length > 0) {
  16809. if (item < 0) {
  16810. item = 0;
  16811. } else if (item >= children.length) {
  16812. item = children.length - 1;
  16813. }
  16814. this.focusedChild_ = item;
  16815. children[item].el_.focus();
  16816. }
  16817. }
  16818. }
  16819. Component.registerComponent('Menu', Menu);
  16820. /**
  16821. * @file menu-button.js
  16822. */
  16823. /** @import Player from '../player' */
  16824. /**
  16825. * A `MenuButton` class for any popup {@link Menu}.
  16826. *
  16827. * @extends Component
  16828. */
  16829. class MenuButton extends Component {
  16830. /**
  16831. * Creates an instance of this class.
  16832. *
  16833. * @param {Player} player
  16834. * The `Player` that this class should be attached to.
  16835. *
  16836. * @param {Object} [options={}]
  16837. * The key/value store of player options.
  16838. */
  16839. constructor(player, options = {}) {
  16840. super(player, options);
  16841. this.menuButton_ = new Button(player, options);
  16842. this.menuButton_.controlText(this.controlText_);
  16843. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  16844. // Add buildCSSClass values to the button, not the wrapper
  16845. const buttonClass = Button.prototype.buildCSSClass();
  16846. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  16847. this.menuButton_.removeClass('vjs-control');
  16848. this.addChild(this.menuButton_);
  16849. this.update();
  16850. this.enabled_ = true;
  16851. const handleClick = e => this.handleClick(e);
  16852. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  16853. this.on(this.menuButton_, 'tap', handleClick);
  16854. this.on(this.menuButton_, 'click', handleClick);
  16855. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  16856. this.on(this.menuButton_, 'mouseenter', () => {
  16857. this.addClass('vjs-hover');
  16858. this.menu.show();
  16859. on(document, 'keyup', this.handleMenuKeyUp_);
  16860. });
  16861. this.on('mouseleave', e => this.handleMouseLeave(e));
  16862. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  16863. }
  16864. /**
  16865. * Update the menu based on the current state of its items.
  16866. */
  16867. update() {
  16868. const menu = this.createMenu();
  16869. if (this.menu) {
  16870. this.menu.dispose();
  16871. this.removeChild(this.menu);
  16872. }
  16873. this.menu = menu;
  16874. this.addChild(menu);
  16875. /**
  16876. * Track the state of the menu button
  16877. *
  16878. * @type {Boolean}
  16879. * @private
  16880. */
  16881. this.buttonPressed_ = false;
  16882. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  16883. if (this.items && this.items.length <= this.hideThreshold_) {
  16884. this.hide();
  16885. this.menu.contentEl_.removeAttribute('role');
  16886. } else {
  16887. this.show();
  16888. this.menu.contentEl_.setAttribute('role', 'menu');
  16889. }
  16890. }
  16891. /**
  16892. * Create the menu and add all items to it.
  16893. *
  16894. * @return {Menu}
  16895. * The constructed menu
  16896. */
  16897. createMenu() {
  16898. const menu = new Menu(this.player_, {
  16899. menuButton: this
  16900. });
  16901. /**
  16902. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  16903. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  16904. * it here because every time we run `createMenu` we need to reset the value.
  16905. *
  16906. * @protected
  16907. * @type {Number}
  16908. */
  16909. this.hideThreshold_ = 0;
  16910. // Add a title list item to the top
  16911. if (this.options_.title) {
  16912. const titleEl = createEl('li', {
  16913. className: 'vjs-menu-title',
  16914. textContent: toTitleCase(this.options_.title),
  16915. tabIndex: -1
  16916. });
  16917. const titleComponent = new Component(this.player_, {
  16918. el: titleEl
  16919. });
  16920. menu.addItem(titleComponent);
  16921. }
  16922. this.items = this.createItems();
  16923. if (this.items) {
  16924. // Add menu items to the menu
  16925. for (let i = 0; i < this.items.length; i++) {
  16926. menu.addItem(this.items[i]);
  16927. }
  16928. }
  16929. return menu;
  16930. }
  16931. /**
  16932. * Create the list of menu items. Specific to each subclass.
  16933. *
  16934. * @abstract
  16935. */
  16936. createItems() {}
  16937. /**
  16938. * Create the `MenuButtons`s DOM element.
  16939. *
  16940. * @return {Element}
  16941. * The element that gets created.
  16942. */
  16943. createEl() {
  16944. return super.createEl('div', {
  16945. className: this.buildWrapperCSSClass()
  16946. }, {});
  16947. }
  16948. /**
  16949. * Overwrites the `setIcon` method from `Component`.
  16950. * In this case, we want the icon to be appended to the menuButton.
  16951. *
  16952. * @param {string} name
  16953. * The icon name to be added.
  16954. */
  16955. setIcon(name) {
  16956. super.setIcon(name, this.menuButton_.el_);
  16957. }
  16958. /**
  16959. * Allow sub components to stack CSS class names for the wrapper element
  16960. *
  16961. * @return {string}
  16962. * The constructed wrapper DOM `className`
  16963. */
  16964. buildWrapperCSSClass() {
  16965. let menuButtonClass = 'vjs-menu-button';
  16966. // If the inline option is passed, we want to use different styles altogether.
  16967. if (this.options_.inline === true) {
  16968. menuButtonClass += '-inline';
  16969. } else {
  16970. menuButtonClass += '-popup';
  16971. }
  16972. // TODO: Fix the CSS so that this isn't necessary
  16973. const buttonClass = Button.prototype.buildCSSClass();
  16974. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  16975. }
  16976. /**
  16977. * Builds the default DOM `className`.
  16978. *
  16979. * @return {string}
  16980. * The DOM `className` for this object.
  16981. */
  16982. buildCSSClass() {
  16983. let menuButtonClass = 'vjs-menu-button';
  16984. // If the inline option is passed, we want to use different styles altogether.
  16985. if (this.options_.inline === true) {
  16986. menuButtonClass += '-inline';
  16987. } else {
  16988. menuButtonClass += '-popup';
  16989. }
  16990. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  16991. }
  16992. /**
  16993. * Get or set the localized control text that will be used for accessibility.
  16994. *
  16995. * > NOTE: This will come from the internal `menuButton_` element.
  16996. *
  16997. * @param {string} [text]
  16998. * Control text for element.
  16999. *
  17000. * @param {Element} [el=this.menuButton_.el()]
  17001. * Element to set the title on.
  17002. *
  17003. * @return {string}
  17004. * - The control text when getting
  17005. */
  17006. controlText(text, el = this.menuButton_.el()) {
  17007. return this.menuButton_.controlText(text, el);
  17008. }
  17009. /**
  17010. * Dispose of the `menu-button` and all child components.
  17011. */
  17012. dispose() {
  17013. this.handleMouseLeave();
  17014. super.dispose();
  17015. }
  17016. /**
  17017. * Handle a click on a `MenuButton`.
  17018. * See {@link ClickableComponent#handleClick} for instances where this is called.
  17019. *
  17020. * @param {Event} event
  17021. * The `keydown`, `tap`, or `click` event that caused this function to be
  17022. * called.
  17023. *
  17024. * @listens tap
  17025. * @listens click
  17026. */
  17027. handleClick(event) {
  17028. if (this.buttonPressed_) {
  17029. this.unpressButton();
  17030. } else {
  17031. this.pressButton();
  17032. }
  17033. }
  17034. /**
  17035. * Handle `mouseleave` for `MenuButton`.
  17036. *
  17037. * @param {Event} event
  17038. * The `mouseleave` event that caused this function to be called.
  17039. *
  17040. * @listens mouseleave
  17041. */
  17042. handleMouseLeave(event) {
  17043. this.removeClass('vjs-hover');
  17044. off(document, 'keyup', this.handleMenuKeyUp_);
  17045. }
  17046. /**
  17047. * Set the focus to the actual button, not to this element
  17048. */
  17049. focus() {
  17050. this.menuButton_.focus();
  17051. }
  17052. /**
  17053. * Remove the focus from the actual button, not this element
  17054. */
  17055. blur() {
  17056. this.menuButton_.blur();
  17057. }
  17058. /**
  17059. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  17060. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  17061. *
  17062. * @param {Event} event
  17063. * The `keydown` event that caused this function to be called.
  17064. *
  17065. * @listens keydown
  17066. */
  17067. handleKeyDown(event) {
  17068. // Escape or Tab unpress the 'button'
  17069. if (event.key === 'Escape' || event.key === 'Tab') {
  17070. if (this.buttonPressed_) {
  17071. this.unpressButton();
  17072. }
  17073. // Don't preventDefault for Tab key - we still want to lose focus
  17074. if (!event.key === 'Tab') {
  17075. event.preventDefault();
  17076. // Set focus back to the menu button's button
  17077. this.menuButton_.focus();
  17078. }
  17079. // Up Arrow or Down Arrow also 'press' the button to open the menu
  17080. } else if (event.key === 'Up' || event.key === 'Down' && !(this.player_.options_.playerOptions.spatialNavigation && this.player_.options_.playerOptions.spatialNavigation.enabled)) {
  17081. if (!this.buttonPressed_) {
  17082. event.preventDefault();
  17083. this.pressButton();
  17084. }
  17085. }
  17086. }
  17087. /**
  17088. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  17089. * the constructor.
  17090. *
  17091. * @param {Event} event
  17092. * Key press event
  17093. *
  17094. * @listens keyup
  17095. */
  17096. handleMenuKeyUp(event) {
  17097. // Escape hides popup menu
  17098. if (event.key === 'Escape' || event.key === 'Tab') {
  17099. this.removeClass('vjs-hover');
  17100. }
  17101. }
  17102. /**
  17103. * This method name now delegates to `handleSubmenuKeyDown`. This means
  17104. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  17105. * stop working.
  17106. *
  17107. * @param {Event} event
  17108. * The event that caused this function to be called.
  17109. */
  17110. handleSubmenuKeyPress(event) {
  17111. this.handleSubmenuKeyDown(event);
  17112. }
  17113. /**
  17114. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  17115. * the constructor.
  17116. *
  17117. * @param {Event} event
  17118. * Key press event
  17119. *
  17120. * @listens keydown
  17121. */
  17122. handleSubmenuKeyDown(event) {
  17123. // Escape or Tab unpress the 'button'
  17124. if (event.key === 'Escape' || event.key === 'Tab') {
  17125. if (this.buttonPressed_) {
  17126. this.unpressButton();
  17127. }
  17128. // Don't preventDefault for Tab key - we still want to lose focus
  17129. if (!event.key === 'Tab') {
  17130. event.preventDefault();
  17131. // Set focus back to the menu button's button
  17132. this.menuButton_.focus();
  17133. }
  17134. }
  17135. }
  17136. /**
  17137. * Put the current `MenuButton` into a pressed state.
  17138. */
  17139. pressButton() {
  17140. if (this.enabled_) {
  17141. this.buttonPressed_ = true;
  17142. this.menu.show();
  17143. this.menu.lockShowing();
  17144. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  17145. // set the focus into the submenu, except on iOS where it is resulting in
  17146. // undesired scrolling behavior when the player is in an iframe
  17147. if (IS_IOS && isInFrame()) {
  17148. // Return early so that the menu isn't focused
  17149. return;
  17150. }
  17151. this.menu.focus();
  17152. }
  17153. }
  17154. /**
  17155. * Take the current `MenuButton` out of a pressed state.
  17156. */
  17157. unpressButton() {
  17158. if (this.enabled_) {
  17159. this.buttonPressed_ = false;
  17160. this.menu.unlockShowing();
  17161. this.menu.hide();
  17162. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  17163. }
  17164. }
  17165. /**
  17166. * Disable the `MenuButton`. Don't allow it to be clicked.
  17167. */
  17168. disable() {
  17169. this.unpressButton();
  17170. this.enabled_ = false;
  17171. this.addClass('vjs-disabled');
  17172. this.menuButton_.disable();
  17173. }
  17174. /**
  17175. * Enable the `MenuButton`. Allow it to be clicked.
  17176. */
  17177. enable() {
  17178. this.enabled_ = true;
  17179. this.removeClass('vjs-disabled');
  17180. this.menuButton_.enable();
  17181. }
  17182. }
  17183. Component.registerComponent('MenuButton', MenuButton);
  17184. /**
  17185. * @file track-button.js
  17186. */
  17187. /** @import Player from './player' */
  17188. /**
  17189. * The base class for buttons that toggle specific track types (e.g. subtitles).
  17190. *
  17191. * @extends MenuButton
  17192. */
  17193. class TrackButton extends MenuButton {
  17194. /**
  17195. * Creates an instance of this class.
  17196. *
  17197. * @param {Player} player
  17198. * The `Player` that this class should be attached to.
  17199. *
  17200. * @param {Object} [options]
  17201. * The key/value store of player options.
  17202. */
  17203. constructor(player, options) {
  17204. const tracks = options.tracks;
  17205. super(player, options);
  17206. if (this.items.length <= 1) {
  17207. this.hide();
  17208. }
  17209. if (!tracks) {
  17210. return;
  17211. }
  17212. const updateHandler = bind_(this, this.update);
  17213. tracks.addEventListener('removetrack', updateHandler);
  17214. tracks.addEventListener('addtrack', updateHandler);
  17215. tracks.addEventListener('labelchange', updateHandler);
  17216. this.player_.on('ready', updateHandler);
  17217. this.player_.on('dispose', function () {
  17218. tracks.removeEventListener('removetrack', updateHandler);
  17219. tracks.removeEventListener('addtrack', updateHandler);
  17220. tracks.removeEventListener('labelchange', updateHandler);
  17221. });
  17222. }
  17223. }
  17224. Component.registerComponent('TrackButton', TrackButton);
  17225. /**
  17226. * @file menu-item.js
  17227. */
  17228. /** @import Player from '../player' */
  17229. /**
  17230. * The component for a menu item. `<li>`
  17231. *
  17232. * @extends ClickableComponent
  17233. */
  17234. class MenuItem extends ClickableComponent {
  17235. /**
  17236. * Creates an instance of the this class.
  17237. *
  17238. * @param {Player} player
  17239. * The `Player` that this class should be attached to.
  17240. *
  17241. * @param {Object} [options={}]
  17242. * The key/value store of player options.
  17243. *
  17244. */
  17245. constructor(player, options) {
  17246. super(player, options);
  17247. this.selectable = options.selectable;
  17248. this.isSelected_ = options.selected || false;
  17249. this.multiSelectable = options.multiSelectable;
  17250. this.selected(this.isSelected_);
  17251. if (this.selectable) {
  17252. if (this.multiSelectable) {
  17253. this.el_.setAttribute('role', 'menuitemcheckbox');
  17254. } else {
  17255. this.el_.setAttribute('role', 'menuitemradio');
  17256. }
  17257. } else {
  17258. this.el_.setAttribute('role', 'menuitem');
  17259. }
  17260. }
  17261. /**
  17262. * Create the `MenuItem's DOM element
  17263. *
  17264. * @param {string} [type=li]
  17265. * Element's node type, not actually used, always set to `li`.
  17266. *
  17267. * @param {Object} [props={}]
  17268. * An object of properties that should be set on the element
  17269. *
  17270. * @param {Object} [attrs={}]
  17271. * An object of attributes that should be set on the element
  17272. *
  17273. * @return {Element}
  17274. * The element that gets created.
  17275. */
  17276. createEl(type, props, attrs) {
  17277. // The control is textual, not just an icon
  17278. this.nonIconControl = true;
  17279. const el = super.createEl('li', Object.assign({
  17280. className: 'vjs-menu-item',
  17281. tabIndex: -1
  17282. }, props), attrs);
  17283. // swap icon with menu item text.
  17284. const menuItemEl = createEl('span', {
  17285. className: 'vjs-menu-item-text',
  17286. textContent: this.localize(this.options_.label)
  17287. });
  17288. // If using SVG icons, the element with vjs-icon-placeholder will be added separately.
  17289. if (this.player_.options_.experimentalSvgIcons) {
  17290. el.appendChild(menuItemEl);
  17291. } else {
  17292. el.replaceChild(menuItemEl, el.querySelector('.vjs-icon-placeholder'));
  17293. }
  17294. return el;
  17295. }
  17296. /**
  17297. * Ignore keys which are used by the menu, but pass any other ones up. See
  17298. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  17299. *
  17300. * @param {KeyboardEvent} event
  17301. * The `keydown` event that caused this function to be called.
  17302. *
  17303. * @listens keydown
  17304. */
  17305. handleKeyDown(event) {
  17306. if (!['Tab', 'Escape', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'].includes(event.key)) {
  17307. // Pass keydown handling up for unused keys
  17308. super.handleKeyDown(event);
  17309. }
  17310. }
  17311. /**
  17312. * Any click on a `MenuItem` puts it into the selected state.
  17313. * See {@link ClickableComponent#handleClick} for instances where this is called.
  17314. *
  17315. * @param {Event} event
  17316. * The `keydown`, `tap`, or `click` event that caused this function to be
  17317. * called.
  17318. *
  17319. * @listens tap
  17320. * @listens click
  17321. */
  17322. handleClick(event) {
  17323. this.selected(true);
  17324. }
  17325. /**
  17326. * Set the state for this menu item as selected or not.
  17327. *
  17328. * @param {boolean} selected
  17329. * if the menu item is selected or not
  17330. */
  17331. selected(selected) {
  17332. if (this.selectable) {
  17333. if (selected) {
  17334. this.addClass('vjs-selected');
  17335. this.el_.setAttribute('aria-checked', 'true');
  17336. // aria-checked isn't fully supported by browsers/screen readers,
  17337. // so indicate selected state to screen reader in the control text.
  17338. this.controlText(', selected');
  17339. this.isSelected_ = true;
  17340. } else {
  17341. this.removeClass('vjs-selected');
  17342. this.el_.setAttribute('aria-checked', 'false');
  17343. // Indicate un-selected state to screen reader
  17344. this.controlText('');
  17345. this.isSelected_ = false;
  17346. }
  17347. }
  17348. }
  17349. }
  17350. Component.registerComponent('MenuItem', MenuItem);
  17351. /**
  17352. * @file text-track-menu-item.js
  17353. */
  17354. /** @import Player from '../../player' */
  17355. /**
  17356. * The specific menu item type for selecting a language within a text track kind
  17357. *
  17358. * @extends MenuItem
  17359. */
  17360. class TextTrackMenuItem extends MenuItem {
  17361. /**
  17362. * Creates an instance of this class.
  17363. *
  17364. * @param {Player} player
  17365. * The `Player` that this class should be attached to.
  17366. *
  17367. * @param {Object} [options]
  17368. * The key/value store of player options.
  17369. */
  17370. constructor(player, options) {
  17371. const track = options.track;
  17372. const tracks = player.textTracks();
  17373. // Modify options for parent MenuItem class's init.
  17374. options.label = track.label || track.language || 'Unknown';
  17375. options.selected = track.mode === 'showing';
  17376. super(player, options);
  17377. this.track = track;
  17378. // Determine the relevant kind(s) of tracks for this component and filter
  17379. // out empty kinds.
  17380. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  17381. const changeHandler = (...args) => {
  17382. this.handleTracksChange.apply(this, args);
  17383. };
  17384. const selectedLanguageChangeHandler = (...args) => {
  17385. this.handleSelectedLanguageChange.apply(this, args);
  17386. };
  17387. player.on(['loadstart', 'texttrackchange'], changeHandler);
  17388. tracks.addEventListener('change', changeHandler);
  17389. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  17390. this.on('dispose', function () {
  17391. player.off(['loadstart', 'texttrackchange'], changeHandler);
  17392. tracks.removeEventListener('change', changeHandler);
  17393. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  17394. });
  17395. // iOS7 doesn't dispatch change events to TextTrackLists when an
  17396. // associated track's mode changes. Without something like
  17397. // Object.observe() (also not present on iOS7), it's not
  17398. // possible to detect changes to the mode attribute and polyfill
  17399. // the change event. As a poor substitute, we manually dispatch
  17400. // change events whenever the controls modify the mode.
  17401. if (tracks.onchange === undefined) {
  17402. let event;
  17403. this.on(['tap', 'click'], function () {
  17404. if (typeof window.Event !== 'object') {
  17405. // Android 2.3 throws an Illegal Constructor error for window.Event
  17406. try {
  17407. event = new window.Event('change');
  17408. } catch (err) {
  17409. // continue regardless of error
  17410. }
  17411. }
  17412. if (!event) {
  17413. event = document.createEvent('Event');
  17414. event.initEvent('change', true, true);
  17415. }
  17416. tracks.dispatchEvent(event);
  17417. });
  17418. }
  17419. // set the default state based on current tracks
  17420. this.handleTracksChange();
  17421. }
  17422. /**
  17423. * This gets called when an `TextTrackMenuItem` is "clicked". See
  17424. * {@link ClickableComponent} for more detailed information on what a click can be.
  17425. *
  17426. * @param {Event} event
  17427. * The `keydown`, `tap`, or `click` event that caused this function to be
  17428. * called.
  17429. *
  17430. * @listens tap
  17431. * @listens click
  17432. */
  17433. handleClick(event) {
  17434. const referenceTrack = this.track;
  17435. const tracks = this.player_.textTracks();
  17436. super.handleClick(event);
  17437. if (!tracks) {
  17438. return;
  17439. }
  17440. for (let i = 0; i < tracks.length; i++) {
  17441. const track = tracks[i];
  17442. // If the track from the text tracks list is not of the right kind,
  17443. // skip it. We do not want to affect tracks of incompatible kind(s).
  17444. if (this.kinds.indexOf(track.kind) === -1) {
  17445. continue;
  17446. }
  17447. // If this text track is the component's track and it is not showing,
  17448. // set it to showing.
  17449. if (track === referenceTrack) {
  17450. if (track.mode !== 'showing') {
  17451. track.mode = 'showing';
  17452. }
  17453. // If this text track is not the component's track and it is not
  17454. // disabled, set it to disabled.
  17455. } else if (track.mode !== 'disabled') {
  17456. track.mode = 'disabled';
  17457. }
  17458. }
  17459. }
  17460. /**
  17461. * Handle text track list change
  17462. *
  17463. * @param {Event} event
  17464. * The `change` event that caused this function to be called.
  17465. *
  17466. * @listens TextTrackList#change
  17467. */
  17468. handleTracksChange(event) {
  17469. const shouldBeSelected = this.track.mode === 'showing';
  17470. // Prevent redundant selected() calls because they may cause
  17471. // screen readers to read the appended control text unnecessarily
  17472. if (shouldBeSelected !== this.isSelected_) {
  17473. this.selected(shouldBeSelected);
  17474. }
  17475. }
  17476. handleSelectedLanguageChange(event) {
  17477. if (this.track.mode === 'showing') {
  17478. const selectedLanguage = this.player_.cache_.selectedLanguage;
  17479. // Don't replace the kind of track across the same language
  17480. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  17481. return;
  17482. }
  17483. this.player_.cache_.selectedLanguage = {
  17484. enabled: true,
  17485. language: this.track.language,
  17486. kind: this.track.kind
  17487. };
  17488. }
  17489. }
  17490. dispose() {
  17491. // remove reference to track object on dispose
  17492. this.track = null;
  17493. super.dispose();
  17494. }
  17495. }
  17496. Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  17497. /**
  17498. * @file off-text-track-menu-item.js
  17499. */
  17500. /** @import Player from '../../player' */
  17501. /**
  17502. * A special menu item for turning off a specific type of text track
  17503. *
  17504. * @extends TextTrackMenuItem
  17505. */
  17506. class OffTextTrackMenuItem extends TextTrackMenuItem {
  17507. /**
  17508. * Creates an instance of this class.
  17509. *
  17510. * @param {Player} player
  17511. * The `Player` that this class should be attached to.
  17512. *
  17513. * @param {Object} [options]
  17514. * The key/value store of player options.
  17515. */
  17516. constructor(player, options) {
  17517. // Create pseudo track info
  17518. // Requires options['kind']
  17519. options.track = {
  17520. player,
  17521. // it is no longer necessary to store `kind` or `kinds` on the track itself
  17522. // since they are now stored in the `kinds` property of all instances of
  17523. // TextTrackMenuItem, but this will remain for backwards compatibility
  17524. kind: options.kind,
  17525. kinds: options.kinds,
  17526. default: false,
  17527. mode: 'disabled'
  17528. };
  17529. if (!options.kinds) {
  17530. options.kinds = [options.kind];
  17531. }
  17532. if (options.label) {
  17533. options.track.label = options.label;
  17534. } else {
  17535. options.track.label = options.kinds.join(' and ') + ' off';
  17536. }
  17537. // MenuItem is selectable
  17538. options.selectable = true;
  17539. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  17540. options.multiSelectable = false;
  17541. super(player, options);
  17542. }
  17543. /**
  17544. * Handle text track change
  17545. *
  17546. * @param {Event} event
  17547. * The event that caused this function to run
  17548. */
  17549. handleTracksChange(event) {
  17550. const tracks = this.player().textTracks();
  17551. let shouldBeSelected = true;
  17552. for (let i = 0, l = tracks.length; i < l; i++) {
  17553. const track = tracks[i];
  17554. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  17555. shouldBeSelected = false;
  17556. break;
  17557. }
  17558. }
  17559. // Prevent redundant selected() calls because they may cause
  17560. // screen readers to read the appended control text unnecessarily
  17561. if (shouldBeSelected !== this.isSelected_) {
  17562. this.selected(shouldBeSelected);
  17563. }
  17564. }
  17565. handleSelectedLanguageChange(event) {
  17566. const tracks = this.player().textTracks();
  17567. let allHidden = true;
  17568. for (let i = 0, l = tracks.length; i < l; i++) {
  17569. const track = tracks[i];
  17570. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  17571. allHidden = false;
  17572. break;
  17573. }
  17574. }
  17575. if (allHidden) {
  17576. this.player_.cache_.selectedLanguage = {
  17577. enabled: false
  17578. };
  17579. }
  17580. }
  17581. /**
  17582. * Update control text and label on languagechange
  17583. */
  17584. handleLanguagechange() {
  17585. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  17586. super.handleLanguagechange();
  17587. }
  17588. }
  17589. Component.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  17590. /**
  17591. * @file text-track-button.js
  17592. */
  17593. /** @import Player from '../../player' */
  17594. /**
  17595. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  17596. *
  17597. * @extends MenuButton
  17598. */
  17599. class TextTrackButton extends TrackButton {
  17600. /**
  17601. * Creates an instance of this class.
  17602. *
  17603. * @param {Player} player
  17604. * The `Player` that this class should be attached to.
  17605. *
  17606. * @param {Object} [options={}]
  17607. * The key/value store of player options.
  17608. */
  17609. constructor(player, options = {}) {
  17610. options.tracks = player.textTracks();
  17611. super(player, options);
  17612. }
  17613. /**
  17614. * Create a menu item for each text track
  17615. *
  17616. * @param {TextTrackMenuItem[]} [items=[]]
  17617. * Existing array of items to use during creation
  17618. *
  17619. * @return {TextTrackMenuItem[]}
  17620. * Array of menu items that were created
  17621. */
  17622. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  17623. // Label is an override for the [track] off label
  17624. // USed to localise captions/subtitles
  17625. let label;
  17626. if (this.label_) {
  17627. label = `${this.label_} off`;
  17628. }
  17629. // Add an OFF menu item to turn all tracks off
  17630. items.push(new OffTextTrackMenuItem(this.player_, {
  17631. kinds: this.kinds_,
  17632. kind: this.kind_,
  17633. label
  17634. }));
  17635. this.hideThreshold_ += 1;
  17636. const tracks = this.player_.textTracks();
  17637. if (!Array.isArray(this.kinds_)) {
  17638. this.kinds_ = [this.kind_];
  17639. }
  17640. for (let i = 0; i < tracks.length; i++) {
  17641. const track = tracks[i];
  17642. // only add tracks that are of an appropriate kind and have a label
  17643. if (this.kinds_.indexOf(track.kind) > -1) {
  17644. const item = new TrackMenuItem(this.player_, {
  17645. track,
  17646. kinds: this.kinds_,
  17647. kind: this.kind_,
  17648. // MenuItem is selectable
  17649. selectable: true,
  17650. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  17651. multiSelectable: false
  17652. });
  17653. item.addClass(`vjs-${track.kind}-menu-item`);
  17654. items.push(item);
  17655. }
  17656. }
  17657. return items;
  17658. }
  17659. }
  17660. Component.registerComponent('TextTrackButton', TextTrackButton);
  17661. /**
  17662. * @file chapters-track-menu-item.js
  17663. */
  17664. /** @import Player from '../../player' */
  17665. /**
  17666. * The chapter track menu item
  17667. *
  17668. * @extends MenuItem
  17669. */
  17670. class ChaptersTrackMenuItem extends MenuItem {
  17671. /**
  17672. * Creates an instance of this class.
  17673. *
  17674. * @param {Player} player
  17675. * The `Player` that this class should be attached to.
  17676. *
  17677. * @param {Object} [options]
  17678. * The key/value store of player options.
  17679. */
  17680. constructor(player, options) {
  17681. const track = options.track;
  17682. const cue = options.cue;
  17683. const currentTime = player.currentTime();
  17684. // Modify options for parent MenuItem class's init.
  17685. options.selectable = true;
  17686. options.multiSelectable = false;
  17687. options.label = cue.text;
  17688. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  17689. super(player, options);
  17690. this.track = track;
  17691. this.cue = cue;
  17692. }
  17693. /**
  17694. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  17695. * {@link ClickableComponent} for more detailed information on what a click can be.
  17696. *
  17697. * @param {Event} [event]
  17698. * The `keydown`, `tap`, or `click` event that caused this function to be
  17699. * called.
  17700. *
  17701. * @listens tap
  17702. * @listens click
  17703. */
  17704. handleClick(event) {
  17705. super.handleClick();
  17706. this.player_.currentTime(this.cue.startTime);
  17707. }
  17708. }
  17709. Component.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  17710. /**
  17711. * @file chapters-button.js
  17712. */
  17713. /** @import Player from '../../player' */
  17714. /** @import Menu from '../../menu/menu' */
  17715. /** @import TextTrack from '../../tracks/text-track' */
  17716. /** @import TextTrackMenuItem from '../text-track-controls/text-track-menu-item' */
  17717. /**
  17718. * The button component for toggling and selecting chapters
  17719. * Chapters act much differently than other text tracks
  17720. * Cues are navigation vs. other tracks of alternative languages
  17721. *
  17722. * @extends TextTrackButton
  17723. */
  17724. class ChaptersButton extends TextTrackButton {
  17725. /**
  17726. * Creates an instance of this class.
  17727. *
  17728. * @param {Player} player
  17729. * The `Player` that this class should be attached to.
  17730. *
  17731. * @param {Object} [options]
  17732. * The key/value store of player options.
  17733. *
  17734. * @param {Function} [ready]
  17735. * The function to call when this function is ready.
  17736. */
  17737. constructor(player, options, ready) {
  17738. super(player, options, ready);
  17739. this.setIcon('chapters');
  17740. this.selectCurrentItem_ = () => {
  17741. this.items.forEach(item => {
  17742. item.selected(this.track_.activeCues[0] === item.cue);
  17743. });
  17744. };
  17745. }
  17746. /**
  17747. * Builds the default DOM `className`.
  17748. *
  17749. * @return {string}
  17750. * The DOM `className` for this object.
  17751. */
  17752. buildCSSClass() {
  17753. return `vjs-chapters-button ${super.buildCSSClass()}`;
  17754. }
  17755. buildWrapperCSSClass() {
  17756. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  17757. }
  17758. /**
  17759. * Update the menu based on the current state of its items.
  17760. *
  17761. * @param {Event} [event]
  17762. * An event that triggered this function to run.
  17763. *
  17764. * @listens TextTrackList#addtrack
  17765. * @listens TextTrackList#removetrack
  17766. * @listens TextTrackList#change
  17767. */
  17768. update(event) {
  17769. if (event && event.track && event.track.kind !== 'chapters') {
  17770. return;
  17771. }
  17772. const track = this.findChaptersTrack();
  17773. if (track !== this.track_) {
  17774. this.setTrack(track);
  17775. super.update();
  17776. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  17777. // Update the menu initially or if the number of cues has changed since set
  17778. super.update();
  17779. }
  17780. }
  17781. /**
  17782. * Set the currently selected track for the chapters button.
  17783. *
  17784. * @param {TextTrack} track
  17785. * The new track to select. Nothing will change if this is the currently selected
  17786. * track.
  17787. */
  17788. setTrack(track) {
  17789. if (this.track_ === track) {
  17790. return;
  17791. }
  17792. if (!this.updateHandler_) {
  17793. this.updateHandler_ = this.update.bind(this);
  17794. }
  17795. // here this.track_ refers to the old track instance
  17796. if (this.track_) {
  17797. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  17798. if (remoteTextTrackEl) {
  17799. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  17800. }
  17801. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  17802. this.track_ = null;
  17803. }
  17804. this.track_ = track;
  17805. // here this.track_ refers to the new track instance
  17806. if (this.track_) {
  17807. this.track_.mode = 'hidden';
  17808. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  17809. if (remoteTextTrackEl) {
  17810. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  17811. }
  17812. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  17813. }
  17814. }
  17815. /**
  17816. * Find the track object that is currently in use by this ChaptersButton
  17817. *
  17818. * @return {TextTrack|undefined}
  17819. * The current track or undefined if none was found.
  17820. */
  17821. findChaptersTrack() {
  17822. const tracks = this.player_.textTracks() || [];
  17823. for (let i = tracks.length - 1; i >= 0; i--) {
  17824. // We will always choose the last track as our chaptersTrack
  17825. const track = tracks[i];
  17826. if (track.kind === this.kind_) {
  17827. return track;
  17828. }
  17829. }
  17830. }
  17831. /**
  17832. * Get the caption for the ChaptersButton based on the track label. This will also
  17833. * use the current tracks localized kind as a fallback if a label does not exist.
  17834. *
  17835. * @return {string}
  17836. * The tracks current label or the localized track kind.
  17837. */
  17838. getMenuCaption() {
  17839. if (this.track_ && this.track_.label) {
  17840. return this.track_.label;
  17841. }
  17842. return this.localize(toTitleCase(this.kind_));
  17843. }
  17844. /**
  17845. * Create menu from chapter track
  17846. *
  17847. * @return {Menu}
  17848. * New menu for the chapter buttons
  17849. */
  17850. createMenu() {
  17851. this.options_.title = this.getMenuCaption();
  17852. return super.createMenu();
  17853. }
  17854. /**
  17855. * Create a menu item for each text track
  17856. *
  17857. * @return {TextTrackMenuItem[]}
  17858. * Array of menu items
  17859. */
  17860. createItems() {
  17861. const items = [];
  17862. if (!this.track_) {
  17863. return items;
  17864. }
  17865. const cues = this.track_.cues;
  17866. if (!cues) {
  17867. return items;
  17868. }
  17869. for (let i = 0, l = cues.length; i < l; i++) {
  17870. const cue = cues[i];
  17871. const mi = new ChaptersTrackMenuItem(this.player_, {
  17872. track: this.track_,
  17873. cue
  17874. });
  17875. items.push(mi);
  17876. }
  17877. return items;
  17878. }
  17879. }
  17880. /**
  17881. * `kind` of TextTrack to look for to associate it with this menu.
  17882. *
  17883. * @type {string}
  17884. * @private
  17885. */
  17886. ChaptersButton.prototype.kind_ = 'chapters';
  17887. /**
  17888. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  17889. *
  17890. * @type {string}
  17891. * @protected
  17892. */
  17893. ChaptersButton.prototype.controlText_ = 'Chapters';
  17894. Component.registerComponent('ChaptersButton', ChaptersButton);
  17895. /**
  17896. * @file descriptions-button.js
  17897. */
  17898. /** @import Player from '../../player' */
  17899. /**
  17900. * The button component for toggling and selecting descriptions
  17901. *
  17902. * @extends TextTrackButton
  17903. */
  17904. class DescriptionsButton extends TextTrackButton {
  17905. /**
  17906. * Creates an instance of this class.
  17907. *
  17908. * @param {Player} player
  17909. * The `Player` that this class should be attached to.
  17910. *
  17911. * @param {Object} [options]
  17912. * The key/value store of player options.
  17913. *
  17914. * @param {Function} [ready]
  17915. * The function to call when this component is ready.
  17916. */
  17917. constructor(player, options, ready) {
  17918. super(player, options, ready);
  17919. this.setIcon('audio-description');
  17920. const tracks = player.textTracks();
  17921. const changeHandler = bind_(this, this.handleTracksChange);
  17922. tracks.addEventListener('change', changeHandler);
  17923. this.on('dispose', function () {
  17924. tracks.removeEventListener('change', changeHandler);
  17925. });
  17926. }
  17927. /**
  17928. * Handle text track change
  17929. *
  17930. * @param {Event} event
  17931. * The event that caused this function to run
  17932. *
  17933. * @listens TextTrackList#change
  17934. */
  17935. handleTracksChange(event) {
  17936. const tracks = this.player().textTracks();
  17937. let disabled = false;
  17938. // Check whether a track of a different kind is showing
  17939. for (let i = 0, l = tracks.length; i < l; i++) {
  17940. const track = tracks[i];
  17941. if (track.kind !== this.kind_ && track.mode === 'showing') {
  17942. disabled = true;
  17943. break;
  17944. }
  17945. }
  17946. // If another track is showing, disable this menu button
  17947. if (disabled) {
  17948. this.disable();
  17949. } else {
  17950. this.enable();
  17951. }
  17952. }
  17953. /**
  17954. * Builds the default DOM `className`.
  17955. *
  17956. * @return {string}
  17957. * The DOM `className` for this object.
  17958. */
  17959. buildCSSClass() {
  17960. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  17961. }
  17962. buildWrapperCSSClass() {
  17963. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  17964. }
  17965. }
  17966. /**
  17967. * `kind` of TextTrack to look for to associate it with this menu.
  17968. *
  17969. * @type {string}
  17970. * @private
  17971. */
  17972. DescriptionsButton.prototype.kind_ = 'descriptions';
  17973. /**
  17974. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  17975. *
  17976. * @type {string}
  17977. * @protected
  17978. */
  17979. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  17980. Component.registerComponent('DescriptionsButton', DescriptionsButton);
  17981. /**
  17982. * @file subtitles-button.js
  17983. */
  17984. /** @import Player from '../../player' */
  17985. /**
  17986. * The button component for toggling and selecting subtitles
  17987. *
  17988. * @extends TextTrackButton
  17989. */
  17990. class SubtitlesButton extends TextTrackButton {
  17991. /**
  17992. * Creates an instance of this class.
  17993. *
  17994. * @param {Player} player
  17995. * The `Player` that this class should be attached to.
  17996. *
  17997. * @param {Object} [options]
  17998. * The key/value store of player options.
  17999. *
  18000. * @param {Function} [ready]
  18001. * The function to call when this component is ready.
  18002. */
  18003. constructor(player, options, ready) {
  18004. super(player, options, ready);
  18005. this.setIcon('subtitles');
  18006. }
  18007. /**
  18008. * Builds the default DOM `className`.
  18009. *
  18010. * @return {string}
  18011. * The DOM `className` for this object.
  18012. */
  18013. buildCSSClass() {
  18014. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  18015. }
  18016. buildWrapperCSSClass() {
  18017. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  18018. }
  18019. }
  18020. /**
  18021. * `kind` of TextTrack to look for to associate it with this menu.
  18022. *
  18023. * @type {string}
  18024. * @private
  18025. */
  18026. SubtitlesButton.prototype.kind_ = 'subtitles';
  18027. /**
  18028. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  18029. *
  18030. * @type {string}
  18031. * @protected
  18032. */
  18033. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  18034. Component.registerComponent('SubtitlesButton', SubtitlesButton);
  18035. /**
  18036. * @file caption-settings-menu-item.js
  18037. */
  18038. /** @import Player from '../../player' */
  18039. /**
  18040. * The menu item for caption track settings menu
  18041. *
  18042. * @extends TextTrackMenuItem
  18043. */
  18044. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  18045. /**
  18046. * Creates an instance of this class.
  18047. *
  18048. * @param {Player} player
  18049. * The `Player` that this class should be attached to.
  18050. *
  18051. * @param {Object} [options]
  18052. * The key/value store of player options.
  18053. */
  18054. constructor(player, options) {
  18055. options.track = {
  18056. player,
  18057. kind: options.kind,
  18058. label: options.kind + ' settings',
  18059. selectable: false,
  18060. default: false,
  18061. mode: 'disabled'
  18062. };
  18063. // CaptionSettingsMenuItem has no concept of 'selected'
  18064. options.selectable = false;
  18065. options.name = 'CaptionSettingsMenuItem';
  18066. super(player, options);
  18067. this.addClass('vjs-texttrack-settings');
  18068. this.controlText(', opens ' + options.kind + ' settings dialog');
  18069. }
  18070. /**
  18071. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  18072. * {@link ClickableComponent} for more detailed information on what a click can be.
  18073. *
  18074. * @param {Event} [event]
  18075. * The `keydown`, `tap`, or `click` event that caused this function to be
  18076. * called.
  18077. *
  18078. * @listens tap
  18079. * @listens click
  18080. */
  18081. handleClick(event) {
  18082. this.player().getChild('textTrackSettings').open();
  18083. }
  18084. /**
  18085. * Update control text and label on languagechange
  18086. */
  18087. handleLanguagechange() {
  18088. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  18089. super.handleLanguagechange();
  18090. }
  18091. }
  18092. Component.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  18093. /**
  18094. * @file captions-button.js
  18095. */
  18096. /** @import Player from '../../player' */
  18097. /**
  18098. * The button component for toggling and selecting captions
  18099. *
  18100. * @extends TextTrackButton
  18101. */
  18102. class CaptionsButton extends TextTrackButton {
  18103. /**
  18104. * Creates an instance of this class.
  18105. *
  18106. * @param {Player} player
  18107. * The `Player` that this class should be attached to.
  18108. *
  18109. * @param {Object} [options]
  18110. * The key/value store of player options.
  18111. *
  18112. * @param {Function} [ready]
  18113. * The function to call when this component is ready.
  18114. */
  18115. constructor(player, options, ready) {
  18116. super(player, options, ready);
  18117. this.setIcon('captions');
  18118. }
  18119. /**
  18120. * Builds the default DOM `className`.
  18121. *
  18122. * @return {string}
  18123. * The DOM `className` for this object.
  18124. */
  18125. buildCSSClass() {
  18126. return `vjs-captions-button ${super.buildCSSClass()}`;
  18127. }
  18128. buildWrapperCSSClass() {
  18129. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  18130. }
  18131. /**
  18132. * Create caption menu items
  18133. *
  18134. * @return {CaptionSettingsMenuItem[]}
  18135. * The array of current menu items.
  18136. */
  18137. createItems() {
  18138. const items = [];
  18139. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  18140. items.push(new CaptionSettingsMenuItem(this.player_, {
  18141. kind: this.kind_
  18142. }));
  18143. this.hideThreshold_ += 1;
  18144. }
  18145. return super.createItems(items);
  18146. }
  18147. }
  18148. /**
  18149. * `kind` of TextTrack to look for to associate it with this menu.
  18150. *
  18151. * @type {string}
  18152. * @private
  18153. */
  18154. CaptionsButton.prototype.kind_ = 'captions';
  18155. /**
  18156. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  18157. *
  18158. * @type {string}
  18159. * @protected
  18160. */
  18161. CaptionsButton.prototype.controlText_ = 'Captions';
  18162. Component.registerComponent('CaptionsButton', CaptionsButton);
  18163. /**
  18164. * @file subs-caps-menu-item.js
  18165. */
  18166. /**
  18167. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  18168. * in the SubsCapsMenu.
  18169. *
  18170. * @extends TextTrackMenuItem
  18171. */
  18172. class SubsCapsMenuItem extends TextTrackMenuItem {
  18173. createEl(type, props, attrs) {
  18174. const el = super.createEl(type, props, attrs);
  18175. const parentSpan = el.querySelector('.vjs-menu-item-text');
  18176. if (this.options_.track.kind === 'captions') {
  18177. if (this.player_.options_.experimentalSvgIcons) {
  18178. this.setIcon('captions', el);
  18179. } else {
  18180. parentSpan.appendChild(createEl('span', {
  18181. className: 'vjs-icon-placeholder'
  18182. }, {
  18183. 'aria-hidden': true
  18184. }));
  18185. }
  18186. parentSpan.appendChild(createEl('span', {
  18187. className: 'vjs-control-text',
  18188. // space added as the text will visually flow with the
  18189. // label
  18190. textContent: ` ${this.localize('Captions')}`
  18191. }));
  18192. }
  18193. return el;
  18194. }
  18195. }
  18196. Component.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  18197. /**
  18198. * @file sub-caps-button.js
  18199. */
  18200. /** @import Player from '../../player' */
  18201. /**
  18202. * The button component for toggling and selecting captions and/or subtitles
  18203. *
  18204. * @extends TextTrackButton
  18205. */
  18206. class SubsCapsButton extends TextTrackButton {
  18207. /**
  18208. * Creates an instance of this class.
  18209. *
  18210. * @param {Player} player
  18211. * The `Player` that this class should be attached to.
  18212. *
  18213. * @param {Object} [options]
  18214. * The key/value store of player options.
  18215. *
  18216. * @param {Function} [ready]
  18217. * The function to call when this component is ready.
  18218. */
  18219. constructor(player, options = {}) {
  18220. super(player, options);
  18221. // Although North America uses "captions" in most cases for
  18222. // "captions and subtitles" other locales use "subtitles"
  18223. this.label_ = 'subtitles';
  18224. this.setIcon('subtitles');
  18225. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  18226. this.label_ = 'captions';
  18227. this.setIcon('captions');
  18228. }
  18229. this.menuButton_.controlText(toTitleCase(this.label_));
  18230. }
  18231. /**
  18232. * Builds the default DOM `className`.
  18233. *
  18234. * @return {string}
  18235. * The DOM `className` for this object.
  18236. */
  18237. buildCSSClass() {
  18238. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  18239. }
  18240. buildWrapperCSSClass() {
  18241. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  18242. }
  18243. /**
  18244. * Create caption/subtitles menu items
  18245. *
  18246. * @return {CaptionSettingsMenuItem[]}
  18247. * The array of current menu items.
  18248. */
  18249. createItems() {
  18250. let items = [];
  18251. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  18252. items.push(new CaptionSettingsMenuItem(this.player_, {
  18253. kind: this.label_
  18254. }));
  18255. this.hideThreshold_ += 1;
  18256. }
  18257. items = super.createItems(items, SubsCapsMenuItem);
  18258. return items;
  18259. }
  18260. }
  18261. /**
  18262. * `kind`s of TextTrack to look for to associate it with this menu.
  18263. *
  18264. * @type {array}
  18265. * @private
  18266. */
  18267. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  18268. /**
  18269. * The text that should display over the `SubsCapsButton`s controls.
  18270. *
  18271. *
  18272. * @type {string}
  18273. * @protected
  18274. */
  18275. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  18276. Component.registerComponent('SubsCapsButton', SubsCapsButton);
  18277. /**
  18278. * @file audio-track-menu-item.js
  18279. */
  18280. /** @import Player from '../../player' */
  18281. /**
  18282. * An {@link AudioTrack} {@link MenuItem}
  18283. *
  18284. * @extends MenuItem
  18285. */
  18286. class AudioTrackMenuItem extends MenuItem {
  18287. /**
  18288. * Creates an instance of this class.
  18289. *
  18290. * @param {Player} player
  18291. * The `Player` that this class should be attached to.
  18292. *
  18293. * @param {Object} [options]
  18294. * The key/value store of player options.
  18295. */
  18296. constructor(player, options) {
  18297. const track = options.track;
  18298. const tracks = player.audioTracks();
  18299. // Modify options for parent MenuItem class's init.
  18300. options.label = track.label || track.language || 'Unknown';
  18301. options.selected = track.enabled;
  18302. super(player, options);
  18303. this.track = track;
  18304. this.addClass(`vjs-${track.kind}-menu-item`);
  18305. const changeHandler = (...args) => {
  18306. this.handleTracksChange.apply(this, args);
  18307. };
  18308. tracks.addEventListener('change', changeHandler);
  18309. this.on('dispose', () => {
  18310. tracks.removeEventListener('change', changeHandler);
  18311. });
  18312. }
  18313. createEl(type, props, attrs) {
  18314. const el = super.createEl(type, props, attrs);
  18315. const parentSpan = el.querySelector('.vjs-menu-item-text');
  18316. if (['main-desc', 'descriptions'].indexOf(this.options_.track.kind) >= 0) {
  18317. parentSpan.appendChild(createEl('span', {
  18318. className: 'vjs-icon-placeholder'
  18319. }, {
  18320. 'aria-hidden': true
  18321. }));
  18322. parentSpan.appendChild(createEl('span', {
  18323. className: 'vjs-control-text',
  18324. textContent: ' ' + this.localize('Descriptions')
  18325. }));
  18326. }
  18327. return el;
  18328. }
  18329. /**
  18330. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  18331. * for more detailed information on what a click can be.
  18332. *
  18333. * @param {Event} [event]
  18334. * The `keydown`, `tap`, or `click` event that caused this function to be
  18335. * called.
  18336. *
  18337. * @listens tap
  18338. * @listens click
  18339. */
  18340. handleClick(event) {
  18341. super.handleClick(event);
  18342. // the audio track list will automatically toggle other tracks
  18343. // off for us.
  18344. this.track.enabled = true;
  18345. // when native audio tracks are used, we want to make sure that other tracks are turned off
  18346. if (this.player_.tech_.featuresNativeAudioTracks) {
  18347. const tracks = this.player_.audioTracks();
  18348. for (let i = 0; i < tracks.length; i++) {
  18349. const track = tracks[i];
  18350. // skip the current track since we enabled it above
  18351. if (track === this.track) {
  18352. continue;
  18353. }
  18354. track.enabled = track === this.track;
  18355. }
  18356. }
  18357. }
  18358. /**
  18359. * Handle any {@link AudioTrack} change.
  18360. *
  18361. * @param {Event} [event]
  18362. * The {@link AudioTrackList#change} event that caused this to run.
  18363. *
  18364. * @listens AudioTrackList#change
  18365. */
  18366. handleTracksChange(event) {
  18367. this.selected(this.track.enabled);
  18368. }
  18369. }
  18370. Component.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  18371. /**
  18372. * @file audio-track-button.js
  18373. */
  18374. /**
  18375. * The base class for buttons that toggle specific {@link AudioTrack} types.
  18376. *
  18377. * @extends TrackButton
  18378. */
  18379. class AudioTrackButton extends TrackButton {
  18380. /**
  18381. * Creates an instance of this class.
  18382. *
  18383. * @param {Player} player
  18384. * The `Player` that this class should be attached to.
  18385. *
  18386. * @param {Object} [options={}]
  18387. * The key/value store of player options.
  18388. */
  18389. constructor(player, options = {}) {
  18390. options.tracks = player.audioTracks();
  18391. super(player, options);
  18392. this.setIcon('audio');
  18393. }
  18394. /**
  18395. * Builds the default DOM `className`.
  18396. *
  18397. * @return {string}
  18398. * The DOM `className` for this object.
  18399. */
  18400. buildCSSClass() {
  18401. return `vjs-audio-button ${super.buildCSSClass()}`;
  18402. }
  18403. buildWrapperCSSClass() {
  18404. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  18405. }
  18406. /**
  18407. * Create a menu item for each audio track
  18408. *
  18409. * @param {AudioTrackMenuItem[]} [items=[]]
  18410. * An array of existing menu items to use.
  18411. *
  18412. * @return {AudioTrackMenuItem[]}
  18413. * An array of menu items
  18414. */
  18415. createItems(items = []) {
  18416. // if there's only one audio track, there no point in showing it
  18417. this.hideThreshold_ = 1;
  18418. const tracks = this.player_.audioTracks();
  18419. for (let i = 0; i < tracks.length; i++) {
  18420. const track = tracks[i];
  18421. items.push(new AudioTrackMenuItem(this.player_, {
  18422. track,
  18423. // MenuItem is selectable
  18424. selectable: true,
  18425. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  18426. multiSelectable: false
  18427. }));
  18428. }
  18429. return items;
  18430. }
  18431. }
  18432. /**
  18433. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  18434. *
  18435. * @type {string}
  18436. * @protected
  18437. */
  18438. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  18439. Component.registerComponent('AudioTrackButton', AudioTrackButton);
  18440. /**
  18441. * @file playback-rate-menu-item.js
  18442. */
  18443. /** @import Player from '../../player' */
  18444. /**
  18445. * The specific menu item type for selecting a playback rate.
  18446. *
  18447. * @extends MenuItem
  18448. */
  18449. class PlaybackRateMenuItem extends MenuItem {
  18450. /**
  18451. * Creates an instance of this class.
  18452. *
  18453. * @param {Player} player
  18454. * The `Player` that this class should be attached to.
  18455. *
  18456. * @param {Object} [options]
  18457. * The key/value store of player options.
  18458. */
  18459. constructor(player, options) {
  18460. const label = options.rate;
  18461. const rate = parseFloat(label, 10);
  18462. // Modify options for parent MenuItem class's init.
  18463. options.label = label;
  18464. options.selected = rate === player.playbackRate();
  18465. options.selectable = true;
  18466. options.multiSelectable = false;
  18467. super(player, options);
  18468. this.label = label;
  18469. this.rate = rate;
  18470. this.on(player, 'ratechange', e => this.update(e));
  18471. }
  18472. /**
  18473. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  18474. * {@link ClickableComponent} for more detailed information on what a click can be.
  18475. *
  18476. * @param {Event} [event]
  18477. * The `keydown`, `tap`, or `click` event that caused this function to be
  18478. * called.
  18479. *
  18480. * @listens tap
  18481. * @listens click
  18482. */
  18483. handleClick(event) {
  18484. super.handleClick();
  18485. this.player().playbackRate(this.rate);
  18486. }
  18487. /**
  18488. * Update the PlaybackRateMenuItem when the playbackrate changes.
  18489. *
  18490. * @param {Event} [event]
  18491. * The `ratechange` event that caused this function to run.
  18492. *
  18493. * @listens Player#ratechange
  18494. */
  18495. update(event) {
  18496. this.selected(this.player().playbackRate() === this.rate);
  18497. }
  18498. }
  18499. /**
  18500. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  18501. *
  18502. * @type {string}
  18503. * @private
  18504. */
  18505. PlaybackRateMenuItem.prototype.contentElType = 'button';
  18506. Component.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  18507. /**
  18508. * @file playback-rate-menu-button.js
  18509. */
  18510. /** @import Player from '../../player' */
  18511. /**
  18512. * The component for controlling the playback rate.
  18513. *
  18514. * @extends MenuButton
  18515. */
  18516. class PlaybackRateMenuButton extends MenuButton {
  18517. /**
  18518. * Creates an instance of this class.
  18519. *
  18520. * @param {Player} player
  18521. * The `Player` that this class should be attached to.
  18522. *
  18523. * @param {Object} [options]
  18524. * The key/value store of player options.
  18525. */
  18526. constructor(player, options) {
  18527. super(player, options);
  18528. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  18529. this.updateVisibility();
  18530. this.updateLabel();
  18531. this.on(player, 'loadstart', e => this.updateVisibility(e));
  18532. this.on(player, 'ratechange', e => this.updateLabel(e));
  18533. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  18534. }
  18535. /**
  18536. * Create the `Component`'s DOM element
  18537. *
  18538. * @return {Element}
  18539. * The element that was created.
  18540. */
  18541. createEl() {
  18542. const el = super.createEl();
  18543. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  18544. this.labelEl_ = createEl('div', {
  18545. className: 'vjs-playback-rate-value',
  18546. id: this.labelElId_,
  18547. textContent: '1x'
  18548. });
  18549. el.appendChild(this.labelEl_);
  18550. return el;
  18551. }
  18552. dispose() {
  18553. this.labelEl_ = null;
  18554. super.dispose();
  18555. }
  18556. /**
  18557. * Builds the default DOM `className`.
  18558. *
  18559. * @return {string}
  18560. * The DOM `className` for this object.
  18561. */
  18562. buildCSSClass() {
  18563. return `vjs-playback-rate ${super.buildCSSClass()}`;
  18564. }
  18565. buildWrapperCSSClass() {
  18566. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  18567. }
  18568. /**
  18569. * Create the list of menu items. Specific to each subclass.
  18570. *
  18571. */
  18572. createItems() {
  18573. const rates = this.playbackRates();
  18574. const items = [];
  18575. for (let i = rates.length - 1; i >= 0; i--) {
  18576. items.push(new PlaybackRateMenuItem(this.player(), {
  18577. rate: rates[i] + 'x'
  18578. }));
  18579. }
  18580. return items;
  18581. }
  18582. /**
  18583. * On playbackrateschange, update the menu to account for the new items.
  18584. *
  18585. * @listens Player#playbackrateschange
  18586. */
  18587. handlePlaybackRateschange(event) {
  18588. this.update();
  18589. }
  18590. /**
  18591. * Get possible playback rates
  18592. *
  18593. * @return {Array}
  18594. * All possible playback rates
  18595. */
  18596. playbackRates() {
  18597. const player = this.player();
  18598. return player.playbackRates && player.playbackRates() || [];
  18599. }
  18600. /**
  18601. * Get whether playback rates is supported by the tech
  18602. * and an array of playback rates exists
  18603. *
  18604. * @return {boolean}
  18605. * Whether changing playback rate is supported
  18606. */
  18607. playbackRateSupported() {
  18608. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  18609. }
  18610. /**
  18611. * Hide playback rate controls when they're no playback rate options to select
  18612. *
  18613. * @param {Event} [event]
  18614. * The event that caused this function to run.
  18615. *
  18616. * @listens Player#loadstart
  18617. */
  18618. updateVisibility(event) {
  18619. if (this.playbackRateSupported()) {
  18620. this.removeClass('vjs-hidden');
  18621. } else {
  18622. this.addClass('vjs-hidden');
  18623. }
  18624. }
  18625. /**
  18626. * Update button label when rate changed
  18627. *
  18628. * @param {Event} [event]
  18629. * The event that caused this function to run.
  18630. *
  18631. * @listens Player#ratechange
  18632. */
  18633. updateLabel(event) {
  18634. if (this.playbackRateSupported()) {
  18635. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  18636. }
  18637. }
  18638. }
  18639. /**
  18640. * The text that should display over the `PlaybackRateMenuButton`s controls.
  18641. *
  18642. * Added for localization.
  18643. *
  18644. * @type {string}
  18645. * @protected
  18646. */
  18647. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  18648. Component.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  18649. /**
  18650. * @file spacer.js
  18651. */
  18652. /**
  18653. * Just an empty spacer element that can be used as an append point for plugins, etc.
  18654. * Also can be used to create space between elements when necessary.
  18655. *
  18656. * @extends Component
  18657. */
  18658. class Spacer extends Component {
  18659. /**
  18660. * Builds the default DOM `className`.
  18661. *
  18662. * @return {string}
  18663. * The DOM `className` for this object.
  18664. */
  18665. buildCSSClass() {
  18666. return `vjs-spacer ${super.buildCSSClass()}`;
  18667. }
  18668. /**
  18669. * Create the `Component`'s DOM element
  18670. *
  18671. * @return {Element}
  18672. * The element that was created.
  18673. */
  18674. createEl(tag = 'div', props = {}, attributes = {}) {
  18675. if (!props.className) {
  18676. props.className = this.buildCSSClass();
  18677. }
  18678. return super.createEl(tag, props, attributes);
  18679. }
  18680. }
  18681. Component.registerComponent('Spacer', Spacer);
  18682. /**
  18683. * @file custom-control-spacer.js
  18684. */
  18685. /**
  18686. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  18687. *
  18688. * @extends Spacer
  18689. */
  18690. class CustomControlSpacer extends Spacer {
  18691. /**
  18692. * Builds the default DOM `className`.
  18693. *
  18694. * @return {string}
  18695. * The DOM `className` for this object.
  18696. */
  18697. buildCSSClass() {
  18698. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  18699. }
  18700. /**
  18701. * Create the `Component`'s DOM element
  18702. *
  18703. * @return {Element}
  18704. * The element that was created.
  18705. */
  18706. createEl() {
  18707. return super.createEl('div', {
  18708. className: this.buildCSSClass(),
  18709. // No-flex/table-cell mode requires there be some content
  18710. // in the cell to fill the remaining space of the table.
  18711. textContent: '\u00a0'
  18712. });
  18713. }
  18714. }
  18715. Component.registerComponent('CustomControlSpacer', CustomControlSpacer);
  18716. /**
  18717. * @file control-bar.js
  18718. */
  18719. /**
  18720. * Container of main controls.
  18721. *
  18722. * @extends Component
  18723. */
  18724. class ControlBar extends Component {
  18725. /**
  18726. * Create the `Component`'s DOM element
  18727. *
  18728. * @return {Element}
  18729. * The element that was created.
  18730. */
  18731. createEl() {
  18732. return super.createEl('div', {
  18733. className: 'vjs-control-bar',
  18734. dir: 'ltr'
  18735. });
  18736. }
  18737. }
  18738. /**
  18739. * Default options for `ControlBar`
  18740. *
  18741. * @type {Object}
  18742. * @private
  18743. */
  18744. ControlBar.prototype.options_ = {
  18745. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'pictureInPictureToggle', 'fullscreenToggle']
  18746. };
  18747. Component.registerComponent('ControlBar', ControlBar);
  18748. /**
  18749. * @file error-display.js
  18750. */
  18751. /** @import Player from './player' */
  18752. /**
  18753. * A display that indicates an error has occurred. This means that the video
  18754. * is unplayable.
  18755. *
  18756. * @extends ModalDialog
  18757. */
  18758. class ErrorDisplay extends ModalDialog {
  18759. /**
  18760. * Creates an instance of this class.
  18761. *
  18762. * @param {Player} player
  18763. * The `Player` that this class should be attached to.
  18764. *
  18765. * @param {Object} [options]
  18766. * The key/value store of player options.
  18767. */
  18768. constructor(player, options) {
  18769. super(player, options);
  18770. this.on(player, 'error', e => {
  18771. this.open(e);
  18772. });
  18773. }
  18774. /**
  18775. * Builds the default DOM `className`.
  18776. *
  18777. * @return {string}
  18778. * The DOM `className` for this object.
  18779. *
  18780. * @deprecated Since version 5.
  18781. */
  18782. buildCSSClass() {
  18783. return `vjs-error-display ${super.buildCSSClass()}`;
  18784. }
  18785. /**
  18786. * Gets the localized error message based on the `Player`s error.
  18787. *
  18788. * @return {string}
  18789. * The `Player`s error message localized or an empty string.
  18790. */
  18791. content() {
  18792. const error = this.player().error();
  18793. return error ? this.localize(error.message) : '';
  18794. }
  18795. }
  18796. /**
  18797. * The default options for an `ErrorDisplay`.
  18798. *
  18799. * @private
  18800. */
  18801. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  18802. pauseOnOpen: false,
  18803. fillAlways: true,
  18804. temporary: false,
  18805. uncloseable: true
  18806. });
  18807. Component.registerComponent('ErrorDisplay', ErrorDisplay);
  18808. /** @import Player from './player' */
  18809. /** @import { ContentDescriptor } from '../utils/dom' */
  18810. /**
  18811. * Creates DOM element of 'select' & its options.
  18812. *
  18813. * @extends Component
  18814. */
  18815. class TextTrackSelect extends Component {
  18816. /**
  18817. * Creates an instance of this class.
  18818. *
  18819. * @param {Player} player
  18820. * The `Player` that this class should be attached to.
  18821. *
  18822. * @param {Object} [options]
  18823. * The key/value store of player options.
  18824. *
  18825. * @param {ContentDescriptor} [options.content=undefined]
  18826. * Provide customized content for this modal.
  18827. *
  18828. * @param {string} [options.legendId]
  18829. * A text with part of an string to create atribute of aria-labelledby.
  18830. *
  18831. * @param {string} [options.id]
  18832. * A text with part of an string to create atribute of aria-labelledby.
  18833. *
  18834. * @param {Array} [options.SelectOptions]
  18835. * Array that contains the value & textContent of for each of the
  18836. * options elements.
  18837. */
  18838. constructor(player, options = {}) {
  18839. super(player, options);
  18840. this.el_.setAttribute('aria-labelledby', this.selectLabelledbyIds);
  18841. }
  18842. /**
  18843. * Create the `TextTrackSelect`'s DOM element
  18844. *
  18845. * @return {Element}
  18846. * The DOM element that gets created.
  18847. */
  18848. createEl() {
  18849. this.selectLabelledbyIds = [this.options_.legendId, this.options_.labelId].join(' ').trim();
  18850. // Create select & inner options
  18851. const selectoptions = createEl('select', {
  18852. id: this.options_.id
  18853. }, {}, this.options_.SelectOptions.map(optionText => {
  18854. // Constructs an id for the <option>.
  18855. // For the colour settings that have two <selects> with a <label> each, generates an id based off the label value
  18856. // For font size/family and edge style with one <select> and no <label>, generates an id with a guid
  18857. const optionId = (this.options_.labelId ? this.options_.labelId : `vjs-track-option-${newGUID()}`) + '-' + optionText[1].replace(/\W+/g, '');
  18858. const option = createEl('option', {
  18859. id: optionId,
  18860. value: this.localize(optionText[0]),
  18861. textContent: this.localize(optionText[1])
  18862. });
  18863. option.setAttribute('aria-labelledby', `${this.selectLabelledbyIds} ${optionId}`);
  18864. return option;
  18865. }));
  18866. return selectoptions;
  18867. }
  18868. }
  18869. Component.registerComponent('TextTrackSelect', TextTrackSelect);
  18870. /** @import Player from './player' */
  18871. /** @import { ContentDescriptor } from '../utils/dom' */
  18872. /**
  18873. * Creates fieldset section of 'TextTrackSettings'.
  18874. * Manganes two versions of fieldsets, one for type of 'colors'
  18875. * & the other for 'font', Component adds diferent DOM elements
  18876. * to that fieldset depending on the type.
  18877. *
  18878. * @extends Component
  18879. */
  18880. class TextTrackFieldset extends Component {
  18881. /**
  18882. * Creates an instance of this class.
  18883. *
  18884. * @param {Player} player
  18885. * The `Player` that this class should be attached to.
  18886. *
  18887. * @param {Object} [options]
  18888. * The key/value store of player options.
  18889. *
  18890. * @param {ContentDescriptor} [options.content=undefined]
  18891. * Provide customized content for this modal.
  18892. *
  18893. * @param {string} [options.legendId]
  18894. * A text with part of an string to create atribute of aria-labelledby.
  18895. * It passes to 'TextTrackSelect'.
  18896. *
  18897. * @param {string} [options.id]
  18898. * A text with part of an string to create atribute of aria-labelledby.
  18899. * It passes to 'TextTrackSelect'.
  18900. *
  18901. * @param {string} [options.legendText]
  18902. * A text to use as the text content of the legend element.
  18903. *
  18904. * @param {Array} [options.selects]
  18905. * Array that contains the selects that are use to create 'selects'
  18906. * components.
  18907. *
  18908. * @param {Array} [options.SelectOptions]
  18909. * Array that contains the value & textContent of for each of the
  18910. * options elements, it passes to 'TextTrackSelect'.
  18911. *
  18912. * @param {string} [options.type]
  18913. * Conditions if some DOM elements will be added to the fieldset
  18914. * component.
  18915. *
  18916. * @param {Object} [options.selectConfigs]
  18917. * Object with the following properties that are the selects configurations:
  18918. * backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,
  18919. * fontPercent, textOpacity, windowColor, windowOpacity.
  18920. * These properties are use to configure the 'TextTrackSelect' Component.
  18921. */
  18922. constructor(player, options = {}) {
  18923. super(player, options);
  18924. // Add Components & DOM Elements
  18925. const legendElement = createEl('legend', {
  18926. textContent: this.localize(this.options_.legendText),
  18927. id: this.options_.legendId
  18928. });
  18929. this.el().appendChild(legendElement);
  18930. const selects = this.options_.selects;
  18931. // Iterate array of selects to create 'selects' components
  18932. for (const i of selects) {
  18933. const selectConfig = this.options_.selectConfigs[i];
  18934. const selectClassName = selectConfig.className;
  18935. const id = selectConfig.id.replace('%s', this.options_.id_);
  18936. let span = null;
  18937. const guid = `vjs_select_${newGUID()}`;
  18938. // Conditionally create span to add on the component
  18939. if (this.options_.type === 'colors') {
  18940. span = createEl('span', {
  18941. className: selectClassName
  18942. });
  18943. const label = createEl('label', {
  18944. id,
  18945. className: 'vjs-label',
  18946. textContent: this.localize(selectConfig.label)
  18947. });
  18948. label.setAttribute('for', guid);
  18949. span.appendChild(label);
  18950. }
  18951. const textTrackSelect = new TextTrackSelect(player, {
  18952. SelectOptions: selectConfig.options,
  18953. legendId: this.options_.legendId,
  18954. id: guid,
  18955. labelId: id
  18956. });
  18957. this.addChild(textTrackSelect);
  18958. // Conditionally append to 'select' component to conditionally created span
  18959. if (this.options_.type === 'colors') {
  18960. span.appendChild(textTrackSelect.el());
  18961. this.el().appendChild(span);
  18962. }
  18963. }
  18964. }
  18965. /**
  18966. * Create the `TextTrackFieldset`'s DOM element
  18967. *
  18968. * @return {Element}
  18969. * The DOM element that gets created.
  18970. */
  18971. createEl() {
  18972. const el = createEl('fieldset', {
  18973. // Prefixing classes of elements within a player with "vjs-"
  18974. // is a convention used in Video.js.
  18975. className: this.options_.className
  18976. });
  18977. return el;
  18978. }
  18979. }
  18980. Component.registerComponent('TextTrackFieldset', TextTrackFieldset);
  18981. /** @import Player from './player' */
  18982. /** @import { ContentDescriptor } from '../utils/dom' */
  18983. /**
  18984. * The component 'TextTrackSettingsColors' displays a set of 'fieldsets'
  18985. * using the component 'TextTrackFieldset'.
  18986. *
  18987. * @extends Component
  18988. */
  18989. class TextTrackSettingsColors extends Component {
  18990. /**
  18991. * Creates an instance of this class.
  18992. *
  18993. * @param {Player} player
  18994. * The `Player` that this class should be attached to.
  18995. *
  18996. * @param {Object} [options]
  18997. * The key/value store of player options.
  18998. *
  18999. * @param {ContentDescriptor} [options.content=undefined]
  19000. * Provide customized content for this modal.
  19001. *
  19002. * @param {Array} [options.fieldSets]
  19003. * Array that contains the configurations for the selects.
  19004. *
  19005. * @param {Object} [options.selectConfigs]
  19006. * Object with the following properties that are the select confugations:
  19007. * backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,
  19008. * fontPercent, textOpacity, windowColor, windowOpacity.
  19009. * it passes to 'TextTrackFieldset'.
  19010. */
  19011. constructor(player, options = {}) {
  19012. super(player, options);
  19013. const id_ = this.options_.textTrackComponentid;
  19014. // createElFgColor_
  19015. const ElFgColorFieldset = new TextTrackFieldset(player, {
  19016. id_,
  19017. legendId: `captions-text-legend-${id_}`,
  19018. legendText: this.localize('Text'),
  19019. className: 'vjs-fg vjs-track-setting',
  19020. selects: this.options_.fieldSets[0],
  19021. selectConfigs: this.options_.selectConfigs,
  19022. type: 'colors'
  19023. });
  19024. this.addChild(ElFgColorFieldset);
  19025. // createElBgColor_
  19026. const ElBgColorFieldset = new TextTrackFieldset(player, {
  19027. id_,
  19028. legendId: `captions-background-${id_}`,
  19029. legendText: this.localize('Text Background'),
  19030. className: 'vjs-bg vjs-track-setting',
  19031. selects: this.options_.fieldSets[1],
  19032. selectConfigs: this.options_.selectConfigs,
  19033. type: 'colors'
  19034. });
  19035. this.addChild(ElBgColorFieldset);
  19036. // createElWinColor_
  19037. const ElWinColorFieldset = new TextTrackFieldset(player, {
  19038. id_,
  19039. legendId: `captions-window-${id_}`,
  19040. legendText: this.localize('Caption Area Background'),
  19041. className: 'vjs-window vjs-track-setting',
  19042. selects: this.options_.fieldSets[2],
  19043. selectConfigs: this.options_.selectConfigs,
  19044. type: 'colors'
  19045. });
  19046. this.addChild(ElWinColorFieldset);
  19047. }
  19048. /**
  19049. * Create the `TextTrackSettingsColors`'s DOM element
  19050. *
  19051. * @return {Element}
  19052. * The DOM element that gets created.
  19053. */
  19054. createEl() {
  19055. const el = createEl('div', {
  19056. className: 'vjs-track-settings-colors'
  19057. });
  19058. return el;
  19059. }
  19060. }
  19061. Component.registerComponent('TextTrackSettingsColors', TextTrackSettingsColors);
  19062. /** @import Player from './player' */
  19063. /** @import { ContentDescriptor } from '../utils/dom' */
  19064. /**
  19065. * The component 'TextTrackSettingsFont' displays a set of 'fieldsets'
  19066. * using the component 'TextTrackFieldset'.
  19067. *
  19068. * @extends Component
  19069. */
  19070. class TextTrackSettingsFont extends Component {
  19071. /**
  19072. * Creates an instance of this class.
  19073. *
  19074. * @param {Player} player
  19075. * The `Player` that this class should be attached to.
  19076. *
  19077. * @param {Object} [options]
  19078. * The key/value store of player options.
  19079. *
  19080. * @param {ContentDescriptor} [options.content=undefined]
  19081. * Provide customized content for this modal.
  19082. *
  19083. * @param {Array} [options.fieldSets]
  19084. * Array that contains the configurations for the selects.
  19085. *
  19086. * @param {Object} [options.selectConfigs]
  19087. * Object with the following properties that are the select confugations:
  19088. * backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,
  19089. * fontPercent, textOpacity, windowColor, windowOpacity.
  19090. * it passes to 'TextTrackFieldset'.
  19091. */
  19092. constructor(player, options = {}) {
  19093. super(player, options);
  19094. const id_ = this.options_.textTrackComponentid;
  19095. const ElFgColorFieldset = new TextTrackFieldset(player, {
  19096. id_,
  19097. legendId: `captions-font-size-${id_}`,
  19098. legendText: 'Font Size',
  19099. className: 'vjs-font-percent vjs-track-setting',
  19100. selects: this.options_.fieldSets[0],
  19101. selectConfigs: this.options_.selectConfigs,
  19102. type: 'font'
  19103. });
  19104. this.addChild(ElFgColorFieldset);
  19105. const ElBgColorFieldset = new TextTrackFieldset(player, {
  19106. id_,
  19107. legendId: `captions-edge-style-${id_}`,
  19108. legendText: this.localize('Text Edge Style'),
  19109. className: 'vjs-edge-style vjs-track-setting',
  19110. selects: this.options_.fieldSets[1],
  19111. selectConfigs: this.options_.selectConfigs,
  19112. type: 'font'
  19113. });
  19114. this.addChild(ElBgColorFieldset);
  19115. const ElWinColorFieldset = new TextTrackFieldset(player, {
  19116. id_,
  19117. legendId: `captions-font-family-${id_}`,
  19118. legendText: this.localize('Font Family'),
  19119. className: 'vjs-font-family vjs-track-setting',
  19120. selects: this.options_.fieldSets[2],
  19121. selectConfigs: this.options_.selectConfigs,
  19122. type: 'font'
  19123. });
  19124. this.addChild(ElWinColorFieldset);
  19125. }
  19126. /**
  19127. * Create the `TextTrackSettingsFont`'s DOM element
  19128. *
  19129. * @return {Element}
  19130. * The DOM element that gets created.
  19131. */
  19132. createEl() {
  19133. const el = createEl('div', {
  19134. className: 'vjs-track-settings-font'
  19135. });
  19136. return el;
  19137. }
  19138. }
  19139. Component.registerComponent('TextTrackSettingsFont', TextTrackSettingsFont);
  19140. /**
  19141. * Buttons of reset & done that modal 'TextTrackSettings'
  19142. * uses as part of its content.
  19143. *
  19144. * 'Reset': Resets all settings on 'TextTrackSettings'.
  19145. * 'Done': Closes 'TextTrackSettings' modal.
  19146. *
  19147. * @extends Component
  19148. */
  19149. class TrackSettingsControls extends Component {
  19150. constructor(player, options = {}) {
  19151. super(player, options);
  19152. // Create DOM elements
  19153. const defaultsDescription = this.localize('restore all settings to the default values');
  19154. const resetButton = new Button(player, {
  19155. controlText: defaultsDescription,
  19156. className: 'vjs-default-button'
  19157. });
  19158. resetButton.el().classList.remove('vjs-control', 'vjs-button');
  19159. resetButton.el().textContent = this.localize('Reset');
  19160. this.addChild(resetButton);
  19161. const doneButton = new Button(player, {
  19162. controlText: defaultsDescription,
  19163. className: 'vjs-done-button'
  19164. });
  19165. // Remove unrequired style classes
  19166. doneButton.el().classList.remove('vjs-control', 'vjs-button');
  19167. doneButton.el().textContent = this.localize('Done');
  19168. this.addChild(doneButton);
  19169. }
  19170. /**
  19171. * Create the `TrackSettingsControls`'s DOM element
  19172. *
  19173. * @return {Element}
  19174. * The DOM element that gets created.
  19175. */
  19176. createEl() {
  19177. const el = createEl('div', {
  19178. className: 'vjs-track-settings-controls'
  19179. });
  19180. return el;
  19181. }
  19182. }
  19183. Component.registerComponent('TrackSettingsControls', TrackSettingsControls);
  19184. /**
  19185. * @file text-track-settings.js
  19186. */
  19187. /** @import Player from '../player' */
  19188. const LOCAL_STORAGE_KEY = 'vjs-text-track-settings';
  19189. const COLOR_BLACK = ['#000', 'Black'];
  19190. const COLOR_BLUE = ['#00F', 'Blue'];
  19191. const COLOR_CYAN = ['#0FF', 'Cyan'];
  19192. const COLOR_GREEN = ['#0F0', 'Green'];
  19193. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  19194. const COLOR_RED = ['#F00', 'Red'];
  19195. const COLOR_WHITE = ['#FFF', 'White'];
  19196. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  19197. const OPACITY_OPAQUE = ['1', 'Opaque'];
  19198. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  19199. const OPACITY_TRANS = ['0', 'Transparent'];
  19200. // Configuration for the various <select> elements in the DOM of this component.
  19201. //
  19202. // Possible keys include:
  19203. //
  19204. // `default`:
  19205. // The default option index. Only needs to be provided if not zero.
  19206. // `parser`:
  19207. // A function which is used to parse the value from the selected option in
  19208. // a customized way.
  19209. // `selector`:
  19210. // The selector used to find the associated <select> element.
  19211. const selectConfigs = {
  19212. backgroundColor: {
  19213. selector: '.vjs-bg-color > select',
  19214. id: 'captions-background-color-%s',
  19215. label: 'Color',
  19216. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN],
  19217. className: 'vjs-bg-color'
  19218. },
  19219. backgroundOpacity: {
  19220. selector: '.vjs-bg-opacity > select',
  19221. id: 'captions-background-opacity-%s',
  19222. label: 'Opacity',
  19223. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS],
  19224. className: 'vjs-bg-opacity vjs-opacity'
  19225. },
  19226. color: {
  19227. selector: '.vjs-text-color > select',
  19228. id: 'captions-foreground-color-%s',
  19229. label: 'Color',
  19230. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN],
  19231. className: 'vjs-text-color'
  19232. },
  19233. edgeStyle: {
  19234. selector: '.vjs-edge-style > select',
  19235. id: '',
  19236. label: 'Text Edge Style',
  19237. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Drop shadow']]
  19238. },
  19239. fontFamily: {
  19240. selector: '.vjs-font-family > select',
  19241. id: '',
  19242. label: 'Font Family',
  19243. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  19244. },
  19245. fontPercent: {
  19246. selector: '.vjs-font-percent > select',
  19247. id: '',
  19248. label: 'Font Size',
  19249. options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],
  19250. default: 2,
  19251. parser: v => v === '1.00' ? null : Number(v)
  19252. },
  19253. textOpacity: {
  19254. selector: '.vjs-text-opacity > select',
  19255. id: 'captions-foreground-opacity-%s',
  19256. label: 'Opacity',
  19257. options: [OPACITY_OPAQUE, OPACITY_SEMI],
  19258. className: 'vjs-text-opacity vjs-opacity'
  19259. },
  19260. // Options for this object are defined below.
  19261. windowColor: {
  19262. selector: '.vjs-window-color > select',
  19263. id: 'captions-window-color-%s',
  19264. label: 'Color',
  19265. className: 'vjs-window-color'
  19266. },
  19267. // Options for this object are defined below.
  19268. windowOpacity: {
  19269. selector: '.vjs-window-opacity > select',
  19270. id: 'captions-window-opacity-%s',
  19271. label: 'Opacity',
  19272. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE],
  19273. className: 'vjs-window-opacity vjs-opacity'
  19274. }
  19275. };
  19276. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  19277. /**
  19278. * Get the actual value of an option.
  19279. *
  19280. * @param {string} value
  19281. * The value to get
  19282. *
  19283. * @param {Function} [parser]
  19284. * Optional function to adjust the value.
  19285. *
  19286. * @return {*}
  19287. * - Will be `undefined` if no value exists
  19288. * - Will be `undefined` if the given value is "none".
  19289. * - Will be the actual value otherwise.
  19290. *
  19291. * @private
  19292. */
  19293. function parseOptionValue(value, parser) {
  19294. if (parser) {
  19295. value = parser(value);
  19296. }
  19297. if (value && value !== 'none') {
  19298. return value;
  19299. }
  19300. }
  19301. /**
  19302. * Gets the value of the selected <option> element within a <select> element.
  19303. *
  19304. * @param {Element} el
  19305. * the element to look in
  19306. *
  19307. * @param {Function} [parser]
  19308. * Optional function to adjust the value.
  19309. *
  19310. * @return {*}
  19311. * - Will be `undefined` if no value exists
  19312. * - Will be `undefined` if the given value is "none".
  19313. * - Will be the actual value otherwise.
  19314. *
  19315. * @private
  19316. */
  19317. function getSelectedOptionValue(el, parser) {
  19318. const value = el.options[el.options.selectedIndex].value;
  19319. return parseOptionValue(value, parser);
  19320. }
  19321. /**
  19322. * Sets the selected <option> element within a <select> element based on a
  19323. * given value.
  19324. *
  19325. * @param {Element} el
  19326. * The element to look in.
  19327. *
  19328. * @param {string} value
  19329. * the property to look on.
  19330. *
  19331. * @param {Function} [parser]
  19332. * Optional function to adjust the value before comparing.
  19333. *
  19334. * @private
  19335. */
  19336. function setSelectedOption(el, value, parser) {
  19337. if (!value) {
  19338. return;
  19339. }
  19340. for (let i = 0; i < el.options.length; i++) {
  19341. if (parseOptionValue(el.options[i].value, parser) === value) {
  19342. el.selectedIndex = i;
  19343. break;
  19344. }
  19345. }
  19346. }
  19347. /**
  19348. * Manipulate Text Tracks settings.
  19349. *
  19350. * @extends ModalDialog
  19351. */
  19352. class TextTrackSettings extends ModalDialog {
  19353. /**
  19354. * Creates an instance of this class.
  19355. *
  19356. * @param {Player} player
  19357. * The `Player` that this class should be attached to.
  19358. *
  19359. * @param {Object} [options]
  19360. * The key/value store of player options.
  19361. */
  19362. constructor(player, options) {
  19363. options.temporary = false;
  19364. super(player, options);
  19365. this.updateDisplay = this.updateDisplay.bind(this);
  19366. // fill the modal and pretend we have opened it
  19367. this.fill();
  19368. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  19369. this.renderModalComponents(player);
  19370. this.endDialog = createEl('p', {
  19371. className: 'vjs-control-text',
  19372. textContent: this.localize('End of dialog window.')
  19373. });
  19374. this.el().appendChild(this.endDialog);
  19375. this.setDefaults();
  19376. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  19377. if (options.persistTextTrackSettings === undefined) {
  19378. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  19379. }
  19380. this.bindFunctionsToSelectsAndButtons();
  19381. if (this.options_.persistTextTrackSettings) {
  19382. this.restoreSettings();
  19383. }
  19384. }
  19385. renderModalComponents(player) {
  19386. const textTrackSettingsColors = new TextTrackSettingsColors(player, {
  19387. textTrackComponentid: this.id_,
  19388. selectConfigs,
  19389. fieldSets: [['color', 'textOpacity'], ['backgroundColor', 'backgroundOpacity'], ['windowColor', 'windowOpacity']]
  19390. });
  19391. this.addChild(textTrackSettingsColors);
  19392. const textTrackSettingsFont = new TextTrackSettingsFont(player, {
  19393. textTrackComponentid: this.id_,
  19394. selectConfigs,
  19395. fieldSets: [['fontPercent'], ['edgeStyle'], ['fontFamily']]
  19396. });
  19397. this.addChild(textTrackSettingsFont);
  19398. const trackSettingsControls = new TrackSettingsControls(player);
  19399. this.addChild(trackSettingsControls);
  19400. }
  19401. bindFunctionsToSelectsAndButtons() {
  19402. this.on(this.$('.vjs-done-button'), ['click', 'tap'], () => {
  19403. this.saveSettings();
  19404. this.close();
  19405. });
  19406. this.on(this.$('.vjs-default-button'), ['click', 'tap'], () => {
  19407. this.setDefaults();
  19408. this.updateDisplay();
  19409. });
  19410. each(selectConfigs, config => {
  19411. this.on(this.$(config.selector), 'change', this.updateDisplay);
  19412. });
  19413. }
  19414. dispose() {
  19415. this.endDialog = null;
  19416. super.dispose();
  19417. }
  19418. label() {
  19419. return this.localize('Caption Settings Dialog');
  19420. }
  19421. description() {
  19422. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  19423. }
  19424. buildCSSClass() {
  19425. return super.buildCSSClass() + ' vjs-text-track-settings';
  19426. }
  19427. /**
  19428. * Gets an object of text track settings (or null).
  19429. *
  19430. * @return {Object}
  19431. * An object with config values parsed from the DOM or localStorage.
  19432. */
  19433. getValues() {
  19434. return reduce(selectConfigs, (accum, config, key) => {
  19435. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  19436. if (value !== undefined) {
  19437. accum[key] = value;
  19438. }
  19439. return accum;
  19440. }, {});
  19441. }
  19442. /**
  19443. * Sets text track settings from an object of values.
  19444. *
  19445. * @param {Object} values
  19446. * An object with config values parsed from the DOM or localStorage.
  19447. */
  19448. setValues(values) {
  19449. each(selectConfigs, (config, key) => {
  19450. setSelectedOption(this.$(config.selector), values[key], config.parser);
  19451. });
  19452. }
  19453. /**
  19454. * Sets all `<select>` elements to their default values.
  19455. */
  19456. setDefaults() {
  19457. each(selectConfigs, config => {
  19458. const index = config.hasOwnProperty('default') ? config.default : 0;
  19459. this.$(config.selector).selectedIndex = index;
  19460. });
  19461. }
  19462. /**
  19463. * Restore texttrack settings from localStorage
  19464. */
  19465. restoreSettings() {
  19466. let values;
  19467. try {
  19468. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY));
  19469. } catch (err) {
  19470. log.warn(err);
  19471. }
  19472. if (values) {
  19473. this.setValues(values);
  19474. }
  19475. }
  19476. /**
  19477. * Save text track settings to localStorage
  19478. */
  19479. saveSettings() {
  19480. if (!this.options_.persistTextTrackSettings) {
  19481. return;
  19482. }
  19483. const values = this.getValues();
  19484. try {
  19485. if (Object.keys(values).length) {
  19486. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values));
  19487. } else {
  19488. window.localStorage.removeItem(LOCAL_STORAGE_KEY);
  19489. }
  19490. } catch (err) {
  19491. log.warn(err);
  19492. }
  19493. }
  19494. /**
  19495. * Update display of text track settings
  19496. */
  19497. updateDisplay() {
  19498. const ttDisplay = this.player_.getChild('textTrackDisplay');
  19499. if (ttDisplay) {
  19500. ttDisplay.updateDisplay();
  19501. }
  19502. }
  19503. /**
  19504. * Repopulate dialog with new localizations on languagechange
  19505. */
  19506. handleLanguagechange() {
  19507. this.fill();
  19508. this.renderModalComponents(this.player_);
  19509. this.bindFunctionsToSelectsAndButtons();
  19510. }
  19511. }
  19512. Component.registerComponent('TextTrackSettings', TextTrackSettings);
  19513. /**
  19514. * @file resize-manager.js
  19515. */
  19516. /**
  19517. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  19518. *
  19519. * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.
  19520. *
  19521. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  19522. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  19523. *
  19524. * @example <caption>How to disable the resize manager</caption>
  19525. * const player = videojs('#vid', {
  19526. * resizeManager: false
  19527. * });
  19528. *
  19529. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  19530. *
  19531. * @extends Component
  19532. */
  19533. class ResizeManager extends Component {
  19534. /**
  19535. * Create the ResizeManager.
  19536. *
  19537. * @param {Object} player
  19538. * The `Player` that this class should be attached to.
  19539. *
  19540. * @param {Object} [options]
  19541. * The key/value store of ResizeManager options.
  19542. *
  19543. * @param {Object} [options.ResizeObserver]
  19544. * A polyfill for ResizeObserver can be passed in here.
  19545. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  19546. */
  19547. constructor(player, options) {
  19548. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
  19549. // if `null` was passed, we want to disable the ResizeObserver
  19550. if (options.ResizeObserver === null) {
  19551. RESIZE_OBSERVER_AVAILABLE = false;
  19552. }
  19553. // Only create an element when ResizeObserver isn't available
  19554. const options_ = merge({
  19555. createEl: !RESIZE_OBSERVER_AVAILABLE,
  19556. reportTouchActivity: false
  19557. }, options);
  19558. super(player, options_);
  19559. this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  19560. this.loadListener_ = null;
  19561. this.resizeObserver_ = null;
  19562. this.debouncedHandler_ = debounce(() => {
  19563. this.resizeHandler();
  19564. }, 100, false, this);
  19565. if (RESIZE_OBSERVER_AVAILABLE) {
  19566. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  19567. this.resizeObserver_.observe(player.el());
  19568. } else {
  19569. this.loadListener_ = () => {
  19570. if (!this.el_ || !this.el_.contentWindow) {
  19571. return;
  19572. }
  19573. const debouncedHandler_ = this.debouncedHandler_;
  19574. let unloadListener_ = this.unloadListener_ = function () {
  19575. off(this, 'resize', debouncedHandler_);
  19576. off(this, 'unload', unloadListener_);
  19577. unloadListener_ = null;
  19578. };
  19579. // safari and edge can unload the iframe before resizemanager dispose
  19580. // we have to dispose of event handlers correctly before that happens
  19581. on(this.el_.contentWindow, 'unload', unloadListener_);
  19582. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  19583. };
  19584. this.one('load', this.loadListener_);
  19585. }
  19586. }
  19587. createEl() {
  19588. return super.createEl('iframe', {
  19589. className: 'vjs-resize-manager',
  19590. tabIndex: -1,
  19591. title: this.localize('No content')
  19592. }, {
  19593. 'aria-hidden': 'true'
  19594. });
  19595. }
  19596. /**
  19597. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  19598. *
  19599. * @fires Player#playerresize
  19600. */
  19601. resizeHandler() {
  19602. /**
  19603. * Called when the player size has changed
  19604. *
  19605. * @event Player#playerresize
  19606. * @type {Event}
  19607. */
  19608. // make sure player is still around to trigger
  19609. // prevents this from causing an error after dispose
  19610. if (!this.player_ || !this.player_.trigger) {
  19611. return;
  19612. }
  19613. this.player_.trigger('playerresize');
  19614. }
  19615. dispose() {
  19616. if (this.debouncedHandler_) {
  19617. this.debouncedHandler_.cancel();
  19618. }
  19619. if (this.resizeObserver_) {
  19620. if (this.player_.el()) {
  19621. this.resizeObserver_.unobserve(this.player_.el());
  19622. }
  19623. this.resizeObserver_.disconnect();
  19624. }
  19625. if (this.loadListener_) {
  19626. this.off('load', this.loadListener_);
  19627. }
  19628. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  19629. this.unloadListener_.call(this.el_.contentWindow);
  19630. }
  19631. this.ResizeObserver = null;
  19632. this.resizeObserver = null;
  19633. this.debouncedHandler_ = null;
  19634. this.loadListener_ = null;
  19635. super.dispose();
  19636. }
  19637. }
  19638. Component.registerComponent('ResizeManager', ResizeManager);
  19639. /** @import Player from './player' */
  19640. const defaults$1 = {
  19641. trackingThreshold: 20,
  19642. liveTolerance: 15
  19643. };
  19644. /*
  19645. track when we are at the live edge, and other helpers for live playback */
  19646. /**
  19647. * A class for checking live current time and determining when the player
  19648. * is at or behind the live edge.
  19649. */
  19650. class LiveTracker extends Component {
  19651. /**
  19652. * Creates an instance of this class.
  19653. *
  19654. * @param {Player} player
  19655. * The `Player` that this class should be attached to.
  19656. *
  19657. * @param {Object} [options]
  19658. * The key/value store of player options.
  19659. *
  19660. * @param {number} [options.trackingThreshold=20]
  19661. * Number of seconds of live window (seekableEnd - seekableStart) that
  19662. * media needs to have before the liveui will be shown.
  19663. *
  19664. * @param {number} [options.liveTolerance=15]
  19665. * Number of seconds behind live that we have to be
  19666. * before we will be considered non-live. Note that this will only
  19667. * be used when playing at the live edge. This allows large seekable end
  19668. * changes to not effect whether we are live or not.
  19669. */
  19670. constructor(player, options) {
  19671. // LiveTracker does not need an element
  19672. const options_ = merge(defaults$1, options, {
  19673. createEl: false
  19674. });
  19675. super(player, options_);
  19676. this.trackLiveHandler_ = () => this.trackLive_();
  19677. this.handlePlay_ = e => this.handlePlay(e);
  19678. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  19679. this.handleSeeked_ = e => this.handleSeeked(e);
  19680. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  19681. this.reset_();
  19682. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  19683. // we should try to toggle tracking on canplay as native playback engines, like Safari
  19684. // may not have the proper values for things like seekableEnd until then
  19685. this.on(this.player_, 'canplay', () => this.toggleTracking());
  19686. }
  19687. /**
  19688. * all the functionality for tracking when seek end changes
  19689. * and for tracking how far past seek end we should be
  19690. */
  19691. trackLive_() {
  19692. const seekable = this.player_.seekable();
  19693. // skip undefined seekable
  19694. if (!seekable || !seekable.length) {
  19695. return;
  19696. }
  19697. const newTime = Number(window.performance.now().toFixed(4));
  19698. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  19699. this.lastTime_ = newTime;
  19700. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  19701. const liveCurrentTime = this.liveCurrentTime();
  19702. const currentTime = this.player_.currentTime();
  19703. // we are behind live if any are true
  19704. // 1. the player is paused
  19705. // 2. the user seeked to a location 2 seconds away from live
  19706. // 3. the difference between live and current time is greater
  19707. // liveTolerance which defaults to 15s
  19708. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  19709. // we cannot be behind if
  19710. // 1. until we have not seen a timeupdate yet
  19711. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  19712. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  19713. isBehind = false;
  19714. }
  19715. if (isBehind !== this.behindLiveEdge_) {
  19716. this.behindLiveEdge_ = isBehind;
  19717. this.trigger('liveedgechange');
  19718. }
  19719. }
  19720. /**
  19721. * handle a durationchange event on the player
  19722. * and start/stop tracking accordingly.
  19723. */
  19724. handleDurationchange() {
  19725. this.toggleTracking();
  19726. }
  19727. /**
  19728. * start/stop tracking
  19729. */
  19730. toggleTracking() {
  19731. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  19732. if (this.player_.options_.liveui) {
  19733. this.player_.addClass('vjs-liveui');
  19734. }
  19735. this.startTracking();
  19736. } else {
  19737. this.player_.removeClass('vjs-liveui');
  19738. this.stopTracking();
  19739. }
  19740. }
  19741. /**
  19742. * start tracking live playback
  19743. */
  19744. startTracking() {
  19745. if (this.isTracking()) {
  19746. return;
  19747. }
  19748. // If we haven't seen a timeupdate, we need to check whether playback
  19749. // began before this component started tracking. This can happen commonly
  19750. // when using autoplay.
  19751. if (!this.timeupdateSeen_) {
  19752. this.timeupdateSeen_ = this.player_.hasStarted();
  19753. }
  19754. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  19755. this.trackLive_();
  19756. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  19757. if (!this.timeupdateSeen_) {
  19758. this.one(this.player_, 'play', this.handlePlay_);
  19759. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  19760. } else {
  19761. this.on(this.player_, 'seeked', this.handleSeeked_);
  19762. }
  19763. }
  19764. /**
  19765. * handle the first timeupdate on the player if it wasn't already playing
  19766. * when live tracker started tracking.
  19767. */
  19768. handleFirstTimeupdate() {
  19769. this.timeupdateSeen_ = true;
  19770. this.on(this.player_, 'seeked', this.handleSeeked_);
  19771. }
  19772. /**
  19773. * Keep track of what time a seek starts, and listen for seeked
  19774. * to find where a seek ends.
  19775. */
  19776. handleSeeked() {
  19777. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  19778. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  19779. this.nextSeekedFromUser_ = false;
  19780. this.trackLive_();
  19781. }
  19782. /**
  19783. * handle the first play on the player, and make sure that we seek
  19784. * right to the live edge.
  19785. */
  19786. handlePlay() {
  19787. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  19788. }
  19789. /**
  19790. * Stop tracking, and set all internal variables to
  19791. * their initial value.
  19792. */
  19793. reset_() {
  19794. this.lastTime_ = -1;
  19795. this.pastSeekEnd_ = 0;
  19796. this.lastSeekEnd_ = -1;
  19797. this.behindLiveEdge_ = true;
  19798. this.timeupdateSeen_ = false;
  19799. this.seekedBehindLive_ = false;
  19800. this.nextSeekedFromUser_ = false;
  19801. this.clearInterval(this.trackingInterval_);
  19802. this.trackingInterval_ = null;
  19803. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  19804. this.off(this.player_, 'seeked', this.handleSeeked_);
  19805. this.off(this.player_, 'play', this.handlePlay_);
  19806. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  19807. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  19808. }
  19809. /**
  19810. * The next seeked event is from the user. Meaning that any seek
  19811. * > 2s behind live will be considered behind live for real and
  19812. * liveTolerance will be ignored.
  19813. */
  19814. nextSeekedFromUser() {
  19815. this.nextSeekedFromUser_ = true;
  19816. }
  19817. /**
  19818. * stop tracking live playback
  19819. */
  19820. stopTracking() {
  19821. if (!this.isTracking()) {
  19822. return;
  19823. }
  19824. this.reset_();
  19825. this.trigger('liveedgechange');
  19826. }
  19827. /**
  19828. * A helper to get the player seekable end
  19829. * so that we don't have to null check everywhere
  19830. *
  19831. * @return {number}
  19832. * The furthest seekable end or Infinity.
  19833. */
  19834. seekableEnd() {
  19835. const seekable = this.player_.seekable();
  19836. const seekableEnds = [];
  19837. let i = seekable ? seekable.length : 0;
  19838. while (i--) {
  19839. seekableEnds.push(seekable.end(i));
  19840. }
  19841. // grab the furthest seekable end after sorting, or if there are none
  19842. // default to Infinity
  19843. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  19844. }
  19845. /**
  19846. * A helper to get the player seekable start
  19847. * so that we don't have to null check everywhere
  19848. *
  19849. * @return {number}
  19850. * The earliest seekable start or 0.
  19851. */
  19852. seekableStart() {
  19853. const seekable = this.player_.seekable();
  19854. const seekableStarts = [];
  19855. let i = seekable ? seekable.length : 0;
  19856. while (i--) {
  19857. seekableStarts.push(seekable.start(i));
  19858. }
  19859. // grab the first seekable start after sorting, or if there are none
  19860. // default to 0
  19861. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  19862. }
  19863. /**
  19864. * Get the live time window aka
  19865. * the amount of time between seekable start and
  19866. * live current time.
  19867. *
  19868. * @return {number}
  19869. * The amount of seconds that are seekable in
  19870. * the live video.
  19871. */
  19872. liveWindow() {
  19873. const liveCurrentTime = this.liveCurrentTime();
  19874. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  19875. if (liveCurrentTime === Infinity) {
  19876. return 0;
  19877. }
  19878. return liveCurrentTime - this.seekableStart();
  19879. }
  19880. /**
  19881. * Determines if the player is live, only checks if this component
  19882. * is tracking live playback or not
  19883. *
  19884. * @return {boolean}
  19885. * Whether liveTracker is tracking
  19886. */
  19887. isLive() {
  19888. return this.isTracking();
  19889. }
  19890. /**
  19891. * Determines if currentTime is at the live edge and won't fall behind
  19892. * on each seekableendchange
  19893. *
  19894. * @return {boolean}
  19895. * Whether playback is at the live edge
  19896. */
  19897. atLiveEdge() {
  19898. return !this.behindLiveEdge();
  19899. }
  19900. /**
  19901. * get what we expect the live current time to be
  19902. *
  19903. * @return {number}
  19904. * The expected live current time
  19905. */
  19906. liveCurrentTime() {
  19907. return this.pastSeekEnd() + this.seekableEnd();
  19908. }
  19909. /**
  19910. * The number of seconds that have occurred after seekable end
  19911. * changed. This will be reset to 0 once seekable end changes.
  19912. *
  19913. * @return {number}
  19914. * Seconds past the current seekable end
  19915. */
  19916. pastSeekEnd() {
  19917. const seekableEnd = this.seekableEnd();
  19918. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  19919. this.pastSeekEnd_ = 0;
  19920. }
  19921. this.lastSeekEnd_ = seekableEnd;
  19922. return this.pastSeekEnd_;
  19923. }
  19924. /**
  19925. * If we are currently behind the live edge, aka currentTime will be
  19926. * behind on a seekableendchange
  19927. *
  19928. * @return {boolean}
  19929. * If we are behind the live edge
  19930. */
  19931. behindLiveEdge() {
  19932. return this.behindLiveEdge_;
  19933. }
  19934. /**
  19935. * Whether live tracker is currently tracking or not.
  19936. */
  19937. isTracking() {
  19938. return typeof this.trackingInterval_ === 'number';
  19939. }
  19940. /**
  19941. * Seek to the live edge if we are behind the live edge
  19942. */
  19943. seekToLiveEdge() {
  19944. this.seekedBehindLive_ = false;
  19945. if (this.atLiveEdge()) {
  19946. return;
  19947. }
  19948. this.nextSeekedFromUser_ = false;
  19949. this.player_.currentTime(this.liveCurrentTime());
  19950. }
  19951. /**
  19952. * Dispose of liveTracker
  19953. */
  19954. dispose() {
  19955. this.stopTracking();
  19956. super.dispose();
  19957. }
  19958. }
  19959. Component.registerComponent('LiveTracker', LiveTracker);
  19960. /**
  19961. * Displays an element over the player which contains an optional title and
  19962. * description for the current content.
  19963. *
  19964. * Much of the code for this component originated in the now obsolete
  19965. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  19966. *
  19967. * @extends Component
  19968. */
  19969. class TitleBar extends Component {
  19970. constructor(player, options) {
  19971. super(player, options);
  19972. this.on('statechanged', e => this.updateDom_());
  19973. this.updateDom_();
  19974. }
  19975. /**
  19976. * Create the `TitleBar`'s DOM element
  19977. *
  19978. * @return {Element}
  19979. * The element that was created.
  19980. */
  19981. createEl() {
  19982. this.els = {
  19983. title: createEl('div', {
  19984. className: 'vjs-title-bar-title',
  19985. id: `vjs-title-bar-title-${newGUID()}`
  19986. }),
  19987. description: createEl('div', {
  19988. className: 'vjs-title-bar-description',
  19989. id: `vjs-title-bar-description-${newGUID()}`
  19990. })
  19991. };
  19992. return createEl('div', {
  19993. className: 'vjs-title-bar'
  19994. }, {}, values(this.els));
  19995. }
  19996. /**
  19997. * Updates the DOM based on the component's state object.
  19998. */
  19999. updateDom_() {
  20000. const tech = this.player_.tech_;
  20001. const techEl = tech && tech.el_;
  20002. const techAriaAttrs = {
  20003. title: 'aria-labelledby',
  20004. description: 'aria-describedby'
  20005. };
  20006. ['title', 'description'].forEach(k => {
  20007. const value = this.state[k];
  20008. const el = this.els[k];
  20009. const techAriaAttr = techAriaAttrs[k];
  20010. emptyEl(el);
  20011. if (value) {
  20012. textContent(el, value);
  20013. }
  20014. // If there is a tech element available, update its ARIA attributes
  20015. // according to whether a title and/or description have been provided.
  20016. if (techEl) {
  20017. techEl.removeAttribute(techAriaAttr);
  20018. if (value) {
  20019. techEl.setAttribute(techAriaAttr, el.id);
  20020. }
  20021. }
  20022. });
  20023. if (this.state.title || this.state.description) {
  20024. this.show();
  20025. } else {
  20026. this.hide();
  20027. }
  20028. }
  20029. /**
  20030. * Update the contents of the title bar component with new title and
  20031. * description text.
  20032. *
  20033. * If both title and description are missing, the title bar will be hidden.
  20034. *
  20035. * If either title or description are present, the title bar will be visible.
  20036. *
  20037. * NOTE: Any previously set value will be preserved. To unset a previously
  20038. * set value, you must pass an empty string or null.
  20039. *
  20040. * For example:
  20041. *
  20042. * ```
  20043. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  20044. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  20045. * update({title: ''}) // title: '', description: 'bar2'
  20046. * update({title: 'foo', description: null}) // title: 'foo', description: null
  20047. * ```
  20048. *
  20049. * @param {Object} [options={}]
  20050. * An options object. When empty, the title bar will be hidden.
  20051. *
  20052. * @param {string} [options.title]
  20053. * A title to display in the title bar.
  20054. *
  20055. * @param {string} [options.description]
  20056. * A description to display in the title bar.
  20057. */
  20058. update(options) {
  20059. this.setState(options);
  20060. }
  20061. /**
  20062. * Dispose the component.
  20063. */
  20064. dispose() {
  20065. const tech = this.player_.tech_;
  20066. const techEl = tech && tech.el_;
  20067. if (techEl) {
  20068. techEl.removeAttribute('aria-labelledby');
  20069. techEl.removeAttribute('aria-describedby');
  20070. }
  20071. super.dispose();
  20072. this.els = null;
  20073. }
  20074. }
  20075. Component.registerComponent('TitleBar', TitleBar);
  20076. /** @import Player from './player' */
  20077. /**
  20078. * @typedef {object} TransientButtonOptions
  20079. * @property {string} [controlText] Control text, usually visible for these buttons
  20080. * @property {number} [initialDisplay=4000] Time in ms that button should initially remain visible
  20081. * @property {Array<'top'|'neartop'|'bottom'|'left'|'right'>} [position] Array of position strings to add basic styles for positioning
  20082. * @property {string} [className] Class(es) to add
  20083. * @property {boolean} [takeFocus=false] Whether element sohuld take focus when shown
  20084. * @property {Function} [clickHandler] Function called on button activation
  20085. */
  20086. /** @type {TransientButtonOptions} */
  20087. const defaults = {
  20088. initialDisplay: 4000,
  20089. position: [],
  20090. takeFocus: false
  20091. };
  20092. /**
  20093. * A floating transient button.
  20094. * It's recommended to insert these buttons _before_ the control bar with the this argument to `addChild`
  20095. * for a logical tab order.
  20096. *
  20097. * @example
  20098. * ```
  20099. * player.addChild(
  20100. * 'TransientButton',
  20101. * options,
  20102. * player.children().indexOf(player.getChild("ControlBar"))
  20103. * )
  20104. * ```
  20105. *
  20106. * @extends Button
  20107. */
  20108. class TransientButton extends Button {
  20109. /**
  20110. * TransientButton constructor
  20111. *
  20112. * @param {Player} player The button's player
  20113. * @param {TransientButtonOptions} options Options for the transient button
  20114. */
  20115. constructor(player, options) {
  20116. options = merge(defaults, options);
  20117. super(player, options);
  20118. this.controlText(options.controlText);
  20119. this.hide();
  20120. // When shown, the float button will be visible even if the user is inactive.
  20121. // Clear this if there is any interaction.
  20122. this.on(this.player_, ['useractive', 'userinactive'], e => {
  20123. this.removeClass('force-display');
  20124. });
  20125. }
  20126. /**
  20127. * Return CSS class including position classes
  20128. *
  20129. * @return {string} CSS class list
  20130. */
  20131. buildCSSClass() {
  20132. return `vjs-transient-button focus-visible ${this.options_.position.map(c => `vjs-${c}`).join(' ')}`;
  20133. }
  20134. /**
  20135. * Create the button element
  20136. *
  20137. * @return {HTMLButtonElement} The button element
  20138. */
  20139. createEl() {
  20140. /** @type HTMLButtonElement */
  20141. const el = createEl('button', {}, {
  20142. type: 'button',
  20143. class: this.buildCSSClass()
  20144. }, createEl('span'));
  20145. this.controlTextEl_ = el.querySelector('span');
  20146. return el;
  20147. }
  20148. /**
  20149. * Show the button. The button will remain visible for the `initialDisplay` time, default 4s,
  20150. * and when there is user activity.
  20151. */
  20152. show() {
  20153. super.show();
  20154. this.addClass('force-display');
  20155. if (this.options_.takeFocus) {
  20156. this.el().focus({
  20157. preventScroll: true
  20158. });
  20159. }
  20160. this.forceDisplayTimeout = this.player_.setTimeout(() => {
  20161. this.removeClass('force-display');
  20162. }, this.options_.initialDisplay);
  20163. }
  20164. /**
  20165. * Hide the display, even if during the `initialDisplay` time.
  20166. */
  20167. hide() {
  20168. this.removeClass('force-display');
  20169. super.hide();
  20170. }
  20171. /**
  20172. * Dispose the component
  20173. */
  20174. dispose() {
  20175. this.player_.clearTimeout(this.forceDisplayTimeout);
  20176. super.dispose();
  20177. }
  20178. }
  20179. Component.registerComponent('TransientButton', TransientButton);
  20180. /** @import Html5 from './html5' */
  20181. /**
  20182. * This function is used to fire a sourceset when there is something
  20183. * similar to `mediaEl.load()` being called. It will try to find the source via
  20184. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  20185. * with the source that was found or empty string if we cannot know. If it cannot
  20186. * find a source then `sourceset` will not be fired.
  20187. *
  20188. * @param {Html5} tech
  20189. * The tech object that sourceset was setup on
  20190. *
  20191. * @return {boolean}
  20192. * returns false if the sourceset was not fired and true otherwise.
  20193. */
  20194. const sourcesetLoad = tech => {
  20195. const el = tech.el();
  20196. // if `el.src` is set, that source will be loaded.
  20197. if (el.hasAttribute('src')) {
  20198. tech.triggerSourceset(el.src);
  20199. return true;
  20200. }
  20201. /**
  20202. * Since there isn't a src property on the media element, source elements will be used for
  20203. * implementing the source selection algorithm. This happens asynchronously and
  20204. * for most cases were there is more than one source we cannot tell what source will
  20205. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  20206. * going to do that. There are three special cases that we do handle here though:
  20207. *
  20208. * 1. If there are no sources, do not fire `sourceset`.
  20209. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  20210. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  20211. * That will be our src.
  20212. */
  20213. const sources = tech.$$('source');
  20214. const srcUrls = [];
  20215. let src = '';
  20216. // if there are no sources, do not fire sourceset
  20217. if (!sources.length) {
  20218. return false;
  20219. }
  20220. // only count valid/non-duplicate source elements
  20221. for (let i = 0; i < sources.length; i++) {
  20222. const url = sources[i].src;
  20223. if (url && srcUrls.indexOf(url) === -1) {
  20224. srcUrls.push(url);
  20225. }
  20226. }
  20227. // there were no valid sources
  20228. if (!srcUrls.length) {
  20229. return false;
  20230. }
  20231. // there is only one valid source element url
  20232. // use that
  20233. if (srcUrls.length === 1) {
  20234. src = srcUrls[0];
  20235. }
  20236. tech.triggerSourceset(src);
  20237. return true;
  20238. };
  20239. /**
  20240. * our implementation of an `innerHTML` descriptor for browsers
  20241. * that do not have one.
  20242. */
  20243. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  20244. get() {
  20245. return this.cloneNode(true).innerHTML;
  20246. },
  20247. set(v) {
  20248. // make a dummy node to use innerHTML on
  20249. const dummy = document.createElement(this.nodeName.toLowerCase());
  20250. // set innerHTML to the value provided
  20251. dummy.innerHTML = v;
  20252. // make a document fragment to hold the nodes from dummy
  20253. const docFrag = document.createDocumentFragment();
  20254. // copy all of the nodes created by the innerHTML on dummy
  20255. // to the document fragment
  20256. while (dummy.childNodes.length) {
  20257. docFrag.appendChild(dummy.childNodes[0]);
  20258. }
  20259. // remove content
  20260. this.innerText = '';
  20261. // now we add all of that html in one by appending the
  20262. // document fragment. This is how innerHTML does it.
  20263. window.Element.prototype.appendChild.call(this, docFrag);
  20264. // then return the result that innerHTML's setter would
  20265. return this.innerHTML;
  20266. }
  20267. });
  20268. /**
  20269. * Get a property descriptor given a list of priorities and the
  20270. * property to get.
  20271. */
  20272. const getDescriptor = (priority, prop) => {
  20273. let descriptor = {};
  20274. for (let i = 0; i < priority.length; i++) {
  20275. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  20276. if (descriptor && descriptor.set && descriptor.get) {
  20277. break;
  20278. }
  20279. }
  20280. descriptor.enumerable = true;
  20281. descriptor.configurable = true;
  20282. return descriptor;
  20283. };
  20284. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  20285. /**
  20286. * Patches browser internal functions so that we can tell synchronously
  20287. * if a `<source>` was appended to the media element. For some reason this
  20288. * causes a `sourceset` if the the media element is ready and has no source.
  20289. * This happens when:
  20290. * - The page has just loaded and the media element does not have a source.
  20291. * - The media element was emptied of all sources, then `load()` was called.
  20292. *
  20293. * It does this by patching the following functions/properties when they are supported:
  20294. *
  20295. * - `append()` - can be used to add a `<source>` element to the media element
  20296. * - `appendChild()` - can be used to add a `<source>` element to the media element
  20297. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  20298. * - `innerHTML` - can be used to add a `<source>` element to the media element
  20299. *
  20300. * @param {Html5} tech
  20301. * The tech object that sourceset is being setup on.
  20302. */
  20303. const firstSourceWatch = function (tech) {
  20304. const el = tech.el();
  20305. // make sure firstSourceWatch isn't setup twice.
  20306. if (el.resetSourceWatch_) {
  20307. return;
  20308. }
  20309. const old = {};
  20310. const innerDescriptor = getInnerHTMLDescriptor(tech);
  20311. const appendWrapper = appendFn => (...args) => {
  20312. const retval = appendFn.apply(el, args);
  20313. sourcesetLoad(tech);
  20314. return retval;
  20315. };
  20316. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  20317. if (!el[k]) {
  20318. return;
  20319. }
  20320. // store the old function
  20321. old[k] = el[k];
  20322. // call the old function with a sourceset if a source
  20323. // was loaded
  20324. el[k] = appendWrapper(old[k]);
  20325. });
  20326. Object.defineProperty(el, 'innerHTML', merge(innerDescriptor, {
  20327. set: appendWrapper(innerDescriptor.set)
  20328. }));
  20329. el.resetSourceWatch_ = () => {
  20330. el.resetSourceWatch_ = null;
  20331. Object.keys(old).forEach(k => {
  20332. el[k] = old[k];
  20333. });
  20334. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  20335. };
  20336. // on the first sourceset, we need to revert our changes
  20337. tech.one('sourceset', el.resetSourceWatch_);
  20338. };
  20339. /**
  20340. * our implementation of a `src` descriptor for browsers
  20341. * that do not have one
  20342. */
  20343. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  20344. get() {
  20345. if (this.hasAttribute('src')) {
  20346. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  20347. }
  20348. return '';
  20349. },
  20350. set(v) {
  20351. window.Element.prototype.setAttribute.call(this, 'src', v);
  20352. return v;
  20353. }
  20354. });
  20355. const getSrcDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  20356. /**
  20357. * setup `sourceset` handling on the `Html5` tech. This function
  20358. * patches the following element properties/functions:
  20359. *
  20360. * - `src` - to determine when `src` is set
  20361. * - `setAttribute()` - to determine when `src` is set
  20362. * - `load()` - this re-triggers the source selection algorithm, and can
  20363. * cause a sourceset.
  20364. *
  20365. * If there is no source when we are adding `sourceset` support or during a `load()`
  20366. * we also patch the functions listed in `firstSourceWatch`.
  20367. *
  20368. * @param {Html5} tech
  20369. * The tech to patch
  20370. */
  20371. const setupSourceset = function (tech) {
  20372. if (!tech.featuresSourceset) {
  20373. return;
  20374. }
  20375. const el = tech.el();
  20376. // make sure sourceset isn't setup twice.
  20377. if (el.resetSourceset_) {
  20378. return;
  20379. }
  20380. const srcDescriptor = getSrcDescriptor(tech);
  20381. const oldSetAttribute = el.setAttribute;
  20382. const oldLoad = el.load;
  20383. Object.defineProperty(el, 'src', merge(srcDescriptor, {
  20384. set: v => {
  20385. const retval = srcDescriptor.set.call(el, v);
  20386. // we use the getter here to get the actual value set on src
  20387. tech.triggerSourceset(el.src);
  20388. return retval;
  20389. }
  20390. }));
  20391. el.setAttribute = (n, v) => {
  20392. const retval = oldSetAttribute.call(el, n, v);
  20393. if (/src/i.test(n)) {
  20394. tech.triggerSourceset(el.src);
  20395. }
  20396. return retval;
  20397. };
  20398. el.load = () => {
  20399. const retval = oldLoad.call(el);
  20400. // if load was called, but there was no source to fire
  20401. // sourceset on. We have to watch for a source append
  20402. // as that can trigger a `sourceset` when the media element
  20403. // has no source
  20404. if (!sourcesetLoad(tech)) {
  20405. tech.triggerSourceset('');
  20406. firstSourceWatch(tech);
  20407. }
  20408. return retval;
  20409. };
  20410. if (el.currentSrc) {
  20411. tech.triggerSourceset(el.currentSrc);
  20412. } else if (!sourcesetLoad(tech)) {
  20413. firstSourceWatch(tech);
  20414. }
  20415. el.resetSourceset_ = () => {
  20416. el.resetSourceset_ = null;
  20417. el.load = oldLoad;
  20418. el.setAttribute = oldSetAttribute;
  20419. Object.defineProperty(el, 'src', srcDescriptor);
  20420. if (el.resetSourceWatch_) {
  20421. el.resetSourceWatch_();
  20422. }
  20423. };
  20424. };
  20425. /**
  20426. * @file html5.js
  20427. */
  20428. /**
  20429. * HTML5 Media Controller - Wrapper for HTML5 Media API
  20430. *
  20431. * @mixes Tech~SourceHandlerAdditions
  20432. * @extends Tech
  20433. */
  20434. class Html5 extends Tech {
  20435. /**
  20436. * Create an instance of this Tech.
  20437. *
  20438. * @param {Object} [options]
  20439. * The key/value store of player options.
  20440. *
  20441. * @param {Function} [ready]
  20442. * Callback function to call when the `HTML5` Tech is ready.
  20443. */
  20444. constructor(options, ready) {
  20445. super(options, ready);
  20446. const source = options.source;
  20447. let crossoriginTracks = false;
  20448. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  20449. // Set the source if one is provided
  20450. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  20451. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  20452. // anyway so the error gets fired.
  20453. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  20454. this.setSource(source);
  20455. } else {
  20456. this.handleLateInit_(this.el_);
  20457. }
  20458. // setup sourceset after late sourceset/init
  20459. if (options.enableSourceset) {
  20460. this.setupSourcesetHandling_();
  20461. }
  20462. this.isScrubbing_ = false;
  20463. if (this.el_.hasChildNodes()) {
  20464. const nodes = this.el_.childNodes;
  20465. let nodesLength = nodes.length;
  20466. const removeNodes = [];
  20467. while (nodesLength--) {
  20468. const node = nodes[nodesLength];
  20469. const nodeName = node.nodeName.toLowerCase();
  20470. if (nodeName === 'track') {
  20471. if (!this.featuresNativeTextTracks) {
  20472. // Empty video tag tracks so the built-in player doesn't use them also.
  20473. // This may not be fast enough to stop HTML5 browsers from reading the tags
  20474. // so we'll need to turn off any default tracks if we're manually doing
  20475. // captions and subtitles. videoElement.textTracks
  20476. removeNodes.push(node);
  20477. } else {
  20478. // store HTMLTrackElement and TextTrack to remote list
  20479. this.remoteTextTrackEls().addTrackElement_(node);
  20480. this.remoteTextTracks().addTrack(node.track);
  20481. this.textTracks().addTrack(node.track);
  20482. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  20483. crossoriginTracks = true;
  20484. }
  20485. }
  20486. }
  20487. }
  20488. for (let i = 0; i < removeNodes.length; i++) {
  20489. this.el_.removeChild(removeNodes[i]);
  20490. }
  20491. }
  20492. this.proxyNativeTracks_();
  20493. if (this.featuresNativeTextTracks && crossoriginTracks) {
  20494. log.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n' + 'This may prevent text tracks from loading.');
  20495. }
  20496. // prevent iOS Safari from disabling metadata text tracks during native playback
  20497. this.restoreMetadataTracksInIOSNativePlayer_();
  20498. // Determine if native controls should be used
  20499. // Our goal should be to get the custom controls on mobile solid everywhere
  20500. // so we can remove this all together. Right now this will block custom
  20501. // controls on touch enabled laptops like the Chrome Pixel
  20502. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  20503. this.setControls(true);
  20504. }
  20505. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  20506. // into a `fullscreenchange` event
  20507. this.proxyWebkitFullscreen_();
  20508. this.triggerReady();
  20509. }
  20510. /**
  20511. * Dispose of `HTML5` media element and remove all tracks.
  20512. */
  20513. dispose() {
  20514. if (this.el_ && this.el_.resetSourceset_) {
  20515. this.el_.resetSourceset_();
  20516. }
  20517. Html5.disposeMediaElement(this.el_);
  20518. this.options_ = null;
  20519. // tech will handle clearing of the emulated track list
  20520. super.dispose();
  20521. }
  20522. /**
  20523. * Modify the media element so that we can detect when
  20524. * the source is changed. Fires `sourceset` just after the source has changed
  20525. */
  20526. setupSourcesetHandling_() {
  20527. setupSourceset(this);
  20528. }
  20529. /**
  20530. * When a captions track is enabled in the iOS Safari native player, all other
  20531. * tracks are disabled (including metadata tracks), which nulls all of their
  20532. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  20533. * state in those cases so that cue points are not needlessly lost.
  20534. *
  20535. * @private
  20536. */
  20537. restoreMetadataTracksInIOSNativePlayer_() {
  20538. const textTracks = this.textTracks();
  20539. let metadataTracksPreFullscreenState;
  20540. // captures a snapshot of every metadata track's current state
  20541. const takeMetadataTrackSnapshot = () => {
  20542. metadataTracksPreFullscreenState = [];
  20543. for (let i = 0; i < textTracks.length; i++) {
  20544. const track = textTracks[i];
  20545. if (track.kind === 'metadata') {
  20546. metadataTracksPreFullscreenState.push({
  20547. track,
  20548. storedMode: track.mode
  20549. });
  20550. }
  20551. }
  20552. };
  20553. // snapshot each metadata track's initial state, and update the snapshot
  20554. // each time there is a track 'change' event
  20555. takeMetadataTrackSnapshot();
  20556. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  20557. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  20558. const restoreTrackMode = () => {
  20559. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  20560. const storedTrack = metadataTracksPreFullscreenState[i];
  20561. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  20562. storedTrack.track.mode = storedTrack.storedMode;
  20563. }
  20564. }
  20565. // we only want this handler to be executed on the first 'change' event
  20566. textTracks.removeEventListener('change', restoreTrackMode);
  20567. };
  20568. // when we enter fullscreen playback, stop updating the snapshot and
  20569. // restore all track modes to their pre-fullscreen state
  20570. this.on('webkitbeginfullscreen', () => {
  20571. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  20572. // remove the listener before adding it just in case it wasn't previously removed
  20573. textTracks.removeEventListener('change', restoreTrackMode);
  20574. textTracks.addEventListener('change', restoreTrackMode);
  20575. });
  20576. // start updating the snapshot again after leaving fullscreen
  20577. this.on('webkitendfullscreen', () => {
  20578. // remove the listener before adding it just in case it wasn't previously removed
  20579. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  20580. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  20581. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  20582. textTracks.removeEventListener('change', restoreTrackMode);
  20583. });
  20584. }
  20585. /**
  20586. * Attempt to force override of tracks for the given type
  20587. *
  20588. * @param {string} type - Track type to override, possible values include 'Audio',
  20589. * 'Video', and 'Text'.
  20590. * @param {boolean} override - If set to true native audio/video will be overridden,
  20591. * otherwise native audio/video will potentially be used.
  20592. * @private
  20593. */
  20594. overrideNative_(type, override) {
  20595. // If there is no behavioral change don't add/remove listeners
  20596. if (override !== this[`featuresNative${type}Tracks`]) {
  20597. return;
  20598. }
  20599. const lowerCaseType = type.toLowerCase();
  20600. if (this[`${lowerCaseType}TracksListeners_`]) {
  20601. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  20602. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  20603. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  20604. });
  20605. }
  20606. this[`featuresNative${type}Tracks`] = !override;
  20607. this[`${lowerCaseType}TracksListeners_`] = null;
  20608. this.proxyNativeTracksForType_(lowerCaseType);
  20609. }
  20610. /**
  20611. * Attempt to force override of native audio tracks.
  20612. *
  20613. * @param {boolean} override - If set to true native audio will be overridden,
  20614. * otherwise native audio will potentially be used.
  20615. */
  20616. overrideNativeAudioTracks(override) {
  20617. this.overrideNative_('Audio', override);
  20618. }
  20619. /**
  20620. * Attempt to force override of native video tracks.
  20621. *
  20622. * @param {boolean} override - If set to true native video will be overridden,
  20623. * otherwise native video will potentially be used.
  20624. */
  20625. overrideNativeVideoTracks(override) {
  20626. this.overrideNative_('Video', override);
  20627. }
  20628. /**
  20629. * Proxy native track list events for the given type to our track
  20630. * lists if the browser we are playing in supports that type of track list.
  20631. *
  20632. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  20633. * @private
  20634. */
  20635. proxyNativeTracksForType_(name) {
  20636. const props = NORMAL[name];
  20637. const elTracks = this.el()[props.getterName];
  20638. const techTracks = this[props.getterName]();
  20639. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  20640. return;
  20641. }
  20642. const listeners = {
  20643. change: e => {
  20644. const event = {
  20645. type: 'change',
  20646. target: techTracks,
  20647. currentTarget: techTracks,
  20648. srcElement: techTracks
  20649. };
  20650. techTracks.trigger(event);
  20651. // if we are a text track change event, we should also notify the
  20652. // remote text track list. This can potentially cause a false positive
  20653. // if we were to get a change event on a non-remote track and
  20654. // we triggered the event on the remote text track list which doesn't
  20655. // contain that track. However, best practices mean looping through the
  20656. // list of tracks and searching for the appropriate mode value, so,
  20657. // this shouldn't pose an issue
  20658. if (name === 'text') {
  20659. this[REMOTE.remoteText.getterName]().trigger(event);
  20660. }
  20661. },
  20662. addtrack(e) {
  20663. techTracks.addTrack(e.track);
  20664. },
  20665. removetrack(e) {
  20666. techTracks.removeTrack(e.track);
  20667. }
  20668. };
  20669. const removeOldTracks = function () {
  20670. const removeTracks = [];
  20671. for (let i = 0; i < techTracks.length; i++) {
  20672. let found = false;
  20673. for (let j = 0; j < elTracks.length; j++) {
  20674. if (elTracks[j] === techTracks[i]) {
  20675. found = true;
  20676. break;
  20677. }
  20678. }
  20679. if (!found) {
  20680. removeTracks.push(techTracks[i]);
  20681. }
  20682. }
  20683. while (removeTracks.length) {
  20684. techTracks.removeTrack(removeTracks.shift());
  20685. }
  20686. };
  20687. this[props.getterName + 'Listeners_'] = listeners;
  20688. Object.keys(listeners).forEach(eventName => {
  20689. const listener = listeners[eventName];
  20690. elTracks.addEventListener(eventName, listener);
  20691. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  20692. });
  20693. // Remove (native) tracks that are not used anymore
  20694. this.on('loadstart', removeOldTracks);
  20695. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  20696. }
  20697. /**
  20698. * Proxy all native track list events to our track lists if the browser we are playing
  20699. * in supports that type of track list.
  20700. *
  20701. * @private
  20702. */
  20703. proxyNativeTracks_() {
  20704. NORMAL.names.forEach(name => {
  20705. this.proxyNativeTracksForType_(name);
  20706. });
  20707. }
  20708. /**
  20709. * Create the `Html5` Tech's DOM element.
  20710. *
  20711. * @return {Element}
  20712. * The element that gets created.
  20713. */
  20714. createEl() {
  20715. let el = this.options_.tag;
  20716. // Check if this browser supports moving the element into the box.
  20717. // On the iPhone video will break if you move the element,
  20718. // So we have to create a brand new element.
  20719. // If we ingested the player div, we do not need to move the media element.
  20720. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  20721. // If the original tag is still there, clone and remove it.
  20722. if (el) {
  20723. const clone = el.cloneNode(true);
  20724. if (el.parentNode) {
  20725. el.parentNode.insertBefore(clone, el);
  20726. }
  20727. Html5.disposeMediaElement(el);
  20728. el = clone;
  20729. } else {
  20730. el = document.createElement('video');
  20731. // determine if native controls should be used
  20732. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  20733. const attributes = merge({}, tagAttributes);
  20734. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  20735. delete attributes.controls;
  20736. }
  20737. setAttributes(el, Object.assign(attributes, {
  20738. id: this.options_.techId,
  20739. class: 'vjs-tech'
  20740. }));
  20741. }
  20742. el.playerId = this.options_.playerId;
  20743. }
  20744. if (typeof this.options_.preload !== 'undefined') {
  20745. setAttribute(el, 'preload', this.options_.preload);
  20746. }
  20747. if (this.options_.disablePictureInPicture !== undefined) {
  20748. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  20749. }
  20750. // Update specific tag settings, in case they were overridden
  20751. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  20752. // when iOS/Safari or other browsers attempt to autoplay.
  20753. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  20754. for (let i = 0; i < settingsAttrs.length; i++) {
  20755. const attr = settingsAttrs[i];
  20756. const value = this.options_[attr];
  20757. if (typeof value !== 'undefined') {
  20758. if (value) {
  20759. setAttribute(el, attr, attr);
  20760. } else {
  20761. removeAttribute(el, attr);
  20762. }
  20763. el[attr] = value;
  20764. }
  20765. }
  20766. return el;
  20767. }
  20768. /**
  20769. * This will be triggered if the loadstart event has already fired, before videojs was
  20770. * ready. Two known examples of when this can happen are:
  20771. * 1. If we're loading the playback object after it has started loading
  20772. * 2. The media is already playing the (often with autoplay on) then
  20773. *
  20774. * This function will fire another loadstart so that videojs can catchup.
  20775. *
  20776. * @fires Tech#loadstart
  20777. *
  20778. * @return {undefined}
  20779. * returns nothing.
  20780. */
  20781. handleLateInit_(el) {
  20782. if (el.networkState === 0 || el.networkState === 3) {
  20783. // The video element hasn't started loading the source yet
  20784. // or didn't find a source
  20785. return;
  20786. }
  20787. if (el.readyState === 0) {
  20788. // NetworkState is set synchronously BUT loadstart is fired at the
  20789. // end of the current stack, usually before setInterval(fn, 0).
  20790. // So at this point we know loadstart may have already fired or is
  20791. // about to fire, and either way the player hasn't seen it yet.
  20792. // We don't want to fire loadstart prematurely here and cause a
  20793. // double loadstart so we'll wait and see if it happens between now
  20794. // and the next loop, and fire it if not.
  20795. // HOWEVER, we also want to make sure it fires before loadedmetadata
  20796. // which could also happen between now and the next loop, so we'll
  20797. // watch for that also.
  20798. let loadstartFired = false;
  20799. const setLoadstartFired = function () {
  20800. loadstartFired = true;
  20801. };
  20802. this.on('loadstart', setLoadstartFired);
  20803. const triggerLoadstart = function () {
  20804. // We did miss the original loadstart. Make sure the player
  20805. // sees loadstart before loadedmetadata
  20806. if (!loadstartFired) {
  20807. this.trigger('loadstart');
  20808. }
  20809. };
  20810. this.on('loadedmetadata', triggerLoadstart);
  20811. this.ready(function () {
  20812. this.off('loadstart', setLoadstartFired);
  20813. this.off('loadedmetadata', triggerLoadstart);
  20814. if (!loadstartFired) {
  20815. // We did miss the original native loadstart. Fire it now.
  20816. this.trigger('loadstart');
  20817. }
  20818. });
  20819. return;
  20820. }
  20821. // From here on we know that loadstart already fired and we missed it.
  20822. // The other readyState events aren't as much of a problem if we double
  20823. // them, so not going to go to as much trouble as loadstart to prevent
  20824. // that unless we find reason to.
  20825. const eventsToTrigger = ['loadstart'];
  20826. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  20827. eventsToTrigger.push('loadedmetadata');
  20828. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  20829. if (el.readyState >= 2) {
  20830. eventsToTrigger.push('loadeddata');
  20831. }
  20832. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  20833. if (el.readyState >= 3) {
  20834. eventsToTrigger.push('canplay');
  20835. }
  20836. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  20837. if (el.readyState >= 4) {
  20838. eventsToTrigger.push('canplaythrough');
  20839. }
  20840. // We still need to give the player time to add event listeners
  20841. this.ready(function () {
  20842. eventsToTrigger.forEach(function (type) {
  20843. this.trigger(type);
  20844. }, this);
  20845. });
  20846. }
  20847. /**
  20848. * Set whether we are scrubbing or not.
  20849. * This is used to decide whether we should use `fastSeek` or not.
  20850. * `fastSeek` is used to provide trick play on Safari browsers.
  20851. *
  20852. * @param {boolean} isScrubbing
  20853. * - true for we are currently scrubbing
  20854. * - false for we are no longer scrubbing
  20855. */
  20856. setScrubbing(isScrubbing) {
  20857. this.isScrubbing_ = isScrubbing;
  20858. }
  20859. /**
  20860. * Get whether we are scrubbing or not.
  20861. *
  20862. * @return {boolean} isScrubbing
  20863. * - true for we are currently scrubbing
  20864. * - false for we are no longer scrubbing
  20865. */
  20866. scrubbing() {
  20867. return this.isScrubbing_;
  20868. }
  20869. /**
  20870. * Set current time for the `HTML5` tech.
  20871. *
  20872. * @param {number} seconds
  20873. * Set the current time of the media to this.
  20874. */
  20875. setCurrentTime(seconds) {
  20876. try {
  20877. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  20878. this.el_.fastSeek(seconds);
  20879. } else {
  20880. this.el_.currentTime = seconds;
  20881. }
  20882. } catch (e) {
  20883. log(e, 'Video is not ready. (Video.js)');
  20884. // this.warning(VideoJS.warnings.videoNotReady);
  20885. }
  20886. }
  20887. /**
  20888. * Get the current duration of the HTML5 media element.
  20889. *
  20890. * @return {number}
  20891. * The duration of the media or 0 if there is no duration.
  20892. */
  20893. duration() {
  20894. // Android Chrome will report duration as Infinity for VOD HLS until after
  20895. // playback has started, which triggers the live display erroneously.
  20896. // Return NaN if playback has not started and trigger a durationupdate once
  20897. // the duration can be reliably known.
  20898. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  20899. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  20900. // several with 0
  20901. const checkProgress = () => {
  20902. if (this.el_.currentTime > 0) {
  20903. // Trigger durationchange for genuinely live video
  20904. if (this.el_.duration === Infinity) {
  20905. this.trigger('durationchange');
  20906. }
  20907. this.off('timeupdate', checkProgress);
  20908. }
  20909. };
  20910. this.on('timeupdate', checkProgress);
  20911. return NaN;
  20912. }
  20913. return this.el_.duration || NaN;
  20914. }
  20915. /**
  20916. * Get the current width of the HTML5 media element.
  20917. *
  20918. * @return {number}
  20919. * The width of the HTML5 media element.
  20920. */
  20921. width() {
  20922. return this.el_.offsetWidth;
  20923. }
  20924. /**
  20925. * Get the current height of the HTML5 media element.
  20926. *
  20927. * @return {number}
  20928. * The height of the HTML5 media element.
  20929. */
  20930. height() {
  20931. return this.el_.offsetHeight;
  20932. }
  20933. /**
  20934. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  20935. * `fullscreenchange` event.
  20936. *
  20937. * @private
  20938. * @fires fullscreenchange
  20939. * @listens webkitendfullscreen
  20940. * @listens webkitbeginfullscreen
  20941. * @listens webkitbeginfullscreen
  20942. */
  20943. proxyWebkitFullscreen_() {
  20944. if (!('webkitDisplayingFullscreen' in this.el_)) {
  20945. return;
  20946. }
  20947. const endFn = function () {
  20948. this.trigger('fullscreenchange', {
  20949. isFullscreen: false
  20950. });
  20951. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  20952. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  20953. this.el_.controls = false;
  20954. }
  20955. };
  20956. const beginFn = function () {
  20957. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  20958. this.one('webkitendfullscreen', endFn);
  20959. this.trigger('fullscreenchange', {
  20960. isFullscreen: true,
  20961. // set a flag in case another tech triggers fullscreenchange
  20962. nativeIOSFullscreen: true
  20963. });
  20964. }
  20965. };
  20966. this.on('webkitbeginfullscreen', beginFn);
  20967. this.on('dispose', () => {
  20968. this.off('webkitbeginfullscreen', beginFn);
  20969. this.off('webkitendfullscreen', endFn);
  20970. });
  20971. }
  20972. /**
  20973. * Check if fullscreen is supported on the video el.
  20974. *
  20975. * @return {boolean}
  20976. * - True if fullscreen is supported.
  20977. * - False if fullscreen is not supported.
  20978. */
  20979. supportsFullScreen() {
  20980. return typeof this.el_.webkitEnterFullScreen === 'function';
  20981. }
  20982. /**
  20983. * Request that the `HTML5` Tech enter fullscreen.
  20984. */
  20985. enterFullScreen() {
  20986. const video = this.el_;
  20987. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  20988. // attempt to prime the video element for programmatic access
  20989. // this isn't necessary on the desktop but shouldn't hurt
  20990. silencePromise(this.el_.play());
  20991. // playing and pausing synchronously during the transition to fullscreen
  20992. // can get iOS ~6.1 devices into a play/pause loop
  20993. this.setTimeout(function () {
  20994. video.pause();
  20995. try {
  20996. video.webkitEnterFullScreen();
  20997. } catch (e) {
  20998. this.trigger('fullscreenerror', e);
  20999. }
  21000. }, 0);
  21001. } else {
  21002. try {
  21003. video.webkitEnterFullScreen();
  21004. } catch (e) {
  21005. this.trigger('fullscreenerror', e);
  21006. }
  21007. }
  21008. }
  21009. /**
  21010. * Request that the `HTML5` Tech exit fullscreen.
  21011. */
  21012. exitFullScreen() {
  21013. if (!this.el_.webkitDisplayingFullscreen) {
  21014. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  21015. return;
  21016. }
  21017. this.el_.webkitExitFullScreen();
  21018. }
  21019. /**
  21020. * Create a floating video window always on top of other windows so that users may
  21021. * continue consuming media while they interact with other content sites, or
  21022. * applications on their device.
  21023. *
  21024. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21025. *
  21026. * @return {Promise}
  21027. * A promise with a Picture-in-Picture window.
  21028. */
  21029. requestPictureInPicture() {
  21030. return this.el_.requestPictureInPicture();
  21031. }
  21032. /**
  21033. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  21034. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  21035. * Needs to be checked later than the constructor
  21036. * This will be a false positive for clear sources loaded after a Fairplay source
  21037. *
  21038. * @param {function} cb function to call
  21039. * @return {number} id of request
  21040. */
  21041. requestVideoFrameCallback(cb) {
  21042. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  21043. return this.el_.requestVideoFrameCallback(cb);
  21044. }
  21045. return super.requestVideoFrameCallback(cb);
  21046. }
  21047. /**
  21048. * Native or fallback requestVideoFrameCallback
  21049. *
  21050. * @param {number} id request id to cancel
  21051. */
  21052. cancelVideoFrameCallback(id) {
  21053. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  21054. this.el_.cancelVideoFrameCallback(id);
  21055. } else {
  21056. super.cancelVideoFrameCallback(id);
  21057. }
  21058. }
  21059. /**
  21060. * A getter/setter for the `Html5` Tech's source object.
  21061. * > Note: Please use {@link Html5#setSource}
  21062. *
  21063. * @param {Tech~SourceObject} [src]
  21064. * The source object you want to set on the `HTML5` techs element.
  21065. *
  21066. * @return {Tech~SourceObject|undefined}
  21067. * - The current source object when a source is not passed in.
  21068. * - undefined when setting
  21069. *
  21070. * @deprecated Since version 5.
  21071. */
  21072. src(src) {
  21073. if (src === undefined) {
  21074. return this.el_.src;
  21075. }
  21076. // Setting src through `src` instead of `setSrc` will be deprecated
  21077. this.setSrc(src);
  21078. }
  21079. /**
  21080. * Add a <source> element to the <video> element.
  21081. *
  21082. * @param {string} srcUrl
  21083. * The URL of the video source.
  21084. *
  21085. * @param {string} [mimeType]
  21086. * The MIME type of the video source. Optional but recommended.
  21087. *
  21088. * @return {boolean}
  21089. * Returns true if the source element was successfully added, false otherwise.
  21090. */
  21091. addSourceElement(srcUrl, mimeType) {
  21092. if (!srcUrl) {
  21093. log.error('Invalid source URL.');
  21094. return false;
  21095. }
  21096. const sourceAttributes = {
  21097. src: srcUrl
  21098. };
  21099. if (mimeType) {
  21100. sourceAttributes.type = mimeType;
  21101. }
  21102. const sourceElement = createEl('source', {}, sourceAttributes);
  21103. this.el_.appendChild(sourceElement);
  21104. return true;
  21105. }
  21106. /**
  21107. * Remove a <source> element from the <video> element by its URL.
  21108. *
  21109. * @param {string} srcUrl
  21110. * The URL of the source to remove.
  21111. *
  21112. * @return {boolean}
  21113. * Returns true if the source element was successfully removed, false otherwise.
  21114. */
  21115. removeSourceElement(srcUrl) {
  21116. if (!srcUrl) {
  21117. log.error('Source URL is required to remove the source element.');
  21118. return false;
  21119. }
  21120. const sourceElements = this.el_.querySelectorAll('source');
  21121. for (const sourceElement of sourceElements) {
  21122. if (sourceElement.src === srcUrl) {
  21123. this.el_.removeChild(sourceElement);
  21124. return true;
  21125. }
  21126. }
  21127. log.warn(`No matching source element found with src: ${srcUrl}`);
  21128. return false;
  21129. }
  21130. /**
  21131. * Reset the tech by removing all sources and then calling
  21132. * {@link Html5.resetMediaElement}.
  21133. */
  21134. reset() {
  21135. Html5.resetMediaElement(this.el_);
  21136. }
  21137. /**
  21138. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  21139. * the HTML5 media element.
  21140. *
  21141. * @return {Tech~SourceObject}
  21142. * The current source object from the HTML5 tech. With a fallback to the
  21143. * elements source.
  21144. */
  21145. currentSrc() {
  21146. if (this.currentSource_) {
  21147. return this.currentSource_.src;
  21148. }
  21149. return this.el_.currentSrc;
  21150. }
  21151. /**
  21152. * Set controls attribute for the HTML5 media Element.
  21153. *
  21154. * @param {string} val
  21155. * Value to set the controls attribute to
  21156. */
  21157. setControls(val) {
  21158. this.el_.controls = !!val;
  21159. }
  21160. /**
  21161. * Create and returns a remote {@link TextTrack} object.
  21162. *
  21163. * @param {string} kind
  21164. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  21165. *
  21166. * @param {string} [label]
  21167. * Label to identify the text track
  21168. *
  21169. * @param {string} [language]
  21170. * Two letter language abbreviation
  21171. *
  21172. * @return {TextTrack}
  21173. * The TextTrack that gets created.
  21174. */
  21175. addTextTrack(kind, label, language) {
  21176. if (!this.featuresNativeTextTracks) {
  21177. return super.addTextTrack(kind, label, language);
  21178. }
  21179. return this.el_.addTextTrack(kind, label, language);
  21180. }
  21181. /**
  21182. * Creates either native TextTrack or an emulated TextTrack depending
  21183. * on the value of `featuresNativeTextTracks`
  21184. *
  21185. * @param {Object} options
  21186. * The object should contain the options to initialize the TextTrack with.
  21187. *
  21188. * @param {string} [options.kind]
  21189. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  21190. *
  21191. * @param {string} [options.label]
  21192. * Label to identify the text track
  21193. *
  21194. * @param {string} [options.language]
  21195. * Two letter language abbreviation.
  21196. *
  21197. * @param {boolean} [options.default]
  21198. * Default this track to on.
  21199. *
  21200. * @param {string} [options.id]
  21201. * The internal id to assign this track.
  21202. *
  21203. * @param {string} [options.src]
  21204. * A source url for the track.
  21205. *
  21206. * @return {HTMLTrackElement}
  21207. * The track element that gets created.
  21208. */
  21209. createRemoteTextTrack(options) {
  21210. if (!this.featuresNativeTextTracks) {
  21211. return super.createRemoteTextTrack(options);
  21212. }
  21213. const htmlTrackElement = document.createElement('track');
  21214. if (options.kind) {
  21215. htmlTrackElement.kind = options.kind;
  21216. }
  21217. if (options.label) {
  21218. htmlTrackElement.label = options.label;
  21219. }
  21220. if (options.language || options.srclang) {
  21221. htmlTrackElement.srclang = options.language || options.srclang;
  21222. }
  21223. if (options.default) {
  21224. htmlTrackElement.default = options.default;
  21225. }
  21226. if (options.id) {
  21227. htmlTrackElement.id = options.id;
  21228. }
  21229. if (options.src) {
  21230. htmlTrackElement.src = options.src;
  21231. }
  21232. return htmlTrackElement;
  21233. }
  21234. /**
  21235. * Creates a remote text track object and returns an html track element.
  21236. *
  21237. * @param {Object} options The object should contain values for
  21238. * kind, language, label, and src (location of the WebVTT file)
  21239. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  21240. * will not be removed from the TextTrackList and HtmlTrackElementList
  21241. * after a source change
  21242. * @return {HTMLTrackElement} An Html Track Element.
  21243. * This can be an emulated {@link HTMLTrackElement} or a native one.
  21244. *
  21245. */
  21246. addRemoteTextTrack(options, manualCleanup) {
  21247. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  21248. if (this.featuresNativeTextTracks) {
  21249. this.el().appendChild(htmlTrackElement);
  21250. }
  21251. return htmlTrackElement;
  21252. }
  21253. /**
  21254. * Remove remote `TextTrack` from `TextTrackList` object
  21255. *
  21256. * @param {TextTrack} track
  21257. * `TextTrack` object to remove
  21258. */
  21259. removeRemoteTextTrack(track) {
  21260. super.removeRemoteTextTrack(track);
  21261. if (this.featuresNativeTextTracks) {
  21262. const tracks = this.$$('track');
  21263. let i = tracks.length;
  21264. while (i--) {
  21265. if (track === tracks[i] || track === tracks[i].track) {
  21266. this.el().removeChild(tracks[i]);
  21267. }
  21268. }
  21269. }
  21270. }
  21271. /**
  21272. * Gets available media playback quality metrics as specified by the W3C's Media
  21273. * Playback Quality API.
  21274. *
  21275. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  21276. *
  21277. * @return {Object}
  21278. * An object with supported media playback quality metrics
  21279. */
  21280. getVideoPlaybackQuality() {
  21281. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  21282. return this.el().getVideoPlaybackQuality();
  21283. }
  21284. const videoPlaybackQuality = {};
  21285. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  21286. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  21287. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  21288. }
  21289. if (window.performance) {
  21290. videoPlaybackQuality.creationTime = window.performance.now();
  21291. }
  21292. return videoPlaybackQuality;
  21293. }
  21294. }
  21295. /* HTML5 Support Testing ---------------------------------------------------- */
  21296. /**
  21297. * Element for testing browser HTML5 media capabilities
  21298. *
  21299. * @type {Element}
  21300. * @constant
  21301. * @private
  21302. */
  21303. defineLazyProperty(Html5, 'TEST_VID', function () {
  21304. if (!isReal()) {
  21305. return;
  21306. }
  21307. const video = document.createElement('video');
  21308. const track = document.createElement('track');
  21309. track.kind = 'captions';
  21310. track.srclang = 'en';
  21311. track.label = 'English';
  21312. video.appendChild(track);
  21313. return video;
  21314. });
  21315. /**
  21316. * Check if HTML5 media is supported by this browser/device.
  21317. *
  21318. * @return {boolean}
  21319. * - True if HTML5 media is supported.
  21320. * - False if HTML5 media is not supported.
  21321. */
  21322. Html5.isSupported = function () {
  21323. // IE with no Media Player is a LIAR! (#984)
  21324. try {
  21325. Html5.TEST_VID.volume = 0.5;
  21326. } catch (e) {
  21327. return false;
  21328. }
  21329. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  21330. };
  21331. /**
  21332. * Check if the tech can support the given type
  21333. *
  21334. * @param {string} type
  21335. * The mimetype to check
  21336. * @return {string} 'probably', 'maybe', or '' (empty string)
  21337. */
  21338. Html5.canPlayType = function (type) {
  21339. return Html5.TEST_VID.canPlayType(type);
  21340. };
  21341. /**
  21342. * Check if the tech can support the given source
  21343. *
  21344. * @param {Object} srcObj
  21345. * The source object
  21346. * @param {Object} options
  21347. * The options passed to the tech
  21348. * @return {string} 'probably', 'maybe', or '' (empty string)
  21349. */
  21350. Html5.canPlaySource = function (srcObj, options) {
  21351. return Html5.canPlayType(srcObj.type);
  21352. };
  21353. /**
  21354. * Check if the volume can be changed in this browser/device.
  21355. * Volume cannot be changed in a lot of mobile devices.
  21356. * Specifically, it can't be changed from 1 on iOS.
  21357. *
  21358. * @return {boolean}
  21359. * - True if volume can be controlled
  21360. * - False otherwise
  21361. */
  21362. Html5.canControlVolume = function () {
  21363. // IE will error if Windows Media Player not installed #3315
  21364. try {
  21365. const volume = Html5.TEST_VID.volume;
  21366. Html5.TEST_VID.volume = volume / 2 + 0.1;
  21367. const canControl = volume !== Html5.TEST_VID.volume;
  21368. // With the introduction of iOS 15, there are cases where the volume is read as
  21369. // changed but reverts back to its original state at the start of the next tick.
  21370. // To determine whether volume can be controlled on iOS,
  21371. // a timeout is set and the volume is checked asynchronously.
  21372. // Since `features` doesn't currently work asynchronously, the value is manually set.
  21373. if (canControl && IS_IOS) {
  21374. window.setTimeout(() => {
  21375. if (Html5 && Html5.prototype) {
  21376. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  21377. }
  21378. });
  21379. // default iOS to false, which will be updated in the timeout above.
  21380. return false;
  21381. }
  21382. return canControl;
  21383. } catch (e) {
  21384. return false;
  21385. }
  21386. };
  21387. /**
  21388. * Check if the volume can be muted in this browser/device.
  21389. * Some devices, e.g. iOS, don't allow changing volume
  21390. * but permits muting/unmuting.
  21391. *
  21392. * @return {boolean}
  21393. * - True if volume can be muted
  21394. * - False otherwise
  21395. */
  21396. Html5.canMuteVolume = function () {
  21397. try {
  21398. const muted = Html5.TEST_VID.muted;
  21399. // in some versions of iOS muted property doesn't always
  21400. // work, so we want to set both property and attribute
  21401. Html5.TEST_VID.muted = !muted;
  21402. if (Html5.TEST_VID.muted) {
  21403. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  21404. } else {
  21405. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  21406. }
  21407. return muted !== Html5.TEST_VID.muted;
  21408. } catch (e) {
  21409. return false;
  21410. }
  21411. };
  21412. /**
  21413. * Check if the playback rate can be changed in this browser/device.
  21414. *
  21415. * @return {boolean}
  21416. * - True if playback rate can be controlled
  21417. * - False otherwise
  21418. */
  21419. Html5.canControlPlaybackRate = function () {
  21420. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  21421. // https://github.com/videojs/video.js/issues/3180
  21422. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  21423. return false;
  21424. }
  21425. // IE will error if Windows Media Player not installed #3315
  21426. try {
  21427. const playbackRate = Html5.TEST_VID.playbackRate;
  21428. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  21429. return playbackRate !== Html5.TEST_VID.playbackRate;
  21430. } catch (e) {
  21431. return false;
  21432. }
  21433. };
  21434. /**
  21435. * Check if we can override a video/audio elements attributes, with
  21436. * Object.defineProperty.
  21437. *
  21438. * @return {boolean}
  21439. * - True if builtin attributes can be overridden
  21440. * - False otherwise
  21441. */
  21442. Html5.canOverrideAttributes = function () {
  21443. // if we cannot overwrite the src/innerHTML property, there is no support
  21444. // iOS 7 safari for instance cannot do this.
  21445. try {
  21446. const noop = () => {};
  21447. Object.defineProperty(document.createElement('video'), 'src', {
  21448. get: noop,
  21449. set: noop
  21450. });
  21451. Object.defineProperty(document.createElement('audio'), 'src', {
  21452. get: noop,
  21453. set: noop
  21454. });
  21455. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  21456. get: noop,
  21457. set: noop
  21458. });
  21459. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  21460. get: noop,
  21461. set: noop
  21462. });
  21463. } catch (e) {
  21464. return false;
  21465. }
  21466. return true;
  21467. };
  21468. /**
  21469. * Check to see if native `TextTrack`s are supported by this browser/device.
  21470. *
  21471. * @return {boolean}
  21472. * - True if native `TextTrack`s are supported.
  21473. * - False otherwise
  21474. */
  21475. Html5.supportsNativeTextTracks = function () {
  21476. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  21477. };
  21478. /**
  21479. * Check to see if native `VideoTrack`s are supported by this browser/device
  21480. *
  21481. * @return {boolean}
  21482. * - True if native `VideoTrack`s are supported.
  21483. * - False otherwise
  21484. */
  21485. Html5.supportsNativeVideoTracks = function () {
  21486. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  21487. };
  21488. /**
  21489. * Check to see if native `AudioTrack`s are supported by this browser/device
  21490. *
  21491. * @return {boolean}
  21492. * - True if native `AudioTrack`s are supported.
  21493. * - False otherwise
  21494. */
  21495. Html5.supportsNativeAudioTracks = function () {
  21496. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  21497. };
  21498. /**
  21499. * An array of events available on the Html5 tech.
  21500. *
  21501. * @private
  21502. * @type {Array}
  21503. */
  21504. Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];
  21505. /**
  21506. * Boolean indicating whether the `Tech` supports volume control.
  21507. *
  21508. * @type {boolean}
  21509. * @default {@link Html5.canControlVolume}
  21510. */
  21511. /**
  21512. * Boolean indicating whether the `Tech` supports muting volume.
  21513. *
  21514. * @type {boolean}
  21515. * @default {@link Html5.canMuteVolume}
  21516. */
  21517. /**
  21518. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  21519. * plays. Examples:
  21520. * - Set player to play 2x (twice) as fast
  21521. * - Set player to play 0.5x (half) as fast
  21522. *
  21523. * @type {boolean}
  21524. * @default {@link Html5.canControlPlaybackRate}
  21525. */
  21526. /**
  21527. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  21528. *
  21529. * @type {boolean}
  21530. * @default
  21531. */
  21532. /**
  21533. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  21534. *
  21535. * @type {boolean}
  21536. * @default {@link Html5.supportsNativeTextTracks}
  21537. */
  21538. /**
  21539. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  21540. *
  21541. * @type {boolean}
  21542. * @default {@link Html5.supportsNativeVideoTracks}
  21543. */
  21544. /**
  21545. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  21546. *
  21547. * @type {boolean}
  21548. * @default {@link Html5.supportsNativeAudioTracks}
  21549. */
  21550. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  21551. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  21552. });
  21553. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  21554. /**
  21555. * Boolean indicating whether the `HTML5` tech currently supports the media element
  21556. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  21557. * false there. Everywhere else this should be true.
  21558. *
  21559. * @type {boolean}
  21560. * @default
  21561. */
  21562. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  21563. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  21564. // Is this true?
  21565. /**
  21566. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  21567. * when going into fullscreen.
  21568. *
  21569. * @type {boolean}
  21570. * @default
  21571. */
  21572. Html5.prototype.featuresFullscreenResize = true;
  21573. /**
  21574. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  21575. * If this is false, manual `progress` events will be triggered instead.
  21576. *
  21577. * @type {boolean}
  21578. * @default
  21579. */
  21580. Html5.prototype.featuresProgressEvents = true;
  21581. /**
  21582. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  21583. * If this is false, manual `timeupdate` events will be triggered instead.
  21584. *
  21585. * @default
  21586. */
  21587. Html5.prototype.featuresTimeupdateEvents = true;
  21588. /**
  21589. * Whether the HTML5 el supports `requestVideoFrameCallback`
  21590. *
  21591. * @type {boolean}
  21592. */
  21593. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  21594. Html5.disposeMediaElement = function (el) {
  21595. if (!el) {
  21596. return;
  21597. }
  21598. if (el.parentNode) {
  21599. el.parentNode.removeChild(el);
  21600. }
  21601. // remove any child track or source nodes to prevent their loading
  21602. while (el.hasChildNodes()) {
  21603. el.removeChild(el.firstChild);
  21604. }
  21605. // remove any src reference. not setting `src=''` because that causes a warning
  21606. // in firefox
  21607. el.removeAttribute('src');
  21608. // force the media element to update its loading state by calling load()
  21609. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  21610. if (typeof el.load === 'function') {
  21611. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  21612. (function () {
  21613. try {
  21614. el.load();
  21615. } catch (e) {
  21616. // not supported
  21617. }
  21618. })();
  21619. }
  21620. };
  21621. Html5.resetMediaElement = function (el) {
  21622. if (!el) {
  21623. return;
  21624. }
  21625. const sources = el.querySelectorAll('source');
  21626. let i = sources.length;
  21627. while (i--) {
  21628. el.removeChild(sources[i]);
  21629. }
  21630. // remove any src reference.
  21631. // not setting `src=''` because that throws an error
  21632. el.removeAttribute('src');
  21633. if (typeof el.load === 'function') {
  21634. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  21635. (function () {
  21636. try {
  21637. el.load();
  21638. } catch (e) {
  21639. // satisfy linter
  21640. }
  21641. })();
  21642. }
  21643. };
  21644. /* Native HTML5 element property wrapping ----------------------------------- */
  21645. // Wrap native boolean attributes with getters that check both property and attribute
  21646. // The list is as followed:
  21647. // muted, defaultMuted, autoplay, controls, loop, playsinline
  21648. [
  21649. /**
  21650. * Get the value of `muted` from the media element. `muted` indicates
  21651. * that the volume for the media should be set to silent. This does not actually change
  21652. * the `volume` attribute.
  21653. *
  21654. * @method Html5#muted
  21655. * @return {boolean}
  21656. * - True if the value of `volume` should be ignored and the audio set to silent.
  21657. * - False if the value of `volume` should be used.
  21658. *
  21659. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  21660. */
  21661. 'muted',
  21662. /**
  21663. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  21664. * whether the media should start muted or not. Only changes the default state of the
  21665. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  21666. * current state.
  21667. *
  21668. * @method Html5#defaultMuted
  21669. * @return {boolean}
  21670. * - The value of `defaultMuted` from the media element.
  21671. * - True indicates that the media should start muted.
  21672. * - False indicates that the media should not start muted
  21673. *
  21674. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  21675. */
  21676. 'defaultMuted',
  21677. /**
  21678. * Get the value of `autoplay` from the media element. `autoplay` indicates
  21679. * that the media should start to play as soon as the page is ready.
  21680. *
  21681. * @method Html5#autoplay
  21682. * @return {boolean}
  21683. * - The value of `autoplay` from the media element.
  21684. * - True indicates that the media should start as soon as the page loads.
  21685. * - False indicates that the media should not start as soon as the page loads.
  21686. *
  21687. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  21688. */
  21689. 'autoplay',
  21690. /**
  21691. * Get the value of `controls` from the media element. `controls` indicates
  21692. * whether the native media controls should be shown or hidden.
  21693. *
  21694. * @method Html5#controls
  21695. * @return {boolean}
  21696. * - The value of `controls` from the media element.
  21697. * - True indicates that native controls should be showing.
  21698. * - False indicates that native controls should be hidden.
  21699. *
  21700. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  21701. */
  21702. 'controls',
  21703. /**
  21704. * Get the value of `loop` from the media element. `loop` indicates
  21705. * that the media should return to the start of the media and continue playing once
  21706. * it reaches the end.
  21707. *
  21708. * @method Html5#loop
  21709. * @return {boolean}
  21710. * - The value of `loop` from the media element.
  21711. * - True indicates that playback should seek back to start once
  21712. * the end of a media is reached.
  21713. * - False indicates that playback should not loop back to the start when the
  21714. * end of the media is reached.
  21715. *
  21716. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  21717. */
  21718. 'loop',
  21719. /**
  21720. * Get the value of `playsinline` from the media element. `playsinline` indicates
  21721. * to the browser that non-fullscreen playback is preferred when fullscreen
  21722. * playback is the native default, such as in iOS Safari.
  21723. *
  21724. * @method Html5#playsinline
  21725. * @return {boolean}
  21726. * - The value of `playsinline` from the media element.
  21727. * - True indicates that the media should play inline.
  21728. * - False indicates that the media should not play inline.
  21729. *
  21730. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  21731. */
  21732. 'playsinline'].forEach(function (prop) {
  21733. Html5.prototype[prop] = function () {
  21734. return this.el_[prop] || this.el_.hasAttribute(prop);
  21735. };
  21736. });
  21737. // Wrap native boolean attributes with setters that set both property and attribute
  21738. // The list is as followed:
  21739. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  21740. // setControls is special-cased above
  21741. [
  21742. /**
  21743. * Set the value of `muted` on the media element. `muted` indicates that the current
  21744. * audio level should be silent.
  21745. *
  21746. * @method Html5#setMuted
  21747. * @param {boolean} muted
  21748. * - True if the audio should be set to silent
  21749. * - False otherwise
  21750. *
  21751. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  21752. */
  21753. 'muted',
  21754. /**
  21755. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  21756. * audio level should be silent, but will only effect the muted level on initial playback..
  21757. *
  21758. * @method Html5.prototype.setDefaultMuted
  21759. * @param {boolean} defaultMuted
  21760. * - True if the audio should be set to silent
  21761. * - False otherwise
  21762. *
  21763. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  21764. */
  21765. 'defaultMuted',
  21766. /**
  21767. * Set the value of `autoplay` on the media element. `autoplay` indicates
  21768. * that the media should start to play as soon as the page is ready.
  21769. *
  21770. * @method Html5#setAutoplay
  21771. * @param {boolean} autoplay
  21772. * - True indicates that the media should start as soon as the page loads.
  21773. * - False indicates that the media should not start as soon as the page loads.
  21774. *
  21775. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  21776. */
  21777. 'autoplay',
  21778. /**
  21779. * Set the value of `loop` on the media element. `loop` indicates
  21780. * that the media should return to the start of the media and continue playing once
  21781. * it reaches the end.
  21782. *
  21783. * @method Html5#setLoop
  21784. * @param {boolean} loop
  21785. * - True indicates that playback should seek back to start once
  21786. * the end of a media is reached.
  21787. * - False indicates that playback should not loop back to the start when the
  21788. * end of the media is reached.
  21789. *
  21790. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  21791. */
  21792. 'loop',
  21793. /**
  21794. * Set the value of `playsinline` from the media element. `playsinline` indicates
  21795. * to the browser that non-fullscreen playback is preferred when fullscreen
  21796. * playback is the native default, such as in iOS Safari.
  21797. *
  21798. * @method Html5#setPlaysinline
  21799. * @param {boolean} playsinline
  21800. * - True indicates that the media should play inline.
  21801. * - False indicates that the media should not play inline.
  21802. *
  21803. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  21804. */
  21805. 'playsinline'].forEach(function (prop) {
  21806. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  21807. this.el_[prop] = v;
  21808. if (v) {
  21809. this.el_.setAttribute(prop, prop);
  21810. } else {
  21811. this.el_.removeAttribute(prop);
  21812. }
  21813. };
  21814. });
  21815. // Wrap native properties with a getter
  21816. // The list is as followed
  21817. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  21818. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  21819. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  21820. [
  21821. /**
  21822. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  21823. * is currently paused or not.
  21824. *
  21825. * @method Html5#paused
  21826. * @return {boolean}
  21827. * The value of `paused` from the media element.
  21828. *
  21829. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  21830. */
  21831. 'paused',
  21832. /**
  21833. * Get the value of `currentTime` from the media element. `currentTime` indicates
  21834. * the current second that the media is at in playback.
  21835. *
  21836. * @method Html5#currentTime
  21837. * @return {number}
  21838. * The value of `currentTime` from the media element.
  21839. *
  21840. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  21841. */
  21842. 'currentTime',
  21843. /**
  21844. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  21845. * object that represents the parts of the media that are already downloaded and
  21846. * available for playback.
  21847. *
  21848. * @method Html5#buffered
  21849. * @return {TimeRange}
  21850. * The value of `buffered` from the media element.
  21851. *
  21852. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  21853. */
  21854. 'buffered',
  21855. /**
  21856. * Get the value of `volume` from the media element. `volume` indicates
  21857. * the current playback volume of audio for a media. `volume` will be a value from 0
  21858. * (silent) to 1 (loudest and default).
  21859. *
  21860. * @method Html5#volume
  21861. * @return {number}
  21862. * The value of `volume` from the media element. Value will be between 0-1.
  21863. *
  21864. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  21865. */
  21866. 'volume',
  21867. /**
  21868. * Get the value of `poster` from the media element. `poster` indicates
  21869. * that the url of an image file that can/will be shown when no media data is available.
  21870. *
  21871. * @method Html5#poster
  21872. * @return {string}
  21873. * The value of `poster` from the media element. Value will be a url to an
  21874. * image.
  21875. *
  21876. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  21877. */
  21878. 'poster',
  21879. /**
  21880. * Get the value of `preload` from the media element. `preload` indicates
  21881. * what should download before the media is interacted with. It can have the following
  21882. * values:
  21883. * - none: nothing should be downloaded
  21884. * - metadata: poster and the first few frames of the media may be downloaded to get
  21885. * media dimensions and other metadata
  21886. * - auto: allow the media and metadata for the media to be downloaded before
  21887. * interaction
  21888. *
  21889. * @method Html5#preload
  21890. * @return {string}
  21891. * The value of `preload` from the media element. Will be 'none', 'metadata',
  21892. * or 'auto'.
  21893. *
  21894. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  21895. */
  21896. 'preload',
  21897. /**
  21898. * Get the value of the `error` from the media element. `error` indicates any
  21899. * MediaError that may have occurred during playback. If error returns null there is no
  21900. * current error.
  21901. *
  21902. * @method Html5#error
  21903. * @return {MediaError|null}
  21904. * The value of `error` from the media element. Will be `MediaError` if there
  21905. * is a current error and null otherwise.
  21906. *
  21907. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  21908. */
  21909. 'error',
  21910. /**
  21911. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  21912. * media is currently seeking to a new position or not.
  21913. *
  21914. * @method Html5#seeking
  21915. * @return {boolean}
  21916. * - The value of `seeking` from the media element.
  21917. * - True indicates that the media is currently seeking to a new position.
  21918. * - False indicates that the media is not seeking to a new position at this time.
  21919. *
  21920. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  21921. */
  21922. 'seeking',
  21923. /**
  21924. * Get the value of `seekable` from the media element. `seekable` returns a
  21925. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  21926. *
  21927. * @method Html5#seekable
  21928. * @return {TimeRange}
  21929. * The value of `seekable` from the media element. A `TimeRange` object
  21930. * indicating the current ranges of time that can be seeked to.
  21931. *
  21932. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  21933. */
  21934. 'seekable',
  21935. /**
  21936. * Get the value of `ended` from the media element. `ended` indicates whether
  21937. * the media has reached the end or not.
  21938. *
  21939. * @method Html5#ended
  21940. * @return {boolean}
  21941. * - The value of `ended` from the media element.
  21942. * - True indicates that the media has ended.
  21943. * - False indicates that the media has not ended.
  21944. *
  21945. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  21946. */
  21947. 'ended',
  21948. /**
  21949. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  21950. * the rate at which the media is currently playing back. Examples:
  21951. * - if playbackRate is set to 2, media will play twice as fast.
  21952. * - if playbackRate is set to 0.5, media will play half as fast.
  21953. *
  21954. * @method Html5#playbackRate
  21955. * @return {number}
  21956. * The value of `playbackRate` from the media element. A number indicating
  21957. * the current playback speed of the media, where 1 is normal speed.
  21958. *
  21959. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  21960. */
  21961. 'playbackRate',
  21962. /**
  21963. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  21964. * the rate at which the media is currently playing back. This value will not indicate the current
  21965. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  21966. *
  21967. * Examples:
  21968. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  21969. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  21970. *
  21971. * @method Html5.prototype.defaultPlaybackRate
  21972. * @return {number}
  21973. * The value of `defaultPlaybackRate` from the media element. A number indicating
  21974. * the current playback speed of the media, where 1 is normal speed.
  21975. *
  21976. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  21977. */
  21978. 'defaultPlaybackRate',
  21979. /**
  21980. * Get the value of 'disablePictureInPicture' from the video element.
  21981. *
  21982. * @method Html5#disablePictureInPicture
  21983. * @return {boolean} value
  21984. * - The value of `disablePictureInPicture` from the video element.
  21985. * - True indicates that the video can't be played in Picture-In-Picture mode
  21986. * - False indicates that the video can be played in Picture-In-Picture mode
  21987. *
  21988. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  21989. */
  21990. 'disablePictureInPicture',
  21991. /**
  21992. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  21993. * object representing points in the media timeline that have been played.
  21994. *
  21995. * @method Html5#played
  21996. * @return {TimeRange}
  21997. * The value of `played` from the media element. A `TimeRange` object indicating
  21998. * the ranges of time that have been played.
  21999. *
  22000. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  22001. */
  22002. 'played',
  22003. /**
  22004. * Get the value of `networkState` from the media element. `networkState` indicates
  22005. * the current network state. It returns an enumeration from the following list:
  22006. * - 0: NETWORK_EMPTY
  22007. * - 1: NETWORK_IDLE
  22008. * - 2: NETWORK_LOADING
  22009. * - 3: NETWORK_NO_SOURCE
  22010. *
  22011. * @method Html5#networkState
  22012. * @return {number}
  22013. * The value of `networkState` from the media element. This will be a number
  22014. * from the list in the description.
  22015. *
  22016. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  22017. */
  22018. 'networkState',
  22019. /**
  22020. * Get the value of `readyState` from the media element. `readyState` indicates
  22021. * the current state of the media element. It returns an enumeration from the
  22022. * following list:
  22023. * - 0: HAVE_NOTHING
  22024. * - 1: HAVE_METADATA
  22025. * - 2: HAVE_CURRENT_DATA
  22026. * - 3: HAVE_FUTURE_DATA
  22027. * - 4: HAVE_ENOUGH_DATA
  22028. *
  22029. * @method Html5#readyState
  22030. * @return {number}
  22031. * The value of `readyState` from the media element. This will be a number
  22032. * from the list in the description.
  22033. *
  22034. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  22035. */
  22036. 'readyState',
  22037. /**
  22038. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  22039. * the current width of the video in css pixels.
  22040. *
  22041. * @method Html5#videoWidth
  22042. * @return {number}
  22043. * The value of `videoWidth` from the video element. This will be a number
  22044. * in css pixels.
  22045. *
  22046. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  22047. */
  22048. 'videoWidth',
  22049. /**
  22050. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  22051. * the current height of the video in css pixels.
  22052. *
  22053. * @method Html5#videoHeight
  22054. * @return {number}
  22055. * The value of `videoHeight` from the video element. This will be a number
  22056. * in css pixels.
  22057. *
  22058. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  22059. */
  22060. 'videoHeight',
  22061. /**
  22062. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  22063. * to the browser that should sent the cookies along with the requests for the
  22064. * different assets/playlists
  22065. *
  22066. * @method Html5#crossOrigin
  22067. * @return {string}
  22068. * - anonymous indicates that the media should not sent cookies.
  22069. * - use-credentials indicates that the media should sent cookies along the requests.
  22070. *
  22071. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  22072. */
  22073. 'crossOrigin'].forEach(function (prop) {
  22074. Html5.prototype[prop] = function () {
  22075. return this.el_[prop];
  22076. };
  22077. });
  22078. // Wrap native properties with a setter in this format:
  22079. // set + toTitleCase(name)
  22080. // The list is as follows:
  22081. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  22082. // setDisablePictureInPicture, setCrossOrigin
  22083. [
  22084. /**
  22085. * Set the value of `volume` on the media element. `volume` indicates the current
  22086. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  22087. * so on.
  22088. *
  22089. * @method Html5#setVolume
  22090. * @param {number} percentAsDecimal
  22091. * The volume percent as a decimal. Valid range is from 0-1.
  22092. *
  22093. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  22094. */
  22095. 'volume',
  22096. /**
  22097. * Set the value of `src` on the media element. `src` indicates the current
  22098. * {@link Tech~SourceObject} for the media.
  22099. *
  22100. * @method Html5#setSrc
  22101. * @param {Tech~SourceObject} src
  22102. * The source object to set as the current source.
  22103. *
  22104. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  22105. */
  22106. 'src',
  22107. /**
  22108. * Set the value of `poster` on the media element. `poster` is the url to
  22109. * an image file that can/will be shown when no media data is available.
  22110. *
  22111. * @method Html5#setPoster
  22112. * @param {string} poster
  22113. * The url to an image that should be used as the `poster` for the media
  22114. * element.
  22115. *
  22116. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  22117. */
  22118. 'poster',
  22119. /**
  22120. * Set the value of `preload` on the media element. `preload` indicates
  22121. * what should download before the media is interacted with. It can have the following
  22122. * values:
  22123. * - none: nothing should be downloaded
  22124. * - metadata: poster and the first few frames of the media may be downloaded to get
  22125. * media dimensions and other metadata
  22126. * - auto: allow the media and metadata for the media to be downloaded before
  22127. * interaction
  22128. *
  22129. * @method Html5#setPreload
  22130. * @param {string} preload
  22131. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  22132. * or 'auto'.
  22133. *
  22134. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  22135. */
  22136. 'preload',
  22137. /**
  22138. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  22139. * the rate at which the media should play back. Examples:
  22140. * - if playbackRate is set to 2, media will play twice as fast.
  22141. * - if playbackRate is set to 0.5, media will play half as fast.
  22142. *
  22143. * @method Html5#setPlaybackRate
  22144. * @return {number}
  22145. * The value of `playbackRate` from the media element. A number indicating
  22146. * the current playback speed of the media, where 1 is normal speed.
  22147. *
  22148. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  22149. */
  22150. 'playbackRate',
  22151. /**
  22152. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  22153. * the rate at which the media should play back upon initial startup. Changing this value
  22154. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  22155. *
  22156. * Example Values:
  22157. * - if playbackRate is set to 2, media will play twice as fast.
  22158. * - if playbackRate is set to 0.5, media will play half as fast.
  22159. *
  22160. * @method Html5.prototype.setDefaultPlaybackRate
  22161. * @return {number}
  22162. * The value of `defaultPlaybackRate` from the media element. A number indicating
  22163. * the current playback speed of the media, where 1 is normal speed.
  22164. *
  22165. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  22166. */
  22167. 'defaultPlaybackRate',
  22168. /**
  22169. * Prevents the browser from suggesting a Picture-in-Picture context menu
  22170. * or to request Picture-in-Picture automatically in some cases.
  22171. *
  22172. * @method Html5#setDisablePictureInPicture
  22173. * @param {boolean} value
  22174. * The true value will disable Picture-in-Picture mode.
  22175. *
  22176. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  22177. */
  22178. 'disablePictureInPicture',
  22179. /**
  22180. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  22181. * to the browser that should sent the cookies along with the requests for the
  22182. * different assets/playlists
  22183. *
  22184. * @method Html5#setCrossOrigin
  22185. * @param {string} crossOrigin
  22186. * - anonymous indicates that the media should not sent cookies.
  22187. * - use-credentials indicates that the media should sent cookies along the requests.
  22188. *
  22189. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  22190. */
  22191. 'crossOrigin'].forEach(function (prop) {
  22192. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  22193. this.el_[prop] = v;
  22194. };
  22195. });
  22196. // wrap native functions with a function
  22197. // The list is as follows:
  22198. // pause, load, play
  22199. [
  22200. /**
  22201. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  22202. * media elements `pause` function.
  22203. *
  22204. * @method Html5#pause
  22205. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  22206. */
  22207. 'pause',
  22208. /**
  22209. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  22210. * media element `load` function.
  22211. *
  22212. * @method Html5#load
  22213. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  22214. */
  22215. 'load',
  22216. /**
  22217. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  22218. * media element `play` function.
  22219. *
  22220. * @method Html5#play
  22221. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  22222. */
  22223. 'play'].forEach(function (prop) {
  22224. Html5.prototype[prop] = function () {
  22225. return this.el_[prop]();
  22226. };
  22227. });
  22228. Tech.withSourceHandlers(Html5);
  22229. /**
  22230. * Native source handler for Html5, simply passes the source to the media element.
  22231. *
  22232. * @property {Tech~SourceObject} source
  22233. * The source object
  22234. *
  22235. * @property {Html5} tech
  22236. * The instance of the HTML5 tech.
  22237. */
  22238. Html5.nativeSourceHandler = {};
  22239. /**
  22240. * Check if the media element can play the given mime type.
  22241. *
  22242. * @param {string} type
  22243. * The mimetype to check
  22244. *
  22245. * @return {string}
  22246. * 'probably', 'maybe', or '' (empty string)
  22247. */
  22248. Html5.nativeSourceHandler.canPlayType = function (type) {
  22249. // IE without MediaPlayer throws an error (#519)
  22250. try {
  22251. return Html5.TEST_VID.canPlayType(type);
  22252. } catch (e) {
  22253. return '';
  22254. }
  22255. };
  22256. /**
  22257. * Check if the media element can handle a source natively.
  22258. *
  22259. * @param {Tech~SourceObject} source
  22260. * The source object
  22261. *
  22262. * @param {Object} [options]
  22263. * Options to be passed to the tech.
  22264. *
  22265. * @return {string}
  22266. * 'probably', 'maybe', or '' (empty string).
  22267. */
  22268. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  22269. // If a type was provided we should rely on that
  22270. if (source.type) {
  22271. return Html5.nativeSourceHandler.canPlayType(source.type);
  22272. // If no type, fall back to checking 'video/[EXTENSION]'
  22273. } else if (source.src) {
  22274. const ext = getFileExtension(source.src);
  22275. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  22276. }
  22277. return '';
  22278. };
  22279. /**
  22280. * Pass the source to the native media element.
  22281. *
  22282. * @param {Tech~SourceObject} source
  22283. * The source object
  22284. *
  22285. * @param {Html5} tech
  22286. * The instance of the Html5 tech
  22287. *
  22288. * @param {Object} [options]
  22289. * The options to pass to the source
  22290. */
  22291. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  22292. tech.setSrc(source.src);
  22293. };
  22294. /**
  22295. * A noop for the native dispose function, as cleanup is not needed.
  22296. */
  22297. Html5.nativeSourceHandler.dispose = function () {};
  22298. // Register the native source handler
  22299. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  22300. Tech.registerTech('Html5', Html5);
  22301. /**
  22302. * @file player.js
  22303. */
  22304. /** @import { TimeRange } from './utils/time' */
  22305. /** @import HtmlTrackElement from './tracks/html-track-element' */
  22306. /**
  22307. * @callback PlayerReadyCallback
  22308. * @this {Player}
  22309. * @returns {void}
  22310. */
  22311. // The following tech events are simply re-triggered
  22312. // on the player when they happen
  22313. const TECH_EVENTS_RETRIGGER = [
  22314. /**
  22315. * Fired while the user agent is downloading media data.
  22316. *
  22317. * @event Player#progress
  22318. * @type {Event}
  22319. */
  22320. /**
  22321. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  22322. *
  22323. * @private
  22324. * @method Player#handleTechProgress_
  22325. * @fires Player#progress
  22326. * @listens Tech#progress
  22327. */
  22328. 'progress',
  22329. /**
  22330. * Fires when the loading of an audio/video is aborted.
  22331. *
  22332. * @event Player#abort
  22333. * @type {Event}
  22334. */
  22335. /**
  22336. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  22337. *
  22338. * @private
  22339. * @method Player#handleTechAbort_
  22340. * @fires Player#abort
  22341. * @listens Tech#abort
  22342. */
  22343. 'abort',
  22344. /**
  22345. * Fires when the browser is intentionally not getting media data.
  22346. *
  22347. * @event Player#suspend
  22348. * @type {Event}
  22349. */
  22350. /**
  22351. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  22352. *
  22353. * @private
  22354. * @method Player#handleTechSuspend_
  22355. * @fires Player#suspend
  22356. * @listens Tech#suspend
  22357. */
  22358. 'suspend',
  22359. /**
  22360. * Fires when the current playlist is empty.
  22361. *
  22362. * @event Player#emptied
  22363. * @type {Event}
  22364. */
  22365. /**
  22366. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  22367. *
  22368. * @private
  22369. * @method Player#handleTechEmptied_
  22370. * @fires Player#emptied
  22371. * @listens Tech#emptied
  22372. */
  22373. 'emptied',
  22374. /**
  22375. * Fires when the browser is trying to get media data, but data is not available.
  22376. *
  22377. * @event Player#stalled
  22378. * @type {Event}
  22379. */
  22380. /**
  22381. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  22382. *
  22383. * @private
  22384. * @method Player#handleTechStalled_
  22385. * @fires Player#stalled
  22386. * @listens Tech#stalled
  22387. */
  22388. 'stalled',
  22389. /**
  22390. * Fires when the browser has loaded meta data for the audio/video.
  22391. *
  22392. * @event Player#loadedmetadata
  22393. * @type {Event}
  22394. */
  22395. /**
  22396. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  22397. *
  22398. * @private
  22399. * @method Player#handleTechLoadedmetadata_
  22400. * @fires Player#loadedmetadata
  22401. * @listens Tech#loadedmetadata
  22402. */
  22403. 'loadedmetadata',
  22404. /**
  22405. * Fires when the browser has loaded the current frame of the audio/video.
  22406. *
  22407. * @event Player#loadeddata
  22408. * @type {event}
  22409. */
  22410. /**
  22411. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  22412. *
  22413. * @private
  22414. * @method Player#handleTechLoaddeddata_
  22415. * @fires Player#loadeddata
  22416. * @listens Tech#loadeddata
  22417. */
  22418. 'loadeddata',
  22419. /**
  22420. * Fires when the current playback position has changed.
  22421. *
  22422. * @event Player#timeupdate
  22423. * @type {event}
  22424. */
  22425. /**
  22426. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  22427. *
  22428. * @private
  22429. * @method Player#handleTechTimeUpdate_
  22430. * @fires Player#timeupdate
  22431. * @listens Tech#timeupdate
  22432. */
  22433. 'timeupdate',
  22434. /**
  22435. * Fires when the video's intrinsic dimensions change
  22436. *
  22437. * @event Player#resize
  22438. * @type {event}
  22439. */
  22440. /**
  22441. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  22442. *
  22443. * @private
  22444. * @method Player#handleTechResize_
  22445. * @fires Player#resize
  22446. * @listens Tech#resize
  22447. */
  22448. 'resize',
  22449. /**
  22450. * Fires when the volume has been changed
  22451. *
  22452. * @event Player#volumechange
  22453. * @type {event}
  22454. */
  22455. /**
  22456. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  22457. *
  22458. * @private
  22459. * @method Player#handleTechVolumechange_
  22460. * @fires Player#volumechange
  22461. * @listens Tech#volumechange
  22462. */
  22463. 'volumechange',
  22464. /**
  22465. * Fires when the text track has been changed
  22466. *
  22467. * @event Player#texttrackchange
  22468. * @type {event}
  22469. */
  22470. /**
  22471. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  22472. *
  22473. * @private
  22474. * @method Player#handleTechTexttrackchange_
  22475. * @fires Player#texttrackchange
  22476. * @listens Tech#texttrackchange
  22477. */
  22478. 'texttrackchange'];
  22479. // events to queue when playback rate is zero
  22480. // this is a hash for the sole purpose of mapping non-camel-cased event names
  22481. // to camel-cased function names
  22482. const TECH_EVENTS_QUEUE = {
  22483. canplay: 'CanPlay',
  22484. canplaythrough: 'CanPlayThrough',
  22485. playing: 'Playing',
  22486. seeked: 'Seeked'
  22487. };
  22488. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  22489. const BREAKPOINT_CLASSES = {};
  22490. // grep: vjs-layout-tiny
  22491. // grep: vjs-layout-x-small
  22492. // grep: vjs-layout-small
  22493. // grep: vjs-layout-medium
  22494. // grep: vjs-layout-large
  22495. // grep: vjs-layout-x-large
  22496. // grep: vjs-layout-huge
  22497. BREAKPOINT_ORDER.forEach(k => {
  22498. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  22499. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  22500. });
  22501. const DEFAULT_BREAKPOINTS = {
  22502. tiny: 210,
  22503. xsmall: 320,
  22504. small: 425,
  22505. medium: 768,
  22506. large: 1440,
  22507. xlarge: 2560,
  22508. huge: Infinity
  22509. };
  22510. /**
  22511. * An instance of the `Player` class is created when any of the Video.js setup methods
  22512. * are used to initialize a video.
  22513. *
  22514. * After an instance has been created it can be accessed globally in three ways:
  22515. * 1. By calling `videojs.getPlayer('example_video_1');`
  22516. * 2. By calling `videojs('example_video_1');` (not recommended)
  22517. * 2. By using it directly via `videojs.players.example_video_1;`
  22518. *
  22519. * @extends Component
  22520. * @global
  22521. */
  22522. class Player extends Component {
  22523. /**
  22524. * Create an instance of this class.
  22525. *
  22526. * @param {Element} tag
  22527. * The original video DOM element used for configuring options.
  22528. *
  22529. * @param {Object} [options]
  22530. * Object of option names and values.
  22531. *
  22532. * @param {PlayerReadyCallback} [ready]
  22533. * Ready callback function.
  22534. */
  22535. constructor(tag, options, ready) {
  22536. // Make sure tag ID exists
  22537. // also here.. probably better
  22538. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  22539. // Set Options
  22540. // The options argument overrides options set in the video tag
  22541. // which overrides globally set options.
  22542. // This latter part coincides with the load order
  22543. // (tag must exist before Player)
  22544. options = Object.assign(Player.getTagSettings(tag), options);
  22545. // Delay the initialization of children because we need to set up
  22546. // player properties first, and can't use `this` before `super()`
  22547. options.initChildren = false;
  22548. // Same with creating the element
  22549. options.createEl = false;
  22550. // don't auto mixin the evented mixin
  22551. options.evented = false;
  22552. // we don't want the player to report touch activity on itself
  22553. // see enableTouchActivity in Component
  22554. options.reportTouchActivity = false;
  22555. // If language is not set, get the closest lang attribute
  22556. if (!options.language) {
  22557. const closest = tag.closest('[lang]');
  22558. if (closest) {
  22559. options.language = closest.getAttribute('lang');
  22560. }
  22561. }
  22562. // Run base component initializing with new options
  22563. super(null, options, ready);
  22564. // Create bound methods for document listeners.
  22565. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  22566. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  22567. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  22568. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  22569. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  22570. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  22571. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  22572. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  22573. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  22574. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  22575. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  22576. this.boundUpdatePlayerHeightOnAudioOnlyMode_ = e => this.updatePlayerHeightOnAudioOnlyMode_(e);
  22577. // default isFullscreen_ to false
  22578. this.isFullscreen_ = false;
  22579. // create logger
  22580. this.log = createLogger(this.id_);
  22581. // Hold our own reference to fullscreen api so it can be mocked in tests
  22582. this.fsApi_ = FullscreenApi;
  22583. // Tracks when a tech changes the poster
  22584. this.isPosterFromTech_ = false;
  22585. // Holds callback info that gets queued when playback rate is zero
  22586. // and a seek is happening
  22587. this.queuedCallbacks_ = [];
  22588. // Turn off API access because we're loading a new tech that might load asynchronously
  22589. this.isReady_ = false;
  22590. // Init state hasStarted_
  22591. this.hasStarted_ = false;
  22592. // Init state userActive_
  22593. this.userActive_ = false;
  22594. // Init debugEnabled_
  22595. this.debugEnabled_ = false;
  22596. // Init state audioOnlyMode_
  22597. this.audioOnlyMode_ = false;
  22598. // Init state audioPosterMode_
  22599. this.audioPosterMode_ = false;
  22600. // Init state audioOnlyCache_
  22601. this.audioOnlyCache_ = {
  22602. controlBarHeight: null,
  22603. playerHeight: null,
  22604. hiddenChildren: []
  22605. };
  22606. // if the global option object was accidentally blown away by
  22607. // someone, bail early with an informative error
  22608. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  22609. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  22610. }
  22611. // Store the original tag used to set options
  22612. this.tag = tag;
  22613. // Store the tag attributes used to restore html5 element
  22614. this.tagAttributes = tag && getAttributes(tag);
  22615. // Update current language
  22616. this.language(this.options_.language);
  22617. // Update Supported Languages
  22618. if (options.languages) {
  22619. // Normalise player option languages to lowercase
  22620. const languagesToLower = {};
  22621. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  22622. languagesToLower[name.toLowerCase()] = options.languages[name];
  22623. });
  22624. this.languages_ = languagesToLower;
  22625. } else {
  22626. this.languages_ = Player.prototype.options_.languages;
  22627. }
  22628. this.resetCache_();
  22629. // Set poster
  22630. /** @type string */
  22631. this.poster_ = options.poster || '';
  22632. // Set controls
  22633. /** @type {boolean} */
  22634. this.controls_ = !!options.controls;
  22635. // Original tag settings stored in options
  22636. // now remove immediately so native controls don't flash.
  22637. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  22638. tag.controls = false;
  22639. tag.removeAttribute('controls');
  22640. this.changingSrc_ = false;
  22641. this.playCallbacks_ = [];
  22642. this.playTerminatedQueue_ = [];
  22643. // the attribute overrides the option
  22644. if (tag.hasAttribute('autoplay')) {
  22645. this.autoplay(true);
  22646. } else {
  22647. // otherwise use the setter to validate and
  22648. // set the correct value.
  22649. this.autoplay(this.options_.autoplay);
  22650. }
  22651. // check plugins
  22652. if (options.plugins) {
  22653. Object.keys(options.plugins).forEach(name => {
  22654. if (typeof this[name] !== 'function') {
  22655. throw new Error(`plugin "${name}" does not exist`);
  22656. }
  22657. });
  22658. }
  22659. /*
  22660. * Store the internal state of scrubbing
  22661. *
  22662. * @private
  22663. * @return {Boolean} True if the user is scrubbing
  22664. */
  22665. this.scrubbing_ = false;
  22666. this.el_ = this.createEl();
  22667. // Make this an evented object and use `el_` as its event bus.
  22668. evented(this, {
  22669. eventBusKey: 'el_'
  22670. });
  22671. // listen to document and player fullscreenchange handlers so we receive those events
  22672. // before a user can receive them so we can update isFullscreen appropriately.
  22673. // make sure that we listen to fullscreenchange events before everything else to make sure that
  22674. // our isFullscreen method is updated properly for internal components as well as external.
  22675. if (this.fsApi_.requestFullscreen) {
  22676. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  22677. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  22678. }
  22679. if (this.fluid_) {
  22680. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  22681. }
  22682. // We also want to pass the original player options to each component and plugin
  22683. // as well so they don't need to reach back into the player for options later.
  22684. // We also need to do another copy of this.options_ so we don't end up with
  22685. // an infinite loop.
  22686. const playerOptionsCopy = merge(this.options_);
  22687. // Load plugins
  22688. if (options.plugins) {
  22689. Object.keys(options.plugins).forEach(name => {
  22690. this[name](options.plugins[name]);
  22691. });
  22692. }
  22693. // Enable debug mode to fire debugon event for all plugins.
  22694. if (options.debug) {
  22695. this.debug(true);
  22696. }
  22697. this.options_.playerOptions = playerOptionsCopy;
  22698. this.middleware_ = [];
  22699. this.playbackRates(options.playbackRates);
  22700. if (options.experimentalSvgIcons) {
  22701. // Add SVG Sprite to the DOM
  22702. const parser = new window.DOMParser();
  22703. const parsedSVG = parser.parseFromString(icons, 'image/svg+xml');
  22704. const errorNode = parsedSVG.querySelector('parsererror');
  22705. if (errorNode) {
  22706. log.warn('Failed to load SVG Icons. Falling back to Font Icons.');
  22707. this.options_.experimentalSvgIcons = null;
  22708. } else {
  22709. const sprite = parsedSVG.documentElement;
  22710. sprite.style.display = 'none';
  22711. this.el_.appendChild(sprite);
  22712. this.addClass('vjs-svg-icons-enabled');
  22713. }
  22714. }
  22715. this.initChildren();
  22716. // Set isAudio based on whether or not an audio tag was used
  22717. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  22718. // Update controls className. Can't do this when the controls are initially
  22719. // set because the element doesn't exist yet.
  22720. if (this.controls()) {
  22721. this.addClass('vjs-controls-enabled');
  22722. } else {
  22723. this.addClass('vjs-controls-disabled');
  22724. }
  22725. // Set ARIA label and region role depending on player type
  22726. this.el_.setAttribute('role', 'region');
  22727. if (this.isAudio()) {
  22728. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  22729. } else {
  22730. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  22731. }
  22732. if (this.isAudio()) {
  22733. this.addClass('vjs-audio');
  22734. }
  22735. // Check if spatial navigation is enabled in the options.
  22736. // If enabled, instantiate the SpatialNavigation class.
  22737. if (options.spatialNavigation && options.spatialNavigation.enabled) {
  22738. this.spatialNavigation = new SpatialNavigation(this);
  22739. this.addClass('vjs-spatial-navigation-enabled');
  22740. }
  22741. // TODO: Make this smarter. Toggle user state between touching/mousing
  22742. // using events, since devices can have both touch and mouse events.
  22743. // TODO: Make this check be performed again when the window switches between monitors
  22744. // (See https://github.com/videojs/video.js/issues/5683)
  22745. if (TOUCH_ENABLED) {
  22746. this.addClass('vjs-touch-enabled');
  22747. }
  22748. // iOS Safari has broken hover handling
  22749. if (!IS_IOS) {
  22750. this.addClass('vjs-workinghover');
  22751. }
  22752. // Make player easily findable by ID
  22753. Player.players[this.id_] = this;
  22754. // Add a major version class to aid css in plugins
  22755. const majorVersion = version.split('.')[0];
  22756. this.addClass(`vjs-v${majorVersion}`);
  22757. // When the player is first initialized, trigger activity so components
  22758. // like the control bar show themselves if needed
  22759. this.userActive(true);
  22760. this.reportUserActivity();
  22761. this.one('play', e => this.listenForUserActivity_(e));
  22762. this.on('keydown', e => this.handleKeyDown(e));
  22763. this.on('languagechange', e => this.handleLanguagechange(e));
  22764. this.breakpoints(this.options_.breakpoints);
  22765. this.responsive(this.options_.responsive);
  22766. // Calling both the audio mode methods after the player is fully
  22767. // setup to be able to listen to the events triggered by them
  22768. this.on('ready', () => {
  22769. // Calling the audioPosterMode method first so that
  22770. // the audioOnlyMode can take precedence when both options are set to true
  22771. this.audioPosterMode(this.options_.audioPosterMode);
  22772. this.audioOnlyMode(this.options_.audioOnlyMode);
  22773. });
  22774. }
  22775. /**
  22776. * Destroys the video player and does any necessary cleanup.
  22777. *
  22778. * This is especially helpful if you are dynamically adding and removing videos
  22779. * to/from the DOM.
  22780. *
  22781. * @fires Player#dispose
  22782. */
  22783. dispose() {
  22784. /**
  22785. * Called when the player is being disposed of.
  22786. *
  22787. * @event Player#dispose
  22788. * @type {Event}
  22789. */
  22790. this.trigger('dispose');
  22791. // prevent dispose from being called twice
  22792. this.off('dispose');
  22793. // Make sure all player-specific document listeners are unbound. This is
  22794. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  22795. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  22796. if (this.styleEl_ && this.styleEl_.parentNode) {
  22797. this.styleEl_.parentNode.removeChild(this.styleEl_);
  22798. this.styleEl_ = null;
  22799. }
  22800. // Kill reference to this player
  22801. Player.players[this.id_] = null;
  22802. if (this.tag && this.tag.player) {
  22803. this.tag.player = null;
  22804. }
  22805. if (this.el_ && this.el_.player) {
  22806. this.el_.player = null;
  22807. }
  22808. if (this.tech_) {
  22809. this.tech_.dispose();
  22810. this.isPosterFromTech_ = false;
  22811. this.poster_ = '';
  22812. }
  22813. if (this.playerElIngest_) {
  22814. this.playerElIngest_ = null;
  22815. }
  22816. if (this.tag) {
  22817. this.tag = null;
  22818. }
  22819. clearCacheForPlayer(this);
  22820. // remove all event handlers for track lists
  22821. // all tracks and track listeners are removed on
  22822. // tech dispose
  22823. ALL.names.forEach(name => {
  22824. const props = ALL[name];
  22825. const list = this[props.getterName]();
  22826. // if it is not a native list
  22827. // we have to manually remove event listeners
  22828. if (list && list.off) {
  22829. list.off();
  22830. }
  22831. });
  22832. // the actual .el_ is removed here, or replaced if
  22833. super.dispose({
  22834. restoreEl: this.options_.restoreEl
  22835. });
  22836. }
  22837. /**
  22838. * Create the `Player`'s DOM element.
  22839. *
  22840. * @return {Element}
  22841. * The DOM element that gets created.
  22842. */
  22843. createEl() {
  22844. let tag = this.tag;
  22845. let el;
  22846. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  22847. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  22848. if (playerElIngest) {
  22849. el = this.el_ = tag.parentNode;
  22850. } else if (!divEmbed) {
  22851. el = this.el_ = super.createEl('div');
  22852. }
  22853. // Copy over all the attributes from the tag, including ID and class
  22854. // ID will now reference player box, not the video tag
  22855. const attrs = getAttributes(tag);
  22856. if (divEmbed) {
  22857. el = this.el_ = tag;
  22858. tag = this.tag = document.createElement('video');
  22859. while (el.children.length) {
  22860. tag.appendChild(el.firstChild);
  22861. }
  22862. if (!hasClass(el, 'video-js')) {
  22863. addClass(el, 'video-js');
  22864. }
  22865. el.appendChild(tag);
  22866. playerElIngest = this.playerElIngest_ = el;
  22867. // move properties over from our custom `video-js` element
  22868. // to our new `video` element. This will move things like
  22869. // `src` or `controls` that were set via js before the player
  22870. // was initialized.
  22871. Object.keys(el).forEach(k => {
  22872. try {
  22873. tag[k] = el[k];
  22874. } catch (e) {
  22875. // we got a a property like outerHTML which we can't actually copy, ignore it
  22876. }
  22877. });
  22878. }
  22879. // set tabindex to -1 to remove the video element from the focus order
  22880. tag.setAttribute('tabindex', '-1');
  22881. attrs.tabindex = '-1';
  22882. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  22883. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  22884. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  22885. // doesn't change behavior of Chrome if JAWS is not being used
  22886. if (IS_CHROME && IS_WINDOWS) {
  22887. tag.setAttribute('role', 'application');
  22888. attrs.role = 'application';
  22889. }
  22890. // Remove width/height attrs from tag so CSS can make it 100% width/height
  22891. tag.removeAttribute('width');
  22892. tag.removeAttribute('height');
  22893. if ('width' in attrs) {
  22894. delete attrs.width;
  22895. }
  22896. if ('height' in attrs) {
  22897. delete attrs.height;
  22898. }
  22899. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  22900. // don't copy over the class attribute to the player element when we're in a div embed
  22901. // the class is already set up properly in the divEmbed case
  22902. // and we want to make sure that the `video-js` class doesn't get lost
  22903. if (!(divEmbed && attr === 'class')) {
  22904. el.setAttribute(attr, attrs[attr]);
  22905. }
  22906. if (divEmbed) {
  22907. tag.setAttribute(attr, attrs[attr]);
  22908. }
  22909. });
  22910. // Update tag id/class for use as HTML5 playback tech
  22911. // Might think we should do this after embedding in container so .vjs-tech class
  22912. // doesn't flash 100% width/height, but class only applies with .video-js parent
  22913. tag.playerId = tag.id;
  22914. tag.id += '_html5_api';
  22915. tag.className = 'vjs-tech';
  22916. // Make player findable on elements
  22917. tag.player = el.player = this;
  22918. // Default state of video is paused
  22919. this.addClass('vjs-paused');
  22920. const deviceClassNames = ['IS_SMART_TV', 'IS_TIZEN', 'IS_WEBOS', 'IS_ANDROID', 'IS_IPAD', 'IS_IPHONE', 'IS_CHROMECAST_RECEIVER'].filter(key => browser[key]).map(key => {
  22921. return 'vjs-device-' + key.substring(3).toLowerCase().replace(/\_/g, '-');
  22922. });
  22923. this.addClass(...deviceClassNames);
  22924. // Add a style element in the player that we'll use to set the width/height
  22925. // of the player in a way that's still overridable by CSS, just like the
  22926. // video element
  22927. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  22928. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  22929. const defaultsStyleEl = $('.vjs-styles-defaults');
  22930. const head = $('head');
  22931. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  22932. }
  22933. this.fill_ = false;
  22934. this.fluid_ = false;
  22935. // Pass in the width/height/aspectRatio options which will update the style el
  22936. this.width(this.options_.width);
  22937. this.height(this.options_.height);
  22938. this.fill(this.options_.fill);
  22939. this.fluid(this.options_.fluid);
  22940. this.aspectRatio(this.options_.aspectRatio);
  22941. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  22942. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  22943. // Hide any links within the video/audio tag,
  22944. // because IE doesn't hide them completely from screen readers.
  22945. const links = tag.getElementsByTagName('a');
  22946. for (let i = 0; i < links.length; i++) {
  22947. const linkEl = links.item(i);
  22948. addClass(linkEl, 'vjs-hidden');
  22949. linkEl.setAttribute('hidden', 'hidden');
  22950. }
  22951. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  22952. // keep track of the original for later so we can know if the source originally failed
  22953. tag.initNetworkState_ = tag.networkState;
  22954. // Wrap video tag in div (el/box) container
  22955. if (tag.parentNode && !playerElIngest) {
  22956. tag.parentNode.insertBefore(el, tag);
  22957. }
  22958. // insert the tag as the first child of the player element
  22959. // then manually add it to the children array so that this.addChild
  22960. // will work properly for other components
  22961. //
  22962. // Breaks iPhone, fixed in HTML5 setup.
  22963. prependTo(tag, el);
  22964. this.children_.unshift(tag);
  22965. // Set lang attr on player to ensure CSS :lang() in consistent with player
  22966. // if it's been set to something different to the doc
  22967. this.el_.setAttribute('lang', this.language_);
  22968. this.el_.setAttribute('translate', 'no');
  22969. this.el_ = el;
  22970. return el;
  22971. }
  22972. /**
  22973. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  22974. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  22975. * behavior.
  22976. *
  22977. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  22978. *
  22979. * @param {string|null} [value]
  22980. * The value to set the `Player`'s crossOrigin to. If an argument is
  22981. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  22982. *
  22983. * @return {string|null|undefined}
  22984. * - The current crossOrigin value of the `Player` when getting.
  22985. * - undefined when setting
  22986. */
  22987. crossOrigin(value) {
  22988. // `null` can be set to unset a value
  22989. if (typeof value === 'undefined') {
  22990. return this.techGet_('crossOrigin');
  22991. }
  22992. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  22993. log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  22994. return;
  22995. }
  22996. this.techCall_('setCrossOrigin', value);
  22997. if (this.posterImage) {
  22998. this.posterImage.crossOrigin(value);
  22999. }
  23000. return;
  23001. }
  23002. /**
  23003. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  23004. * To get the current width use `currentWidth()`.
  23005. *
  23006. * @param {number|string} [value]
  23007. * CSS value to set the `Player`'s width to.
  23008. *
  23009. * @return {number|undefined}
  23010. * - The current width of the `Player` when getting.
  23011. * - Nothing when setting
  23012. */
  23013. width(value) {
  23014. return this.dimension('width', value);
  23015. }
  23016. /**
  23017. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  23018. * To get the current height use `currentheight()`.
  23019. *
  23020. * @param {number|string} [value]
  23021. * CSS value to set the `Player`'s height to.
  23022. *
  23023. * @return {number|undefined}
  23024. * - The current height of the `Player` when getting.
  23025. * - Nothing when setting
  23026. */
  23027. height(value) {
  23028. return this.dimension('height', value);
  23029. }
  23030. /**
  23031. * A getter/setter for the `Player`'s width & height.
  23032. *
  23033. * @param {string} dimension
  23034. * This string can be:
  23035. * - 'width'
  23036. * - 'height'
  23037. *
  23038. * @param {number|string} [value]
  23039. * Value for dimension specified in the first argument.
  23040. *
  23041. * @return {number}
  23042. * The dimension arguments value when getting (width/height).
  23043. */
  23044. dimension(dimension, value) {
  23045. const privDimension = dimension + '_';
  23046. if (value === undefined) {
  23047. return this[privDimension] || 0;
  23048. }
  23049. if (value === '' || value === 'auto') {
  23050. // If an empty string is given, reset the dimension to be automatic
  23051. this[privDimension] = undefined;
  23052. this.updateStyleEl_();
  23053. return;
  23054. }
  23055. const parsedVal = parseFloat(value);
  23056. if (isNaN(parsedVal)) {
  23057. log.error(`Improper value "${value}" supplied for for ${dimension}`);
  23058. return;
  23059. }
  23060. this[privDimension] = parsedVal;
  23061. this.updateStyleEl_();
  23062. }
  23063. /**
  23064. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  23065. *
  23066. * Turning this on will turn off fill mode.
  23067. *
  23068. * @param {boolean} [bool]
  23069. * - A value of true adds the class.
  23070. * - A value of false removes the class.
  23071. * - No value will be a getter.
  23072. *
  23073. * @return {boolean|undefined}
  23074. * - The value of fluid when getting.
  23075. * - `undefined` when setting.
  23076. */
  23077. fluid(bool) {
  23078. if (bool === undefined) {
  23079. return !!this.fluid_;
  23080. }
  23081. this.fluid_ = !!bool;
  23082. if (isEvented(this)) {
  23083. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  23084. }
  23085. if (bool) {
  23086. this.addClass('vjs-fluid');
  23087. this.fill(false);
  23088. addEventedCallback(this, () => {
  23089. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  23090. });
  23091. } else {
  23092. this.removeClass('vjs-fluid');
  23093. }
  23094. this.updateStyleEl_();
  23095. }
  23096. /**
  23097. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  23098. *
  23099. * Turning this on will turn off fluid mode.
  23100. *
  23101. * @param {boolean} [bool]
  23102. * - A value of true adds the class.
  23103. * - A value of false removes the class.
  23104. * - No value will be a getter.
  23105. *
  23106. * @return {boolean|undefined}
  23107. * - The value of fluid when getting.
  23108. * - `undefined` when setting.
  23109. */
  23110. fill(bool) {
  23111. if (bool === undefined) {
  23112. return !!this.fill_;
  23113. }
  23114. this.fill_ = !!bool;
  23115. if (bool) {
  23116. this.addClass('vjs-fill');
  23117. this.fluid(false);
  23118. } else {
  23119. this.removeClass('vjs-fill');
  23120. }
  23121. }
  23122. /**
  23123. * Get/Set the aspect ratio
  23124. *
  23125. * @param {string} [ratio]
  23126. * Aspect ratio for player
  23127. *
  23128. * @return {string|undefined}
  23129. * returns the current aspect ratio when getting
  23130. */
  23131. /**
  23132. * A getter/setter for the `Player`'s aspect ratio.
  23133. *
  23134. * @param {string} [ratio]
  23135. * The value to set the `Player`'s aspect ratio to.
  23136. *
  23137. * @return {string|undefined}
  23138. * - The current aspect ratio of the `Player` when getting.
  23139. * - undefined when setting
  23140. */
  23141. aspectRatio(ratio) {
  23142. if (ratio === undefined) {
  23143. return this.aspectRatio_;
  23144. }
  23145. // Check for width:height format
  23146. if (!/^\d+\:\d+$/.test(ratio)) {
  23147. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  23148. }
  23149. this.aspectRatio_ = ratio;
  23150. // We're assuming if you set an aspect ratio you want fluid mode,
  23151. // because in fixed mode you could calculate width and height yourself.
  23152. this.fluid(true);
  23153. this.updateStyleEl_();
  23154. }
  23155. /**
  23156. * Update styles of the `Player` element (height, width and aspect ratio).
  23157. *
  23158. * @private
  23159. * @listens Tech#loadedmetadata
  23160. */
  23161. updateStyleEl_() {
  23162. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  23163. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  23164. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  23165. const techEl = this.tech_ && this.tech_.el();
  23166. if (techEl) {
  23167. if (width >= 0) {
  23168. techEl.width = width;
  23169. }
  23170. if (height >= 0) {
  23171. techEl.height = height;
  23172. }
  23173. }
  23174. return;
  23175. }
  23176. let width;
  23177. let height;
  23178. let aspectRatio;
  23179. let idClass;
  23180. // The aspect ratio is either used directly or to calculate width and height.
  23181. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  23182. // Use any aspectRatio that's been specifically set
  23183. aspectRatio = this.aspectRatio_;
  23184. } else if (this.videoWidth() > 0) {
  23185. // Otherwise try to get the aspect ratio from the video metadata
  23186. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  23187. } else {
  23188. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  23189. aspectRatio = '16:9';
  23190. }
  23191. // Get the ratio as a decimal we can use to calculate dimensions
  23192. const ratioParts = aspectRatio.split(':');
  23193. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  23194. if (this.width_ !== undefined) {
  23195. // Use any width that's been specifically set
  23196. width = this.width_;
  23197. } else if (this.height_ !== undefined) {
  23198. // Or calculate the width from the aspect ratio if a height has been set
  23199. width = this.height_ / ratioMultiplier;
  23200. } else {
  23201. // Or use the video's metadata, or use the video el's default of 300
  23202. width = this.videoWidth() || 300;
  23203. }
  23204. if (this.height_ !== undefined) {
  23205. // Use any height that's been specifically set
  23206. height = this.height_;
  23207. } else {
  23208. // Otherwise calculate the height from the ratio and the width
  23209. height = width * ratioMultiplier;
  23210. }
  23211. // Ensure the CSS class is valid by starting with an alpha character
  23212. if (/^[^a-zA-Z]/.test(this.id())) {
  23213. idClass = 'dimensions-' + this.id();
  23214. } else {
  23215. idClass = this.id() + '-dimensions';
  23216. }
  23217. // Ensure the right class is still on the player for the style element
  23218. this.addClass(idClass);
  23219. setTextContent(this.styleEl_, `
  23220. .${idClass} {
  23221. width: ${width}px;
  23222. height: ${height}px;
  23223. }
  23224. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  23225. padding-top: ${ratioMultiplier * 100}%;
  23226. }
  23227. `);
  23228. }
  23229. /**
  23230. * Load/Create an instance of playback {@link Tech} including element
  23231. * and API methods. Then append the `Tech` element in `Player` as a child.
  23232. *
  23233. * @param {string} techName
  23234. * name of the playback technology
  23235. *
  23236. * @param {string} source
  23237. * video source
  23238. *
  23239. * @private
  23240. */
  23241. loadTech_(techName, source) {
  23242. // Pause and remove current playback technology
  23243. if (this.tech_) {
  23244. this.unloadTech_();
  23245. }
  23246. const titleTechName = toTitleCase(techName);
  23247. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  23248. // get rid of the HTML5 video tag as soon as we are using another tech
  23249. if (titleTechName !== 'Html5' && this.tag) {
  23250. Tech.getTech('Html5').disposeMediaElement(this.tag);
  23251. this.tag.player = null;
  23252. this.tag = null;
  23253. }
  23254. this.techName_ = titleTechName;
  23255. // Turn off API access because we're loading a new tech that might load asynchronously
  23256. this.isReady_ = false;
  23257. let autoplay = this.autoplay();
  23258. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  23259. // because the player is going to handle autoplay on `loadstart`
  23260. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  23261. autoplay = false;
  23262. }
  23263. // Grab tech-specific options from player options and add source and parent element to use.
  23264. const techOptions = {
  23265. source,
  23266. autoplay,
  23267. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  23268. 'playerId': this.id(),
  23269. 'techId': `${this.id()}_${camelTechName}_api`,
  23270. 'playsinline': this.options_.playsinline,
  23271. 'preload': this.options_.preload,
  23272. 'loop': this.options_.loop,
  23273. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  23274. 'muted': this.options_.muted,
  23275. 'poster': this.poster(),
  23276. 'language': this.language(),
  23277. 'playerElIngest': this.playerElIngest_ || false,
  23278. 'vtt.js': this.options_['vtt.js'],
  23279. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  23280. 'enableSourceset': this.options_.enableSourceset
  23281. };
  23282. ALL.names.forEach(name => {
  23283. const props = ALL[name];
  23284. techOptions[props.getterName] = this[props.privateName];
  23285. });
  23286. Object.assign(techOptions, this.options_[titleTechName]);
  23287. Object.assign(techOptions, this.options_[camelTechName]);
  23288. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  23289. if (this.tag) {
  23290. techOptions.tag = this.tag;
  23291. }
  23292. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  23293. techOptions.startTime = this.cache_.currentTime;
  23294. }
  23295. // Initialize tech instance
  23296. const TechClass = Tech.getTech(techName);
  23297. if (!TechClass) {
  23298. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  23299. }
  23300. this.tech_ = new TechClass(techOptions);
  23301. // player.triggerReady is always async, so don't need this to be async
  23302. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  23303. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  23304. // Listen to all HTML5-defined events and trigger them on the player
  23305. TECH_EVENTS_RETRIGGER.forEach(event => {
  23306. this.on(this.tech_, event, e => this[`handleTech${toTitleCase(event)}_`](e));
  23307. });
  23308. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  23309. this.on(this.tech_, event, eventObj => {
  23310. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  23311. this.queuedCallbacks_.push({
  23312. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  23313. event: eventObj
  23314. });
  23315. return;
  23316. }
  23317. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  23318. });
  23319. });
  23320. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  23321. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  23322. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  23323. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  23324. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  23325. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  23326. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  23327. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  23328. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  23329. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  23330. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  23331. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  23332. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  23333. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  23334. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  23335. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  23336. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  23337. this.usingNativeControls(this.techGet_('controls'));
  23338. if (this.controls() && !this.usingNativeControls()) {
  23339. this.addTechControlsListeners_();
  23340. }
  23341. // Add the tech element in the DOM if it was not already there
  23342. // Make sure to not insert the original video element if using Html5
  23343. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  23344. prependTo(this.tech_.el(), this.el());
  23345. }
  23346. // Get rid of the original video tag reference after the first tech is loaded
  23347. if (this.tag) {
  23348. this.tag.player = null;
  23349. this.tag = null;
  23350. }
  23351. }
  23352. /**
  23353. * Unload and dispose of the current playback {@link Tech}.
  23354. *
  23355. * @private
  23356. */
  23357. unloadTech_() {
  23358. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  23359. ALL.names.forEach(name => {
  23360. const props = ALL[name];
  23361. this[props.privateName] = this[props.getterName]();
  23362. });
  23363. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  23364. this.isReady_ = false;
  23365. this.tech_.dispose();
  23366. this.tech_ = false;
  23367. if (this.isPosterFromTech_) {
  23368. this.poster_ = '';
  23369. this.trigger('posterchange');
  23370. }
  23371. this.isPosterFromTech_ = false;
  23372. }
  23373. /**
  23374. * Return a reference to the current {@link Tech}.
  23375. * It will print a warning by default about the danger of using the tech directly
  23376. * but any argument that is passed in will silence the warning.
  23377. *
  23378. * @param {*} [safety]
  23379. * Anything passed in to silence the warning
  23380. *
  23381. * @return {Tech}
  23382. * The Tech
  23383. */
  23384. tech(safety) {
  23385. if (safety === undefined) {
  23386. log.warn('Using the tech directly can be dangerous. I hope you know what you\'re doing.\n' + 'See https://github.com/videojs/video.js/issues/2617 for more info.\n');
  23387. }
  23388. return this.tech_;
  23389. }
  23390. /**
  23391. * An object that contains Video.js version.
  23392. *
  23393. * @typedef {Object} PlayerVersion
  23394. *
  23395. * @property {string} 'video.js' - Video.js version
  23396. */
  23397. /**
  23398. * Returns an object with Video.js version.
  23399. *
  23400. * @return {PlayerVersion}
  23401. * An object with Video.js version.
  23402. */
  23403. version() {
  23404. return {
  23405. 'video.js': version
  23406. };
  23407. }
  23408. /**
  23409. * Set up click and touch listeners for the playback element
  23410. *
  23411. * - On desktops: a click on the video itself will toggle playback
  23412. * - On mobile devices: a click on the video toggles controls
  23413. * which is done by toggling the user state between active and
  23414. * inactive
  23415. * - A tap can signal that a user has become active or has become inactive
  23416. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  23417. * quick tap should hide them again (signaling the user is in an inactive
  23418. * viewing state)
  23419. * - In addition to this, we still want the user to be considered inactive after
  23420. * a few seconds of inactivity.
  23421. *
  23422. * > Note: the only part of iOS interaction we can't mimic with this setup
  23423. * is a touch and hold on the video element counting as activity in order to
  23424. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  23425. * on any controls will still keep the user active
  23426. *
  23427. * @private
  23428. */
  23429. addTechControlsListeners_() {
  23430. // Make sure to remove all the previous listeners in case we are called multiple times.
  23431. this.removeTechControlsListeners_();
  23432. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  23433. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  23434. // If the controls were hidden we don't want that to change without a tap event
  23435. // so we'll check if the controls were already showing before reporting user
  23436. // activity
  23437. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  23438. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  23439. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  23440. // The tap listener needs to come after the touchend listener because the tap
  23441. // listener cancels out any reportedUserActivity when setting userActive(false)
  23442. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  23443. }
  23444. /**
  23445. * Remove the listeners used for click and tap controls. This is needed for
  23446. * toggling to controls disabled, where a tap/touch should do nothing.
  23447. *
  23448. * @private
  23449. */
  23450. removeTechControlsListeners_() {
  23451. // We don't want to just use `this.off()` because there might be other needed
  23452. // listeners added by techs that extend this.
  23453. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  23454. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  23455. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  23456. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  23457. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  23458. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  23459. }
  23460. /**
  23461. * Player waits for the tech to be ready
  23462. *
  23463. * @private
  23464. */
  23465. handleTechReady_() {
  23466. this.triggerReady();
  23467. // Keep the same volume as before
  23468. if (this.cache_.volume) {
  23469. this.techCall_('setVolume', this.cache_.volume);
  23470. }
  23471. // Look if the tech found a higher resolution poster while loading
  23472. this.handleTechPosterChange_();
  23473. // Update the duration if available
  23474. this.handleTechDurationChange_();
  23475. }
  23476. /**
  23477. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  23478. *
  23479. * @fires Player#loadstart
  23480. * @listens Tech#loadstart
  23481. * @private
  23482. */
  23483. handleTechLoadStart_() {
  23484. // TODO: Update to use `emptied` event instead. See #1277.
  23485. this.removeClass('vjs-ended', 'vjs-seeking');
  23486. // reset the error state
  23487. this.error(null);
  23488. // Update the duration
  23489. this.handleTechDurationChange_();
  23490. if (!this.paused()) {
  23491. /**
  23492. * Fired when the user agent begins looking for media data
  23493. *
  23494. * @event Player#loadstart
  23495. * @type {Event}
  23496. */
  23497. this.trigger('loadstart');
  23498. } else {
  23499. // reset the hasStarted state
  23500. this.hasStarted(false);
  23501. this.trigger('loadstart');
  23502. }
  23503. // autoplay happens after loadstart for the browser,
  23504. // so we mimic that behavior
  23505. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  23506. }
  23507. /**
  23508. * Handle autoplay string values, rather than the typical boolean
  23509. * values that should be handled by the tech. Note that this is not
  23510. * part of any specification. Valid values and what they do can be
  23511. * found on the autoplay getter at Player#autoplay()
  23512. */
  23513. manualAutoplay_(type) {
  23514. if (!this.tech_ || typeof type !== 'string') {
  23515. return;
  23516. }
  23517. // Save original muted() value, set muted to true, and attempt to play().
  23518. // On promise rejection, restore muted from saved value
  23519. const resolveMuted = () => {
  23520. const previouslyMuted = this.muted();
  23521. this.muted(true);
  23522. const restoreMuted = () => {
  23523. this.muted(previouslyMuted);
  23524. };
  23525. // restore muted on play terminatation
  23526. this.playTerminatedQueue_.push(restoreMuted);
  23527. const mutedPromise = this.play();
  23528. if (!isPromise(mutedPromise)) {
  23529. return;
  23530. }
  23531. return mutedPromise.catch(err => {
  23532. restoreMuted();
  23533. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  23534. });
  23535. };
  23536. let promise;
  23537. // if muted defaults to true
  23538. // the only thing we can do is call play
  23539. if (type === 'any' && !this.muted()) {
  23540. promise = this.play();
  23541. if (isPromise(promise)) {
  23542. promise = promise.catch(resolveMuted);
  23543. }
  23544. } else if (type === 'muted' && !this.muted()) {
  23545. promise = resolveMuted();
  23546. } else {
  23547. promise = this.play();
  23548. }
  23549. if (!isPromise(promise)) {
  23550. return;
  23551. }
  23552. return promise.then(() => {
  23553. this.trigger({
  23554. type: 'autoplay-success',
  23555. autoplay: type
  23556. });
  23557. }).catch(() => {
  23558. this.trigger({
  23559. type: 'autoplay-failure',
  23560. autoplay: type
  23561. });
  23562. });
  23563. }
  23564. /**
  23565. * Update the internal source caches so that we return the correct source from
  23566. * `src()`, `currentSource()`, and `currentSources()`.
  23567. *
  23568. * > Note: `currentSources` will not be updated if the source that is passed in exists
  23569. * in the current `currentSources` cache.
  23570. *
  23571. *
  23572. * @param {Tech~SourceObject} srcObj
  23573. * A string or object source to update our caches to.
  23574. */
  23575. updateSourceCaches_(srcObj = '') {
  23576. let src = srcObj;
  23577. let type = '';
  23578. if (typeof src !== 'string') {
  23579. src = srcObj.src;
  23580. type = srcObj.type;
  23581. }
  23582. // make sure all the caches are set to default values
  23583. // to prevent null checking
  23584. this.cache_.source = this.cache_.source || {};
  23585. this.cache_.sources = this.cache_.sources || [];
  23586. // try to get the type of the src that was passed in
  23587. if (src && !type) {
  23588. type = findMimetype(this, src);
  23589. }
  23590. // update `currentSource` cache always
  23591. this.cache_.source = merge({}, srcObj, {
  23592. src,
  23593. type
  23594. });
  23595. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  23596. const sourceElSources = [];
  23597. const sourceEls = this.$$('source');
  23598. const matchingSourceEls = [];
  23599. for (let i = 0; i < sourceEls.length; i++) {
  23600. const sourceObj = getAttributes(sourceEls[i]);
  23601. sourceElSources.push(sourceObj);
  23602. if (sourceObj.src && sourceObj.src === src) {
  23603. matchingSourceEls.push(sourceObj.src);
  23604. }
  23605. }
  23606. // if we have matching source els but not matching sources
  23607. // the current source cache is not up to date
  23608. if (matchingSourceEls.length && !matchingSources.length) {
  23609. this.cache_.sources = sourceElSources;
  23610. // if we don't have matching source or source els set the
  23611. // sources cache to the `currentSource` cache
  23612. } else if (!matchingSources.length) {
  23613. this.cache_.sources = [this.cache_.source];
  23614. }
  23615. // update the tech `src` cache
  23616. this.cache_.src = src;
  23617. }
  23618. /**
  23619. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  23620. * causing the media element to reload.
  23621. *
  23622. * It will fire for the initial source and each subsequent source.
  23623. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  23624. *
  23625. * The event object for this event contains a `src` property that will contain the source
  23626. * that was available when the event was triggered. This is generally only necessary if Video.js
  23627. * is switching techs while the source was being changed.
  23628. *
  23629. * It is also fired when `load` is called on the player (or media element)
  23630. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  23631. * says that the resource selection algorithm needs to be aborted and restarted.
  23632. * In this case, it is very likely that the `src` property will be set to the
  23633. * empty string `""` to indicate we do not know what the source will be but
  23634. * that it is changing.
  23635. *
  23636. * *This event is currently still experimental and may change in minor releases.*
  23637. * __To use this, pass `enableSourceset` option to the player.__
  23638. *
  23639. * @event Player#sourceset
  23640. * @type {Event}
  23641. * @prop {string} src
  23642. * The source url available when the `sourceset` was triggered.
  23643. * It will be an empty string if we cannot know what the source is
  23644. * but know that the source will change.
  23645. */
  23646. /**
  23647. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  23648. *
  23649. * @fires Player#sourceset
  23650. * @listens Tech#sourceset
  23651. * @private
  23652. */
  23653. handleTechSourceset_(event) {
  23654. // only update the source cache when the source
  23655. // was not updated using the player api
  23656. if (!this.changingSrc_) {
  23657. let updateSourceCaches = src => this.updateSourceCaches_(src);
  23658. const playerSrc = this.currentSource().src;
  23659. const eventSrc = event.src;
  23660. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  23661. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  23662. // if both the tech source and the player source were updated we assume
  23663. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  23664. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  23665. updateSourceCaches = () => {};
  23666. }
  23667. }
  23668. // update the source to the initial source right away
  23669. // in some cases this will be empty string
  23670. updateSourceCaches(eventSrc);
  23671. // if the `sourceset` `src` was an empty string
  23672. // wait for a `loadstart` to update the cache to `currentSrc`.
  23673. // If a sourceset happens before a `loadstart`, we reset the state
  23674. if (!event.src) {
  23675. this.tech_.any(['sourceset', 'loadstart'], e => {
  23676. // if a sourceset happens before a `loadstart` there
  23677. // is nothing to do as this `handleTechSourceset_`
  23678. // will be called again and this will be handled there.
  23679. if (e.type === 'sourceset') {
  23680. return;
  23681. }
  23682. const techSrc = this.techGet_('currentSrc');
  23683. this.lastSource_.tech = techSrc;
  23684. this.updateSourceCaches_(techSrc);
  23685. });
  23686. }
  23687. }
  23688. this.lastSource_ = {
  23689. player: this.currentSource().src,
  23690. tech: event.src
  23691. };
  23692. this.trigger({
  23693. src: event.src,
  23694. type: 'sourceset'
  23695. });
  23696. }
  23697. /**
  23698. * Add/remove the vjs-has-started class
  23699. *
  23700. *
  23701. * @param {boolean} request
  23702. * - true: adds the class
  23703. * - false: remove the class
  23704. *
  23705. * @return {boolean}
  23706. * the boolean value of hasStarted_
  23707. */
  23708. hasStarted(request) {
  23709. if (request === undefined) {
  23710. // act as getter, if we have no request to change
  23711. return this.hasStarted_;
  23712. }
  23713. if (request === this.hasStarted_) {
  23714. return;
  23715. }
  23716. this.hasStarted_ = request;
  23717. if (this.hasStarted_) {
  23718. this.addClass('vjs-has-started');
  23719. } else {
  23720. this.removeClass('vjs-has-started');
  23721. }
  23722. }
  23723. /**
  23724. * Fired whenever the media begins or resumes playback
  23725. *
  23726. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  23727. * @fires Player#play
  23728. * @listens Tech#play
  23729. * @private
  23730. */
  23731. handleTechPlay_() {
  23732. this.removeClass('vjs-ended', 'vjs-paused');
  23733. this.addClass('vjs-playing');
  23734. // hide the poster when the user hits play
  23735. this.hasStarted(true);
  23736. /**
  23737. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  23738. * playback has started or resumed.
  23739. *
  23740. * @event Player#play
  23741. * @type {Event}
  23742. */
  23743. this.trigger('play');
  23744. }
  23745. /**
  23746. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  23747. *
  23748. * If there were any events queued while the playback rate was zero, fire
  23749. * those events now.
  23750. *
  23751. * @private
  23752. * @method Player#handleTechRateChange_
  23753. * @fires Player#ratechange
  23754. * @listens Tech#ratechange
  23755. */
  23756. handleTechRateChange_() {
  23757. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  23758. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  23759. this.queuedCallbacks_ = [];
  23760. }
  23761. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  23762. /**
  23763. * Fires when the playing speed of the audio/video is changed
  23764. *
  23765. * @event Player#ratechange
  23766. * @type {event}
  23767. */
  23768. this.trigger('ratechange');
  23769. }
  23770. /**
  23771. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  23772. *
  23773. * @fires Player#waiting
  23774. * @listens Tech#waiting
  23775. * @private
  23776. */
  23777. handleTechWaiting_() {
  23778. this.addClass('vjs-waiting');
  23779. /**
  23780. * A readyState change on the DOM element has caused playback to stop.
  23781. *
  23782. * @event Player#waiting
  23783. * @type {Event}
  23784. */
  23785. this.trigger('waiting');
  23786. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  23787. // premature removal of the waiting class, wait for the time to change.
  23788. const timeWhenWaiting = this.currentTime();
  23789. const timeUpdateListener = () => {
  23790. if (timeWhenWaiting !== this.currentTime()) {
  23791. this.removeClass('vjs-waiting');
  23792. this.off('timeupdate', timeUpdateListener);
  23793. }
  23794. };
  23795. this.on('timeupdate', timeUpdateListener);
  23796. }
  23797. /**
  23798. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  23799. * > Note: This is not consistent between browsers. See #1351
  23800. *
  23801. * @fires Player#canplay
  23802. * @listens Tech#canplay
  23803. * @private
  23804. */
  23805. handleTechCanPlay_() {
  23806. this.removeClass('vjs-waiting');
  23807. /**
  23808. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  23809. *
  23810. * @event Player#canplay
  23811. * @type {Event}
  23812. */
  23813. this.trigger('canplay');
  23814. }
  23815. /**
  23816. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  23817. *
  23818. * @fires Player#canplaythrough
  23819. * @listens Tech#canplaythrough
  23820. * @private
  23821. */
  23822. handleTechCanPlayThrough_() {
  23823. this.removeClass('vjs-waiting');
  23824. /**
  23825. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  23826. * entire media file can be played without buffering.
  23827. *
  23828. * @event Player#canplaythrough
  23829. * @type {Event}
  23830. */
  23831. this.trigger('canplaythrough');
  23832. }
  23833. /**
  23834. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  23835. *
  23836. * @fires Player#playing
  23837. * @listens Tech#playing
  23838. * @private
  23839. */
  23840. handleTechPlaying_() {
  23841. this.removeClass('vjs-waiting');
  23842. /**
  23843. * The media is no longer blocked from playback, and has started playing.
  23844. *
  23845. * @event Player#playing
  23846. * @type {Event}
  23847. */
  23848. this.trigger('playing');
  23849. }
  23850. /**
  23851. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  23852. *
  23853. * @fires Player#seeking
  23854. * @listens Tech#seeking
  23855. * @private
  23856. */
  23857. handleTechSeeking_() {
  23858. this.addClass('vjs-seeking');
  23859. /**
  23860. * Fired whenever the player is jumping to a new time
  23861. *
  23862. * @event Player#seeking
  23863. * @type {Event}
  23864. */
  23865. this.trigger('seeking');
  23866. }
  23867. /**
  23868. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  23869. *
  23870. * @fires Player#seeked
  23871. * @listens Tech#seeked
  23872. * @private
  23873. */
  23874. handleTechSeeked_() {
  23875. this.removeClass('vjs-seeking', 'vjs-ended');
  23876. /**
  23877. * Fired when the player has finished jumping to a new time
  23878. *
  23879. * @event Player#seeked
  23880. * @type {Event}
  23881. */
  23882. this.trigger('seeked');
  23883. }
  23884. /**
  23885. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  23886. *
  23887. * @fires Player#pause
  23888. * @listens Tech#pause
  23889. * @private
  23890. */
  23891. handleTechPause_() {
  23892. this.removeClass('vjs-playing');
  23893. this.addClass('vjs-paused');
  23894. /**
  23895. * Fired whenever the media has been paused
  23896. *
  23897. * @event Player#pause
  23898. * @type {Event}
  23899. */
  23900. this.trigger('pause');
  23901. }
  23902. /**
  23903. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  23904. *
  23905. * @fires Player#ended
  23906. * @listens Tech#ended
  23907. * @private
  23908. */
  23909. handleTechEnded_() {
  23910. this.addClass('vjs-ended');
  23911. this.removeClass('vjs-waiting');
  23912. if (this.options_.loop) {
  23913. this.currentTime(0);
  23914. this.play();
  23915. } else if (!this.paused()) {
  23916. this.pause();
  23917. }
  23918. /**
  23919. * Fired when the end of the media resource is reached (currentTime == duration)
  23920. *
  23921. * @event Player#ended
  23922. * @type {Event}
  23923. */
  23924. this.trigger('ended');
  23925. }
  23926. /**
  23927. * Fired when the duration of the media resource is first known or changed
  23928. *
  23929. * @listens Tech#durationchange
  23930. * @private
  23931. */
  23932. handleTechDurationChange_() {
  23933. this.duration(this.techGet_('duration'));
  23934. }
  23935. /**
  23936. * Handle a click on the media element to play/pause
  23937. *
  23938. * @param {Event} event
  23939. * the event that caused this function to trigger
  23940. *
  23941. * @listens Tech#click
  23942. * @private
  23943. */
  23944. handleTechClick_(event) {
  23945. // When controls are disabled a click should not toggle playback because
  23946. // the click is considered a control
  23947. if (!this.controls_) {
  23948. return;
  23949. }
  23950. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  23951. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  23952. this.options_.userActions.click.call(this, event);
  23953. } else if (this.paused()) {
  23954. silencePromise(this.play());
  23955. } else {
  23956. this.pause();
  23957. }
  23958. }
  23959. }
  23960. /**
  23961. * Handle a double-click on the media element to enter/exit fullscreen,
  23962. * or exit documentPictureInPicture mode
  23963. *
  23964. * @param {Event} event
  23965. * the event that caused this function to trigger
  23966. *
  23967. * @listens Tech#dblclick
  23968. * @private
  23969. */
  23970. handleTechDoubleClick_(event) {
  23971. if (!this.controls_) {
  23972. return;
  23973. }
  23974. // we do not want to toggle fullscreen state
  23975. // when double-clicking inside a control bar or a modal
  23976. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  23977. if (!inAllowedEls) {
  23978. /*
  23979. * options.userActions.doubleClick
  23980. *
  23981. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  23982. * Set to `false` to disable double-click handling
  23983. * Set to a function to substitute an external double-click handler
  23984. */
  23985. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  23986. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  23987. this.options_.userActions.doubleClick.call(this, event);
  23988. } else if (this.isInPictureInPicture() && !document.pictureInPictureElement) {
  23989. // Checking the presence of `window.documentPictureInPicture.window` complicates
  23990. // tests, checking `document.pictureInPictureElement` also works. It wouldn't
  23991. // be null in regular picture in picture.
  23992. // Exit picture in picture mode. This gesture can't trigger pip on the main window.
  23993. this.exitPictureInPicture();
  23994. } else if (this.isFullscreen()) {
  23995. this.exitFullscreen();
  23996. } else {
  23997. this.requestFullscreen();
  23998. }
  23999. }
  24000. }
  24001. }
  24002. /**
  24003. * Handle a tap on the media element. It will toggle the user
  24004. * activity state, which hides and shows the controls.
  24005. *
  24006. * @listens Tech#tap
  24007. * @private
  24008. */
  24009. handleTechTap_() {
  24010. this.userActive(!this.userActive());
  24011. }
  24012. /**
  24013. * Handle touch to start
  24014. *
  24015. * @listens Tech#touchstart
  24016. * @private
  24017. */
  24018. handleTechTouchStart_() {
  24019. this.userWasActive = this.userActive();
  24020. }
  24021. /**
  24022. * Handle touch to move
  24023. *
  24024. * @listens Tech#touchmove
  24025. * @private
  24026. */
  24027. handleTechTouchMove_() {
  24028. if (this.userWasActive) {
  24029. this.reportUserActivity();
  24030. }
  24031. }
  24032. /**
  24033. * Handle touch to end
  24034. *
  24035. * @param {Event} event
  24036. * the touchend event that triggered
  24037. * this function
  24038. *
  24039. * @listens Tech#touchend
  24040. * @private
  24041. */
  24042. handleTechTouchEnd_(event) {
  24043. // Stop the mouse events from also happening
  24044. if (event.cancelable) {
  24045. event.preventDefault();
  24046. }
  24047. }
  24048. /**
  24049. * @private
  24050. */
  24051. toggleFullscreenClass_() {
  24052. if (this.isFullscreen()) {
  24053. this.addClass('vjs-fullscreen');
  24054. } else {
  24055. this.removeClass('vjs-fullscreen');
  24056. }
  24057. }
  24058. /**
  24059. * when the document fschange event triggers it calls this
  24060. */
  24061. documentFullscreenChange_(e) {
  24062. const targetPlayer = e.target.player;
  24063. // if another player was fullscreen
  24064. // do a null check for targetPlayer because older firefox's would put document as e.target
  24065. if (targetPlayer && targetPlayer !== this) {
  24066. return;
  24067. }
  24068. const el = this.el();
  24069. let isFs = document[this.fsApi_.fullscreenElement] === el;
  24070. if (!isFs && el.matches) {
  24071. isFs = el.matches(':' + this.fsApi_.fullscreen);
  24072. }
  24073. this.isFullscreen(isFs);
  24074. }
  24075. /**
  24076. * Handle Tech Fullscreen Change
  24077. *
  24078. * @param {Event} event
  24079. * the fullscreenchange event that triggered this function
  24080. *
  24081. * @param {Object} data
  24082. * the data that was sent with the event
  24083. *
  24084. * @private
  24085. * @listens Tech#fullscreenchange
  24086. * @fires Player#fullscreenchange
  24087. */
  24088. handleTechFullscreenChange_(event, data) {
  24089. if (data) {
  24090. if (data.nativeIOSFullscreen) {
  24091. this.addClass('vjs-ios-native-fs');
  24092. this.tech_.one('webkitendfullscreen', () => {
  24093. this.removeClass('vjs-ios-native-fs');
  24094. });
  24095. }
  24096. this.isFullscreen(data.isFullscreen);
  24097. }
  24098. }
  24099. handleTechFullscreenError_(event, err) {
  24100. this.trigger('fullscreenerror', err);
  24101. }
  24102. /**
  24103. * @private
  24104. */
  24105. togglePictureInPictureClass_() {
  24106. if (this.isInPictureInPicture()) {
  24107. this.addClass('vjs-picture-in-picture');
  24108. } else {
  24109. this.removeClass('vjs-picture-in-picture');
  24110. }
  24111. }
  24112. /**
  24113. * Handle Tech Enter Picture-in-Picture.
  24114. *
  24115. * @param {Event} event
  24116. * the enterpictureinpicture event that triggered this function
  24117. *
  24118. * @private
  24119. * @listens Tech#enterpictureinpicture
  24120. */
  24121. handleTechEnterPictureInPicture_(event) {
  24122. this.isInPictureInPicture(true);
  24123. }
  24124. /**
  24125. * Handle Tech Leave Picture-in-Picture.
  24126. *
  24127. * @param {Event} event
  24128. * the leavepictureinpicture event that triggered this function
  24129. *
  24130. * @private
  24131. * @listens Tech#leavepictureinpicture
  24132. */
  24133. handleTechLeavePictureInPicture_(event) {
  24134. this.isInPictureInPicture(false);
  24135. }
  24136. /**
  24137. * Fires when an error occurred during the loading of an audio/video.
  24138. *
  24139. * @private
  24140. * @listens Tech#error
  24141. */
  24142. handleTechError_() {
  24143. const error = this.tech_.error();
  24144. if (error) {
  24145. this.error(error);
  24146. }
  24147. }
  24148. /**
  24149. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  24150. *
  24151. * @fires Player#textdata
  24152. * @listens Tech#textdata
  24153. * @private
  24154. */
  24155. handleTechTextData_() {
  24156. let data = null;
  24157. if (arguments.length > 1) {
  24158. data = arguments[1];
  24159. }
  24160. /**
  24161. * Fires when we get a textdata event from tech
  24162. *
  24163. * @event Player#textdata
  24164. * @type {Event}
  24165. */
  24166. this.trigger('textdata', data);
  24167. }
  24168. /**
  24169. * Get object for cached values.
  24170. *
  24171. * @return {Object}
  24172. * get the current object cache
  24173. */
  24174. getCache() {
  24175. return this.cache_;
  24176. }
  24177. /**
  24178. * Resets the internal cache object.
  24179. *
  24180. * Using this function outside the player constructor or reset method may
  24181. * have unintended side-effects.
  24182. *
  24183. * @private
  24184. */
  24185. resetCache_() {
  24186. this.cache_ = {
  24187. // Right now, the currentTime is not _really_ cached because it is always
  24188. // retrieved from the tech (see: currentTime). However, for completeness,
  24189. // we set it to zero here to ensure that if we do start actually caching
  24190. // it, we reset it along with everything else.
  24191. currentTime: 0,
  24192. initTime: 0,
  24193. inactivityTimeout: this.options_.inactivityTimeout,
  24194. duration: NaN,
  24195. lastVolume: 1,
  24196. lastPlaybackRate: this.defaultPlaybackRate(),
  24197. media: null,
  24198. src: '',
  24199. source: {},
  24200. sources: [],
  24201. playbackRates: [],
  24202. volume: 1
  24203. };
  24204. }
  24205. /**
  24206. * Pass values to the playback tech
  24207. *
  24208. * @param {string} [method]
  24209. * the method to call
  24210. *
  24211. * @param {Object} [arg]
  24212. * the argument to pass
  24213. *
  24214. * @private
  24215. */
  24216. techCall_(method, arg) {
  24217. // If it's not ready yet, call method when it is
  24218. this.ready(function () {
  24219. if (method in allowedSetters) {
  24220. return set(this.middleware_, this.tech_, method, arg);
  24221. } else if (method in allowedMediators) {
  24222. return mediate(this.middleware_, this.tech_, method, arg);
  24223. }
  24224. try {
  24225. if (this.tech_) {
  24226. this.tech_[method](arg);
  24227. }
  24228. } catch (e) {
  24229. log(e);
  24230. throw e;
  24231. }
  24232. }, true);
  24233. }
  24234. /**
  24235. * Mediate attempt to call playback tech method
  24236. * and return the value of the method called.
  24237. *
  24238. * @param {string} method
  24239. * Tech method
  24240. *
  24241. * @return {*}
  24242. * Value returned by the tech method called, undefined if tech
  24243. * is not ready or tech method is not present
  24244. *
  24245. * @private
  24246. */
  24247. techGet_(method) {
  24248. if (!this.tech_ || !this.tech_.isReady_) {
  24249. return;
  24250. }
  24251. if (method in allowedGetters) {
  24252. return get(this.middleware_, this.tech_, method);
  24253. } else if (method in allowedMediators) {
  24254. return mediate(this.middleware_, this.tech_, method);
  24255. }
  24256. // Log error when playback tech object is present but method
  24257. // is undefined or unavailable
  24258. try {
  24259. return this.tech_[method]();
  24260. } catch (e) {
  24261. // When building additional tech libs, an expected method may not be defined yet
  24262. if (this.tech_[method] === undefined) {
  24263. log(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  24264. throw e;
  24265. }
  24266. // When a method isn't available on the object it throws a TypeError
  24267. if (e.name === 'TypeError') {
  24268. log(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  24269. this.tech_.isReady_ = false;
  24270. throw e;
  24271. }
  24272. // If error unknown, just log and throw
  24273. log(e);
  24274. throw e;
  24275. }
  24276. }
  24277. /**
  24278. * Attempt to begin playback at the first opportunity.
  24279. *
  24280. * @return {Promise|undefined}
  24281. * Returns a promise if the browser supports Promises (or one
  24282. * was passed in as an option). This promise will be resolved on
  24283. * the return value of play. If this is undefined it will fulfill the
  24284. * promise chain otherwise the promise chain will be fulfilled when
  24285. * the promise from play is fulfilled.
  24286. */
  24287. play() {
  24288. return new Promise(resolve => {
  24289. this.play_(resolve);
  24290. });
  24291. }
  24292. /**
  24293. * The actual logic for play, takes a callback that will be resolved on the
  24294. * return value of play. This allows us to resolve to the play promise if there
  24295. * is one on modern browsers.
  24296. *
  24297. * @private
  24298. * @param {Function} [callback]
  24299. * The callback that should be called when the techs play is actually called
  24300. */
  24301. play_(callback = silencePromise) {
  24302. this.playCallbacks_.push(callback);
  24303. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  24304. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  24305. // treat calls to play_ somewhat like the `one` event function
  24306. if (this.waitToPlay_) {
  24307. this.off(['ready', 'loadstart'], this.waitToPlay_);
  24308. this.waitToPlay_ = null;
  24309. }
  24310. // if the player/tech is not ready or the src itself is not ready
  24311. // queue up a call to play on `ready` or `loadstart`
  24312. if (!this.isReady_ || !isSrcReady) {
  24313. this.waitToPlay_ = e => {
  24314. this.play_();
  24315. };
  24316. this.one(['ready', 'loadstart'], this.waitToPlay_);
  24317. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  24318. // in that case, we need to prime the video element by calling load so it'll be ready in time
  24319. if (!isSrcReady && isSafariOrIOS) {
  24320. this.load();
  24321. }
  24322. return;
  24323. }
  24324. // If the player/tech is ready and we have a source, we can attempt playback.
  24325. const val = this.techGet_('play');
  24326. // For native playback, reset the progress bar if we get a play call from a replay.
  24327. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  24328. if (isNativeReplay) {
  24329. this.resetProgressBar_();
  24330. }
  24331. // play was terminated if the returned value is null
  24332. if (val === null) {
  24333. this.runPlayTerminatedQueue_();
  24334. } else {
  24335. this.runPlayCallbacks_(val);
  24336. }
  24337. }
  24338. /**
  24339. * These functions will be run when if play is terminated. If play
  24340. * runPlayCallbacks_ is run these function will not be run. This allows us
  24341. * to differentiate between a terminated play and an actual call to play.
  24342. */
  24343. runPlayTerminatedQueue_() {
  24344. const queue = this.playTerminatedQueue_.slice(0);
  24345. this.playTerminatedQueue_ = [];
  24346. queue.forEach(function (q) {
  24347. q();
  24348. });
  24349. }
  24350. /**
  24351. * When a callback to play is delayed we have to run these
  24352. * callbacks when play is actually called on the tech. This function
  24353. * runs the callbacks that were delayed and accepts the return value
  24354. * from the tech.
  24355. *
  24356. * @param {undefined|Promise} val
  24357. * The return value from the tech.
  24358. */
  24359. runPlayCallbacks_(val) {
  24360. const callbacks = this.playCallbacks_.slice(0);
  24361. this.playCallbacks_ = [];
  24362. // clear play terminatedQueue since we finished a real play
  24363. this.playTerminatedQueue_ = [];
  24364. callbacks.forEach(function (cb) {
  24365. cb(val);
  24366. });
  24367. }
  24368. /**
  24369. * Pause the video playback
  24370. */
  24371. pause() {
  24372. this.techCall_('pause');
  24373. }
  24374. /**
  24375. * Check if the player is paused or has yet to play
  24376. *
  24377. * @return {boolean}
  24378. * - false: if the media is currently playing
  24379. * - true: if media is not currently playing
  24380. */
  24381. paused() {
  24382. // The initial state of paused should be true (in Safari it's actually false)
  24383. return this.techGet_('paused') === false ? false : true;
  24384. }
  24385. /**
  24386. * Get a TimeRange object representing the current ranges of time that the user
  24387. * has played.
  24388. *
  24389. * @return {TimeRange}
  24390. * A time range object that represents all the increments of time that have
  24391. * been played.
  24392. */
  24393. played() {
  24394. return this.techGet_('played') || createTimeRanges(0, 0);
  24395. }
  24396. /**
  24397. * Sets or returns whether or not the user is "scrubbing". Scrubbing is
  24398. * when the user has clicked the progress bar handle and is
  24399. * dragging it along the progress bar.
  24400. *
  24401. * @param {boolean} [isScrubbing]
  24402. * whether the user is or is not scrubbing
  24403. *
  24404. * @return {boolean|undefined}
  24405. * - The value of scrubbing when getting
  24406. * - Nothing when setting
  24407. */
  24408. scrubbing(isScrubbing) {
  24409. if (typeof isScrubbing === 'undefined') {
  24410. return this.scrubbing_;
  24411. }
  24412. this.scrubbing_ = !!isScrubbing;
  24413. this.techCall_('setScrubbing', this.scrubbing_);
  24414. if (isScrubbing) {
  24415. this.addClass('vjs-scrubbing');
  24416. } else {
  24417. this.removeClass('vjs-scrubbing');
  24418. }
  24419. }
  24420. /**
  24421. * Get or set the current time (in seconds)
  24422. *
  24423. * @param {number|string} [seconds]
  24424. * The time to seek to in seconds
  24425. *
  24426. * @return {number|undefined}
  24427. * - the current time in seconds when getting
  24428. * - Nothing when setting
  24429. */
  24430. currentTime(seconds) {
  24431. if (seconds === undefined) {
  24432. // cache last currentTime and return. default to 0 seconds
  24433. //
  24434. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  24435. // currentTime when scrubbing, but may not provide much performance benefit after all.
  24436. // Should be tested. Also something has to read the actual current time or the cache will
  24437. // never get updated.
  24438. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  24439. return this.cache_.currentTime;
  24440. }
  24441. if (seconds < 0) {
  24442. seconds = 0;
  24443. }
  24444. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  24445. this.cache_.initTime = seconds;
  24446. this.off('canplay', this.boundApplyInitTime_);
  24447. this.one('canplay', this.boundApplyInitTime_);
  24448. return;
  24449. }
  24450. this.techCall_('setCurrentTime', seconds);
  24451. this.cache_.initTime = 0;
  24452. if (isFinite(seconds)) {
  24453. this.cache_.currentTime = Number(seconds);
  24454. }
  24455. }
  24456. /**
  24457. * Apply the value of initTime stored in cache as currentTime.
  24458. *
  24459. * @private
  24460. */
  24461. applyInitTime_() {
  24462. this.currentTime(this.cache_.initTime);
  24463. }
  24464. /**
  24465. * Normally gets the length in time of the video in seconds;
  24466. * in all but the rarest use cases an argument will NOT be passed to the method
  24467. *
  24468. * > **NOTE**: The video must have started loading before the duration can be
  24469. * known, and depending on preload behaviour may not be known until the video starts
  24470. * playing.
  24471. *
  24472. * @fires Player#durationchange
  24473. *
  24474. * @param {number} [seconds]
  24475. * The duration of the video to set in seconds
  24476. *
  24477. * @return {number|undefined}
  24478. * - The duration of the video in seconds when getting
  24479. * - Nothing when setting
  24480. */
  24481. duration(seconds) {
  24482. if (seconds === undefined) {
  24483. // return NaN if the duration is not known
  24484. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  24485. }
  24486. seconds = parseFloat(seconds);
  24487. // Standardize on Infinity for signaling video is live
  24488. if (seconds < 0) {
  24489. seconds = Infinity;
  24490. }
  24491. if (seconds !== this.cache_.duration) {
  24492. // Cache the last set value for optimized scrubbing
  24493. this.cache_.duration = seconds;
  24494. if (seconds === Infinity) {
  24495. this.addClass('vjs-live');
  24496. } else {
  24497. this.removeClass('vjs-live');
  24498. }
  24499. if (!isNaN(seconds)) {
  24500. // Do not fire durationchange unless the duration value is known.
  24501. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  24502. /**
  24503. * @event Player#durationchange
  24504. * @type {Event}
  24505. */
  24506. this.trigger('durationchange');
  24507. }
  24508. }
  24509. }
  24510. /**
  24511. * Calculates how much time is left in the video. Not part
  24512. * of the native video API.
  24513. *
  24514. * @return {number}
  24515. * The time remaining in seconds
  24516. */
  24517. remainingTime() {
  24518. return this.duration() - this.currentTime();
  24519. }
  24520. /**
  24521. * A remaining time function that is intended to be used when
  24522. * the time is to be displayed directly to the user.
  24523. *
  24524. * @return {number}
  24525. * The rounded time remaining in seconds
  24526. */
  24527. remainingTimeDisplay() {
  24528. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  24529. }
  24530. //
  24531. // Kind of like an array of portions of the video that have been downloaded.
  24532. /**
  24533. * Get a TimeRange object with an array of the times of the video
  24534. * that have been downloaded. If you just want the percent of the
  24535. * video that's been downloaded, use bufferedPercent.
  24536. *
  24537. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  24538. *
  24539. * @return {TimeRange}
  24540. * A mock {@link TimeRanges} object (following HTML spec)
  24541. */
  24542. buffered() {
  24543. let buffered = this.techGet_('buffered');
  24544. if (!buffered || !buffered.length) {
  24545. buffered = createTimeRanges(0, 0);
  24546. }
  24547. return buffered;
  24548. }
  24549. /**
  24550. * Get the TimeRanges of the media that are currently available
  24551. * for seeking to.
  24552. *
  24553. * @see [Seekable Spec]{@link https://html.spec.whatwg.org/multipage/media.html#dom-media-seekable}
  24554. *
  24555. * @return {TimeRange}
  24556. * A mock {@link TimeRanges} object (following HTML spec)
  24557. */
  24558. seekable() {
  24559. let seekable = this.techGet_('seekable');
  24560. if (!seekable || !seekable.length) {
  24561. seekable = createTimeRanges(0, 0);
  24562. }
  24563. return seekable;
  24564. }
  24565. /**
  24566. * Returns whether the player is in the "seeking" state.
  24567. *
  24568. * @return {boolean} True if the player is in the seeking state, false if not.
  24569. */
  24570. seeking() {
  24571. return this.techGet_('seeking');
  24572. }
  24573. /**
  24574. * Returns whether the player is in the "ended" state.
  24575. *
  24576. * @return {boolean} True if the player is in the ended state, false if not.
  24577. */
  24578. ended() {
  24579. return this.techGet_('ended');
  24580. }
  24581. /**
  24582. * Returns the current state of network activity for the element, from
  24583. * the codes in the list below.
  24584. * - NETWORK_EMPTY (numeric value 0)
  24585. * The element has not yet been initialised. All attributes are in
  24586. * their initial states.
  24587. * - NETWORK_IDLE (numeric value 1)
  24588. * The element's resource selection algorithm is active and has
  24589. * selected a resource, but it is not actually using the network at
  24590. * this time.
  24591. * - NETWORK_LOADING (numeric value 2)
  24592. * The user agent is actively trying to download data.
  24593. * - NETWORK_NO_SOURCE (numeric value 3)
  24594. * The element's resource selection algorithm is active, but it has
  24595. * not yet found a resource to use.
  24596. *
  24597. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  24598. * @return {number} the current network activity state
  24599. */
  24600. networkState() {
  24601. return this.techGet_('networkState');
  24602. }
  24603. /**
  24604. * Returns a value that expresses the current state of the element
  24605. * with respect to rendering the current playback position, from the
  24606. * codes in the list below.
  24607. * - HAVE_NOTHING (numeric value 0)
  24608. * No information regarding the media resource is available.
  24609. * - HAVE_METADATA (numeric value 1)
  24610. * Enough of the resource has been obtained that the duration of the
  24611. * resource is available.
  24612. * - HAVE_CURRENT_DATA (numeric value 2)
  24613. * Data for the immediate current playback position is available.
  24614. * - HAVE_FUTURE_DATA (numeric value 3)
  24615. * Data for the immediate current playback position is available, as
  24616. * well as enough data for the user agent to advance the current
  24617. * playback position in the direction of playback.
  24618. * - HAVE_ENOUGH_DATA (numeric value 4)
  24619. * The user agent estimates that enough data is available for
  24620. * playback to proceed uninterrupted.
  24621. *
  24622. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  24623. * @return {number} the current playback rendering state
  24624. */
  24625. readyState() {
  24626. return this.techGet_('readyState');
  24627. }
  24628. /**
  24629. * Get the percent (as a decimal) of the video that's been downloaded.
  24630. * This method is not a part of the native HTML video API.
  24631. *
  24632. * @return {number}
  24633. * A decimal between 0 and 1 representing the percent
  24634. * that is buffered 0 being 0% and 1 being 100%
  24635. */
  24636. bufferedPercent() {
  24637. return bufferedPercent(this.buffered(), this.duration());
  24638. }
  24639. /**
  24640. * Get the ending time of the last buffered time range
  24641. * This is used in the progress bar to encapsulate all time ranges.
  24642. *
  24643. * @return {number}
  24644. * The end of the last buffered time range
  24645. */
  24646. bufferedEnd() {
  24647. const buffered = this.buffered();
  24648. const duration = this.duration();
  24649. let end = buffered.end(buffered.length - 1);
  24650. if (end > duration) {
  24651. end = duration;
  24652. }
  24653. return end;
  24654. }
  24655. /**
  24656. * Get or set the current volume of the media
  24657. *
  24658. * @param {number} [percentAsDecimal]
  24659. * The new volume as a decimal percent:
  24660. * - 0 is muted/0%/off
  24661. * - 1.0 is 100%/full
  24662. * - 0.5 is half volume or 50%
  24663. *
  24664. * @return {number|undefined}
  24665. * The current volume as a percent when getting
  24666. */
  24667. volume(percentAsDecimal) {
  24668. let vol;
  24669. if (percentAsDecimal !== undefined) {
  24670. // Force value to between 0 and 1
  24671. vol = Math.max(0, Math.min(1, percentAsDecimal));
  24672. this.cache_.volume = vol;
  24673. this.techCall_('setVolume', vol);
  24674. if (vol > 0) {
  24675. this.lastVolume_(vol);
  24676. }
  24677. return;
  24678. }
  24679. // Default to 1 when returning current volume.
  24680. vol = parseFloat(this.techGet_('volume'));
  24681. return isNaN(vol) ? 1 : vol;
  24682. }
  24683. /**
  24684. * Get the current muted state, or turn mute on or off
  24685. *
  24686. * @param {boolean} [muted]
  24687. * - true to mute
  24688. * - false to unmute
  24689. *
  24690. * @return {boolean|undefined}
  24691. * - true if mute is on and getting
  24692. * - false if mute is off and getting
  24693. * - nothing if setting
  24694. */
  24695. muted(muted) {
  24696. if (muted !== undefined) {
  24697. this.techCall_('setMuted', muted);
  24698. return;
  24699. }
  24700. return this.techGet_('muted') || false;
  24701. }
  24702. /**
  24703. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  24704. * indicates the state of muted on initial playback.
  24705. *
  24706. * ```js
  24707. * var myPlayer = videojs('some-player-id');
  24708. *
  24709. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  24710. *
  24711. * // get, should be false
  24712. * console.log(myPlayer.defaultMuted());
  24713. * // set to true
  24714. * myPlayer.defaultMuted(true);
  24715. * // get should be true
  24716. * console.log(myPlayer.defaultMuted());
  24717. * ```
  24718. *
  24719. * @param {boolean} [defaultMuted]
  24720. * - true to mute
  24721. * - false to unmute
  24722. *
  24723. * @return {boolean|undefined}
  24724. * - true if defaultMuted is on and getting
  24725. * - false if defaultMuted is off and getting
  24726. * - Nothing when setting
  24727. */
  24728. defaultMuted(defaultMuted) {
  24729. if (defaultMuted !== undefined) {
  24730. this.techCall_('setDefaultMuted', defaultMuted);
  24731. }
  24732. return this.techGet_('defaultMuted') || false;
  24733. }
  24734. /**
  24735. * Get the last volume, or set it
  24736. *
  24737. * @param {number} [percentAsDecimal]
  24738. * The new last volume as a decimal percent:
  24739. * - 0 is muted/0%/off
  24740. * - 1.0 is 100%/full
  24741. * - 0.5 is half volume or 50%
  24742. *
  24743. * @return {number|undefined}
  24744. * - The current value of lastVolume as a percent when getting
  24745. * - Nothing when setting
  24746. *
  24747. * @private
  24748. */
  24749. lastVolume_(percentAsDecimal) {
  24750. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  24751. this.cache_.lastVolume = percentAsDecimal;
  24752. return;
  24753. }
  24754. return this.cache_.lastVolume;
  24755. }
  24756. /**
  24757. * Check if current tech can support native fullscreen
  24758. * (e.g. with built in controls like iOS)
  24759. *
  24760. * @return {boolean}
  24761. * if native fullscreen is supported
  24762. */
  24763. supportsFullScreen() {
  24764. return this.techGet_('supportsFullScreen') || false;
  24765. }
  24766. /**
  24767. * Check if the player is in fullscreen mode or tell the player that it
  24768. * is or is not in fullscreen mode.
  24769. *
  24770. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  24771. * property and instead document.fullscreenElement is used. But isFullscreen is
  24772. * still a valuable property for internal player workings.
  24773. *
  24774. * @param {boolean} [isFS]
  24775. * Set the players current fullscreen state
  24776. *
  24777. * @return {boolean|undefined}
  24778. * - true if fullscreen is on and getting
  24779. * - false if fullscreen is off and getting
  24780. * - Nothing when setting
  24781. */
  24782. isFullscreen(isFS) {
  24783. if (isFS !== undefined) {
  24784. const oldValue = this.isFullscreen_;
  24785. this.isFullscreen_ = Boolean(isFS);
  24786. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  24787. // this is the only place where we trigger fullscreenchange events for older browsers
  24788. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  24789. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  24790. /**
  24791. * @event Player#fullscreenchange
  24792. * @type {Event}
  24793. */
  24794. this.trigger('fullscreenchange');
  24795. }
  24796. this.toggleFullscreenClass_();
  24797. return;
  24798. }
  24799. return this.isFullscreen_;
  24800. }
  24801. /**
  24802. * Increase the size of the video to full screen
  24803. * In some browsers, full screen is not supported natively, so it enters
  24804. * "full window mode", where the video fills the browser window.
  24805. * In browsers and devices that support native full screen, sometimes the
  24806. * browser's default controls will be shown, and not the Video.js custom skin.
  24807. * This includes most mobile devices (iOS, Android) and older versions of
  24808. * Safari.
  24809. *
  24810. * @param {Object} [fullscreenOptions]
  24811. * Override the player fullscreen options
  24812. *
  24813. * @fires Player#fullscreenchange
  24814. */
  24815. requestFullscreen(fullscreenOptions) {
  24816. if (this.isInPictureInPicture()) {
  24817. this.exitPictureInPicture();
  24818. }
  24819. const self = this;
  24820. return new Promise((resolve, reject) => {
  24821. function offHandler() {
  24822. self.off('fullscreenerror', errorHandler);
  24823. self.off('fullscreenchange', changeHandler);
  24824. }
  24825. function changeHandler() {
  24826. offHandler();
  24827. resolve();
  24828. }
  24829. function errorHandler(e, err) {
  24830. offHandler();
  24831. reject(err);
  24832. }
  24833. self.one('fullscreenchange', changeHandler);
  24834. self.one('fullscreenerror', errorHandler);
  24835. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  24836. if (promise) {
  24837. promise.then(offHandler, offHandler);
  24838. promise.then(resolve, reject);
  24839. }
  24840. });
  24841. }
  24842. requestFullscreenHelper_(fullscreenOptions) {
  24843. let fsOptions;
  24844. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  24845. // Use defaults or player configured option unless passed directly to this method.
  24846. if (!this.fsApi_.prefixed) {
  24847. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  24848. if (fullscreenOptions !== undefined) {
  24849. fsOptions = fullscreenOptions;
  24850. }
  24851. }
  24852. // This method works as follows:
  24853. // 1. if a fullscreen api is available, use it
  24854. // 1. call requestFullscreen with potential options
  24855. // 2. if we got a promise from above, use it to update isFullscreen()
  24856. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  24857. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  24858. // 3. otherwise, use "fullWindow" mode
  24859. if (this.fsApi_.requestFullscreen) {
  24860. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  24861. // Even on browsers with promise support this may not return a promise
  24862. if (promise) {
  24863. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  24864. }
  24865. return promise;
  24866. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  24867. // we can't take the video.js controls fullscreen but we can go fullscreen
  24868. // with native controls
  24869. this.techCall_('enterFullScreen');
  24870. } else {
  24871. // fullscreen isn't supported so we'll just stretch the video element to
  24872. // fill the viewport
  24873. this.enterFullWindow();
  24874. }
  24875. }
  24876. /**
  24877. * Return the video to its normal size after having been in full screen mode
  24878. *
  24879. * @fires Player#fullscreenchange
  24880. */
  24881. exitFullscreen() {
  24882. const self = this;
  24883. return new Promise((resolve, reject) => {
  24884. function offHandler() {
  24885. self.off('fullscreenerror', errorHandler);
  24886. self.off('fullscreenchange', changeHandler);
  24887. }
  24888. function changeHandler() {
  24889. offHandler();
  24890. resolve();
  24891. }
  24892. function errorHandler(e, err) {
  24893. offHandler();
  24894. reject(err);
  24895. }
  24896. self.one('fullscreenchange', changeHandler);
  24897. self.one('fullscreenerror', errorHandler);
  24898. const promise = self.exitFullscreenHelper_();
  24899. if (promise) {
  24900. promise.then(offHandler, offHandler);
  24901. // map the promise to our resolve/reject methods
  24902. promise.then(resolve, reject);
  24903. }
  24904. });
  24905. }
  24906. exitFullscreenHelper_() {
  24907. if (this.fsApi_.requestFullscreen) {
  24908. const promise = document[this.fsApi_.exitFullscreen]();
  24909. // Even on browsers with promise support this may not return a promise
  24910. if (promise) {
  24911. // we're splitting the promise here, so, we want to catch the
  24912. // potential error so that this chain doesn't have unhandled errors
  24913. silencePromise(promise.then(() => this.isFullscreen(false)));
  24914. }
  24915. return promise;
  24916. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  24917. this.techCall_('exitFullScreen');
  24918. } else {
  24919. this.exitFullWindow();
  24920. }
  24921. }
  24922. /**
  24923. * When fullscreen isn't supported we can stretch the
  24924. * video container to as wide as the browser will let us.
  24925. *
  24926. * @fires Player#enterFullWindow
  24927. */
  24928. enterFullWindow() {
  24929. this.isFullscreen(true);
  24930. this.isFullWindow = true;
  24931. // Storing original doc overflow value to return to when fullscreen is off
  24932. this.docOrigOverflow = document.documentElement.style.overflow;
  24933. // Add listener for esc key to exit fullscreen
  24934. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  24935. // Hide any scroll bars
  24936. document.documentElement.style.overflow = 'hidden';
  24937. // Apply fullscreen styles
  24938. addClass(document.body, 'vjs-full-window');
  24939. /**
  24940. * @event Player#enterFullWindow
  24941. * @type {Event}
  24942. */
  24943. this.trigger('enterFullWindow');
  24944. }
  24945. /**
  24946. * Check for call to either exit full window or
  24947. * full screen on ESC key
  24948. *
  24949. * @param {string} event
  24950. * Event to check for key press
  24951. */
  24952. fullWindowOnEscKey(event) {
  24953. if (event.key === 'Escape') {
  24954. if (this.isFullscreen() === true) {
  24955. if (!this.isFullWindow) {
  24956. this.exitFullscreen();
  24957. } else {
  24958. this.exitFullWindow();
  24959. }
  24960. }
  24961. }
  24962. }
  24963. /**
  24964. * Exit full window
  24965. *
  24966. * @fires Player#exitFullWindow
  24967. */
  24968. exitFullWindow() {
  24969. this.isFullscreen(false);
  24970. this.isFullWindow = false;
  24971. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  24972. // Unhide scroll bars.
  24973. document.documentElement.style.overflow = this.docOrigOverflow;
  24974. // Remove fullscreen styles
  24975. removeClass(document.body, 'vjs-full-window');
  24976. // Resize the box, controller, and poster to original sizes
  24977. // this.positionAll();
  24978. /**
  24979. * @event Player#exitFullWindow
  24980. * @type {Event}
  24981. */
  24982. this.trigger('exitFullWindow');
  24983. }
  24984. /**
  24985. * Get or set disable Picture-in-Picture mode.
  24986. *
  24987. * @param {boolean} [value]
  24988. * - true will disable Picture-in-Picture mode
  24989. * - false will enable Picture-in-Picture mode
  24990. */
  24991. disablePictureInPicture(value) {
  24992. if (value === undefined) {
  24993. return this.techGet_('disablePictureInPicture');
  24994. }
  24995. this.techCall_('setDisablePictureInPicture', value);
  24996. this.options_.disablePictureInPicture = value;
  24997. this.trigger('disablepictureinpicturechanged');
  24998. }
  24999. /**
  25000. * Check if the player is in Picture-in-Picture mode or tell the player that it
  25001. * is or is not in Picture-in-Picture mode.
  25002. *
  25003. * @param {boolean} [isPiP]
  25004. * Set the players current Picture-in-Picture state
  25005. *
  25006. * @return {boolean|undefined}
  25007. * - true if Picture-in-Picture is on and getting
  25008. * - false if Picture-in-Picture is off and getting
  25009. * - nothing if setting
  25010. */
  25011. isInPictureInPicture(isPiP) {
  25012. if (isPiP !== undefined) {
  25013. this.isInPictureInPicture_ = !!isPiP;
  25014. this.togglePictureInPictureClass_();
  25015. return;
  25016. }
  25017. return !!this.isInPictureInPicture_;
  25018. }
  25019. /**
  25020. * Create a floating video window always on top of other windows so that users may
  25021. * continue consuming media while they interact with other content sites, or
  25022. * applications on their device.
  25023. *
  25024. * This can use document picture-in-picture or element picture in picture
  25025. *
  25026. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  25027. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  25028. *
  25029. *
  25030. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  25031. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  25032. *
  25033. * @fires Player#enterpictureinpicture
  25034. *
  25035. * @return {Promise}
  25036. * A promise with a Picture-in-Picture window.
  25037. */
  25038. requestPictureInPicture() {
  25039. if (this.options_.enableDocumentPictureInPicture && window.documentPictureInPicture) {
  25040. const pipContainer = document.createElement(this.el().tagName);
  25041. pipContainer.classList = this.el().classList;
  25042. pipContainer.classList.add('vjs-pip-container');
  25043. if (this.posterImage) {
  25044. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  25045. }
  25046. if (this.titleBar) {
  25047. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  25048. }
  25049. pipContainer.appendChild(createEl('p', {
  25050. className: 'vjs-pip-text'
  25051. }, {}, this.localize('Playing in picture-in-picture')));
  25052. return window.documentPictureInPicture.requestWindow({
  25053. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  25054. width: this.videoWidth(),
  25055. height: this.videoHeight()
  25056. }).then(pipWindow => {
  25057. copyStyleSheetsToWindow(pipWindow);
  25058. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  25059. pipWindow.document.body.appendChild(this.el_);
  25060. pipWindow.document.body.classList.add('vjs-pip-window');
  25061. this.player_.isInPictureInPicture(true);
  25062. this.player_.trigger({
  25063. type: 'enterpictureinpicture',
  25064. pipWindow
  25065. });
  25066. // Listen for the PiP closing event to move the video back.
  25067. pipWindow.addEventListener('pagehide', event => {
  25068. const pipVideo = event.target.querySelector('.video-js');
  25069. pipContainer.parentNode.replaceChild(pipVideo, pipContainer);
  25070. this.player_.isInPictureInPicture(false);
  25071. this.player_.trigger('leavepictureinpicture');
  25072. });
  25073. return pipWindow;
  25074. });
  25075. }
  25076. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  25077. /**
  25078. * This event fires when the player enters picture in picture mode
  25079. *
  25080. * @event Player#enterpictureinpicture
  25081. * @type {Event}
  25082. */
  25083. return this.techGet_('requestPictureInPicture');
  25084. }
  25085. return Promise.reject('No PiP mode is available');
  25086. }
  25087. /**
  25088. * Exit Picture-in-Picture mode.
  25089. *
  25090. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  25091. *
  25092. * @fires Player#leavepictureinpicture
  25093. *
  25094. * @return {Promise}
  25095. * A promise.
  25096. */
  25097. exitPictureInPicture() {
  25098. if (window.documentPictureInPicture && window.documentPictureInPicture.window) {
  25099. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the pagehide handler
  25100. window.documentPictureInPicture.window.close();
  25101. return Promise.resolve();
  25102. }
  25103. if ('pictureInPictureEnabled' in document) {
  25104. /**
  25105. * This event fires when the player leaves picture in picture mode
  25106. *
  25107. * @event Player#leavepictureinpicture
  25108. * @type {Event}
  25109. */
  25110. return document.exitPictureInPicture();
  25111. }
  25112. }
  25113. /**
  25114. * Called when this Player has focus and a key gets pressed down, or when
  25115. * any Component of this player receives a key press that it doesn't handle.
  25116. * This allows player-wide hotkeys (either as defined below, or optionally
  25117. * by an external function).
  25118. *
  25119. * @param {KeyboardEvent} event
  25120. * The `keydown` event that caused this function to be called.
  25121. *
  25122. * @listens keydown
  25123. */
  25124. handleKeyDown(event) {
  25125. const {
  25126. userActions
  25127. } = this.options_;
  25128. // Bail out if hotkeys are not configured.
  25129. if (!userActions || !userActions.hotkeys) {
  25130. return;
  25131. }
  25132. // Function that determines whether or not to exclude an element from
  25133. // hotkeys handling.
  25134. const excludeElement = el => {
  25135. const tagName = el.tagName.toLowerCase();
  25136. // The first and easiest test is for `contenteditable` elements.
  25137. if (el.isContentEditable) {
  25138. return true;
  25139. }
  25140. // Inputs matching these types will still trigger hotkey handling as
  25141. // they are not text inputs.
  25142. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  25143. if (tagName === 'input') {
  25144. return allowedInputTypes.indexOf(el.type) === -1;
  25145. }
  25146. // The final test is by tag name. These tags will be excluded entirely.
  25147. const excludedTags = ['textarea'];
  25148. return excludedTags.indexOf(tagName) !== -1;
  25149. };
  25150. // Bail out if the user is focused on an interactive form element.
  25151. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  25152. return;
  25153. }
  25154. if (typeof userActions.hotkeys === 'function') {
  25155. userActions.hotkeys.call(this, event);
  25156. } else {
  25157. this.handleHotkeys(event);
  25158. }
  25159. }
  25160. /**
  25161. * Called when this Player receives a hotkey keydown event.
  25162. * Supported player-wide hotkeys are:
  25163. *
  25164. * f - toggle fullscreen
  25165. * m - toggle mute
  25166. * k or Space - toggle play/pause
  25167. *
  25168. * @param {Event} event
  25169. * The `keydown` event that caused this function to be called.
  25170. */
  25171. handleHotkeys(event) {
  25172. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  25173. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  25174. const {
  25175. fullscreenKey = keydownEvent => event.key.toLowerCase() === 'f',
  25176. muteKey = keydownEvent => event.key.toLowerCase() === 'm',
  25177. playPauseKey = keydownEvent => event.key.toLowerCase() === 'k' || event.key.toLowerCase() === ' '
  25178. } = hotkeys;
  25179. if (fullscreenKey.call(this, event)) {
  25180. event.preventDefault();
  25181. event.stopPropagation();
  25182. const FSToggle = Component.getComponent('FullscreenToggle');
  25183. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  25184. FSToggle.prototype.handleClick.call(this, event);
  25185. }
  25186. } else if (muteKey.call(this, event)) {
  25187. event.preventDefault();
  25188. event.stopPropagation();
  25189. const MuteToggle = Component.getComponent('MuteToggle');
  25190. MuteToggle.prototype.handleClick.call(this, event);
  25191. } else if (playPauseKey.call(this, event)) {
  25192. event.preventDefault();
  25193. event.stopPropagation();
  25194. const PlayToggle = Component.getComponent('PlayToggle');
  25195. PlayToggle.prototype.handleClick.call(this, event);
  25196. }
  25197. }
  25198. /**
  25199. * Check whether the player can play a given mimetype
  25200. *
  25201. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  25202. *
  25203. * @param {string} type
  25204. * The mimetype to check
  25205. *
  25206. * @return {string}
  25207. * 'probably', 'maybe', or '' (empty string)
  25208. */
  25209. canPlayType(type) {
  25210. let can;
  25211. // Loop through each playback technology in the options order
  25212. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  25213. const techName = j[i];
  25214. let tech = Tech.getTech(techName);
  25215. // Support old behavior of techs being registered as components.
  25216. // Remove once that deprecated behavior is removed.
  25217. if (!tech) {
  25218. tech = Component.getComponent(techName);
  25219. }
  25220. // Check if the current tech is defined before continuing
  25221. if (!tech) {
  25222. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  25223. continue;
  25224. }
  25225. // Check if the browser supports this technology
  25226. if (tech.isSupported()) {
  25227. can = tech.canPlayType(type);
  25228. if (can) {
  25229. return can;
  25230. }
  25231. }
  25232. }
  25233. return '';
  25234. }
  25235. /**
  25236. * Select source based on tech-order or source-order
  25237. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  25238. * defaults to tech-order selection
  25239. *
  25240. * @param {Array} sources
  25241. * The sources for a media asset
  25242. *
  25243. * @return {Object|boolean}
  25244. * Object of source and tech order or false
  25245. */
  25246. selectSource(sources) {
  25247. // Get only the techs specified in `techOrder` that exist and are supported by the
  25248. // current platform
  25249. const techs = this.options_.techOrder.map(techName => {
  25250. return [techName, Tech.getTech(techName)];
  25251. }).filter(([techName, tech]) => {
  25252. // Check if the current tech is defined before continuing
  25253. if (tech) {
  25254. // Check if the browser supports this technology
  25255. return tech.isSupported();
  25256. }
  25257. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  25258. return false;
  25259. });
  25260. // Iterate over each `innerArray` element once per `outerArray` element and execute
  25261. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  25262. // that value.
  25263. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  25264. let found;
  25265. outerArray.some(outerChoice => {
  25266. return innerArray.some(innerChoice => {
  25267. found = tester(outerChoice, innerChoice);
  25268. if (found) {
  25269. return true;
  25270. }
  25271. });
  25272. });
  25273. return found;
  25274. };
  25275. let foundSourceAndTech;
  25276. const flip = fn => (a, b) => fn(b, a);
  25277. const finder = ([techName, tech], source) => {
  25278. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  25279. return {
  25280. source,
  25281. tech: techName
  25282. };
  25283. }
  25284. };
  25285. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  25286. // to select from them based on their priority.
  25287. if (this.options_.sourceOrder) {
  25288. // Source-first ordering
  25289. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  25290. } else {
  25291. // Tech-first ordering
  25292. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  25293. }
  25294. return foundSourceAndTech || false;
  25295. }
  25296. /**
  25297. * Executes source setting and getting logic
  25298. *
  25299. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  25300. * A SourceObject, an array of SourceObjects, or a string referencing
  25301. * a URL to a media source. It is _highly recommended_ that an object
  25302. * or array of objects is used here, so that source selection
  25303. * algorithms can take the `type` into account.
  25304. *
  25305. * If not provided, this method acts as a getter.
  25306. * @param {boolean} [isRetry]
  25307. * Indicates whether this is being called internally as a result of a retry
  25308. *
  25309. * @return {string|undefined}
  25310. * If the `source` argument is missing, returns the current source
  25311. * URL. Otherwise, returns nothing/undefined.
  25312. */
  25313. handleSrc_(source, isRetry) {
  25314. // getter usage
  25315. if (typeof source === 'undefined') {
  25316. return this.cache_.src || '';
  25317. }
  25318. // Reset retry behavior for new source
  25319. if (this.resetRetryOnError_) {
  25320. this.resetRetryOnError_();
  25321. }
  25322. // filter out invalid sources and turn our source into
  25323. // an array of source objects
  25324. const sources = filterSource(source);
  25325. // if a source was passed in then it is invalid because
  25326. // it was filtered to a zero length Array. So we have to
  25327. // show an error
  25328. if (!sources.length) {
  25329. this.setTimeout(function () {
  25330. this.error({
  25331. code: 4,
  25332. message: this.options_.notSupportedMessage
  25333. });
  25334. }, 0);
  25335. return;
  25336. }
  25337. // initial sources
  25338. this.changingSrc_ = true;
  25339. // Only update the cached source list if we are not retrying a new source after error,
  25340. // since in that case we want to include the failed source(s) in the cache
  25341. if (!isRetry) {
  25342. this.cache_.sources = sources;
  25343. }
  25344. this.updateSourceCaches_(sources[0]);
  25345. // middlewareSource is the source after it has been changed by middleware
  25346. setSource(this, sources[0], (middlewareSource, mws) => {
  25347. this.middleware_ = mws;
  25348. // since sourceSet is async we have to update the cache again after we select a source since
  25349. // the source that is selected could be out of order from the cache update above this callback.
  25350. if (!isRetry) {
  25351. this.cache_.sources = sources;
  25352. }
  25353. this.updateSourceCaches_(middlewareSource);
  25354. const err = this.src_(middlewareSource);
  25355. if (err) {
  25356. if (sources.length > 1) {
  25357. return this.handleSrc_(sources.slice(1));
  25358. }
  25359. this.changingSrc_ = false;
  25360. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  25361. this.setTimeout(function () {
  25362. this.error({
  25363. code: 4,
  25364. message: this.options_.notSupportedMessage
  25365. });
  25366. }, 0);
  25367. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  25368. // this needs a better comment about why this is needed
  25369. this.triggerReady();
  25370. return;
  25371. }
  25372. setTech(mws, this.tech_);
  25373. });
  25374. // Try another available source if this one fails before playback.
  25375. if (sources.length > 1) {
  25376. const retry = () => {
  25377. // Remove the error modal
  25378. this.error(null);
  25379. this.handleSrc_(sources.slice(1), true);
  25380. };
  25381. const stopListeningForErrors = () => {
  25382. this.off('error', retry);
  25383. };
  25384. this.one('error', retry);
  25385. this.one('playing', stopListeningForErrors);
  25386. this.resetRetryOnError_ = () => {
  25387. this.off('error', retry);
  25388. this.off('playing', stopListeningForErrors);
  25389. };
  25390. }
  25391. }
  25392. /**
  25393. * Get or set the video source.
  25394. *
  25395. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  25396. * A SourceObject, an array of SourceObjects, or a string referencing
  25397. * a URL to a media source. It is _highly recommended_ that an object
  25398. * or array of objects is used here, so that source selection
  25399. * algorithms can take the `type` into account.
  25400. *
  25401. * If not provided, this method acts as a getter.
  25402. *
  25403. * @return {string|undefined}
  25404. * If the `source` argument is missing, returns the current source
  25405. * URL. Otherwise, returns nothing/undefined.
  25406. */
  25407. src(source) {
  25408. return this.handleSrc_(source, false);
  25409. }
  25410. /**
  25411. * Set the source object on the tech, returns a boolean that indicates whether
  25412. * there is a tech that can play the source or not
  25413. *
  25414. * @param {Tech~SourceObject} source
  25415. * The source object to set on the Tech
  25416. *
  25417. * @return {boolean}
  25418. * - True if there is no Tech to playback this source
  25419. * - False otherwise
  25420. *
  25421. * @private
  25422. */
  25423. src_(source) {
  25424. const sourceTech = this.selectSource([source]);
  25425. if (!sourceTech) {
  25426. return true;
  25427. }
  25428. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  25429. this.changingSrc_ = true;
  25430. // load this technology with the chosen source
  25431. this.loadTech_(sourceTech.tech, sourceTech.source);
  25432. this.tech_.ready(() => {
  25433. this.changingSrc_ = false;
  25434. });
  25435. return false;
  25436. }
  25437. // wait until the tech is ready to set the source
  25438. // and set it synchronously if possible (#2326)
  25439. this.ready(function () {
  25440. // The setSource tech method was added with source handlers
  25441. // so older techs won't support it
  25442. // We need to check the direct prototype for the case where subclasses
  25443. // of the tech do not support source handlers
  25444. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  25445. this.techCall_('setSource', source);
  25446. } else {
  25447. this.techCall_('src', source.src);
  25448. }
  25449. this.changingSrc_ = false;
  25450. }, true);
  25451. return false;
  25452. }
  25453. /**
  25454. * Add a <source> element to the <video> element.
  25455. *
  25456. * @param {string} srcUrl
  25457. * The URL of the video source.
  25458. *
  25459. * @param {string} [mimeType]
  25460. * The MIME type of the video source. Optional but recommended.
  25461. *
  25462. * @return {boolean}
  25463. * Returns true if the source element was successfully added, false otherwise.
  25464. */
  25465. addSourceElement(srcUrl, mimeType) {
  25466. if (!this.tech_) {
  25467. return false;
  25468. }
  25469. return this.tech_.addSourceElement(srcUrl, mimeType);
  25470. }
  25471. /**
  25472. * Remove a <source> element from the <video> element by its URL.
  25473. *
  25474. * @param {string} srcUrl
  25475. * The URL of the source to remove.
  25476. *
  25477. * @return {boolean}
  25478. * Returns true if the source element was successfully removed, false otherwise.
  25479. */
  25480. removeSourceElement(srcUrl) {
  25481. if (!this.tech_) {
  25482. return false;
  25483. }
  25484. return this.tech_.removeSourceElement(srcUrl);
  25485. }
  25486. /**
  25487. * Begin loading the src data.
  25488. */
  25489. load() {
  25490. // Workaround to use the load method with the VHS.
  25491. // Does not cover the case when the load method is called directly from the mediaElement.
  25492. if (this.tech_ && this.tech_.vhs) {
  25493. this.src(this.currentSource());
  25494. return;
  25495. }
  25496. this.techCall_('load');
  25497. }
  25498. /**
  25499. * Reset the player. Loads the first tech in the techOrder,
  25500. * removes all the text tracks in the existing `tech`,
  25501. * and calls `reset` on the `tech`.
  25502. */
  25503. reset() {
  25504. if (this.paused()) {
  25505. this.doReset_();
  25506. } else {
  25507. const playPromise = this.play();
  25508. silencePromise(playPromise.then(() => this.doReset_()));
  25509. }
  25510. }
  25511. doReset_() {
  25512. if (this.tech_) {
  25513. this.tech_.clearTracks('text');
  25514. }
  25515. this.removeClass('vjs-playing');
  25516. this.addClass('vjs-paused');
  25517. this.resetCache_();
  25518. this.poster('');
  25519. this.loadTech_(this.options_.techOrder[0], null);
  25520. this.techCall_('reset');
  25521. this.resetControlBarUI_();
  25522. this.error(null);
  25523. if (this.titleBar) {
  25524. this.titleBar.update({
  25525. title: undefined,
  25526. description: undefined
  25527. });
  25528. }
  25529. if (isEvented(this)) {
  25530. this.trigger('playerreset');
  25531. }
  25532. }
  25533. /**
  25534. * Reset Control Bar's UI by calling sub-methods that reset
  25535. * all of Control Bar's components
  25536. */
  25537. resetControlBarUI_() {
  25538. this.resetProgressBar_();
  25539. this.resetPlaybackRate_();
  25540. this.resetVolumeBar_();
  25541. }
  25542. /**
  25543. * Reset tech's progress so progress bar is reset in the UI
  25544. */
  25545. resetProgressBar_() {
  25546. this.currentTime(0);
  25547. const {
  25548. currentTimeDisplay,
  25549. durationDisplay,
  25550. progressControl,
  25551. remainingTimeDisplay
  25552. } = this.controlBar || {};
  25553. const {
  25554. seekBar
  25555. } = progressControl || {};
  25556. if (currentTimeDisplay) {
  25557. currentTimeDisplay.updateContent();
  25558. }
  25559. if (durationDisplay) {
  25560. durationDisplay.updateContent();
  25561. }
  25562. if (remainingTimeDisplay) {
  25563. remainingTimeDisplay.updateContent();
  25564. }
  25565. if (seekBar) {
  25566. seekBar.update();
  25567. if (seekBar.loadProgressBar) {
  25568. seekBar.loadProgressBar.update();
  25569. }
  25570. }
  25571. }
  25572. /**
  25573. * Reset Playback ratio
  25574. */
  25575. resetPlaybackRate_() {
  25576. this.playbackRate(this.defaultPlaybackRate());
  25577. this.handleTechRateChange_();
  25578. }
  25579. /**
  25580. * Reset Volume bar
  25581. */
  25582. resetVolumeBar_() {
  25583. this.volume(1.0);
  25584. this.trigger('volumechange');
  25585. }
  25586. /**
  25587. * Returns all of the current source objects.
  25588. *
  25589. * @return {Tech~SourceObject[]}
  25590. * The current source objects
  25591. */
  25592. currentSources() {
  25593. const source = this.currentSource();
  25594. const sources = [];
  25595. // assume `{}` or `{ src }`
  25596. if (Object.keys(source).length !== 0) {
  25597. sources.push(source);
  25598. }
  25599. return this.cache_.sources || sources;
  25600. }
  25601. /**
  25602. * Returns the current source object.
  25603. *
  25604. * @return {Tech~SourceObject}
  25605. * The current source object
  25606. */
  25607. currentSource() {
  25608. return this.cache_.source || {};
  25609. }
  25610. /**
  25611. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  25612. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  25613. *
  25614. * @return {string}
  25615. * The current source
  25616. */
  25617. currentSrc() {
  25618. return this.currentSource() && this.currentSource().src || '';
  25619. }
  25620. /**
  25621. * Get the current source type e.g. video/mp4
  25622. * This can allow you rebuild the current source object so that you could load the same
  25623. * source and tech later
  25624. *
  25625. * @return {string}
  25626. * The source MIME type
  25627. */
  25628. currentType() {
  25629. return this.currentSource() && this.currentSource().type || '';
  25630. }
  25631. /**
  25632. * Get or set the preload attribute
  25633. *
  25634. * @param {'none'|'auto'|'metadata'} [value]
  25635. * Preload mode to pass to tech
  25636. *
  25637. * @return {string|undefined}
  25638. * - The preload attribute value when getting
  25639. * - Nothing when setting
  25640. */
  25641. preload(value) {
  25642. if (value !== undefined) {
  25643. this.techCall_('setPreload', value);
  25644. this.options_.preload = value;
  25645. return;
  25646. }
  25647. return this.techGet_('preload');
  25648. }
  25649. /**
  25650. * Get or set the autoplay option. When this is a boolean it will
  25651. * modify the attribute on the tech. When this is a string the attribute on
  25652. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  25653. *
  25654. * @param {boolean|'play'|'muted'|'any'} [value]
  25655. * - true: autoplay using the browser behavior
  25656. * - false: do not autoplay
  25657. * - 'play': call play() on every loadstart
  25658. * - 'muted': call muted() then play() on every loadstart
  25659. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  25660. * - *: values other than those listed here will be set `autoplay` to true
  25661. *
  25662. * @return {boolean|string|undefined}
  25663. * - The current value of autoplay when getting
  25664. * - Nothing when setting
  25665. */
  25666. autoplay(value) {
  25667. // getter usage
  25668. if (value === undefined) {
  25669. return this.options_.autoplay || false;
  25670. }
  25671. let techAutoplay;
  25672. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  25673. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  25674. this.options_.autoplay = value;
  25675. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  25676. techAutoplay = false;
  25677. // any falsy value sets autoplay to false in the browser,
  25678. // lets do the same
  25679. } else if (!value) {
  25680. this.options_.autoplay = false;
  25681. // any other value (ie truthy) sets autoplay to true
  25682. } else {
  25683. this.options_.autoplay = true;
  25684. }
  25685. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  25686. // if we don't have a tech then we do not queue up
  25687. // a setAutoplay call on tech ready. We do this because the
  25688. // autoplay option will be passed in the constructor and we
  25689. // do not need to set it twice
  25690. if (this.tech_) {
  25691. this.techCall_('setAutoplay', techAutoplay);
  25692. }
  25693. }
  25694. /**
  25695. * Set or unset the playsinline attribute.
  25696. * Playsinline tells the browser that non-fullscreen playback is preferred.
  25697. *
  25698. * @param {boolean} [value]
  25699. * - true means that we should try to play inline by default
  25700. * - false means that we should use the browser's default playback mode,
  25701. * which in most cases is inline. iOS Safari is a notable exception
  25702. * and plays fullscreen by default.
  25703. *
  25704. * @return {string|undefined}
  25705. * - the current value of playsinline
  25706. * - Nothing when setting
  25707. *
  25708. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  25709. */
  25710. playsinline(value) {
  25711. if (value !== undefined) {
  25712. this.techCall_('setPlaysinline', value);
  25713. this.options_.playsinline = value;
  25714. }
  25715. return this.techGet_('playsinline');
  25716. }
  25717. /**
  25718. * Get or set the loop attribute on the video element.
  25719. *
  25720. * @param {boolean} [value]
  25721. * - true means that we should loop the video
  25722. * - false means that we should not loop the video
  25723. *
  25724. * @return {boolean|undefined}
  25725. * - The current value of loop when getting
  25726. * - Nothing when setting
  25727. */
  25728. loop(value) {
  25729. if (value !== undefined) {
  25730. this.techCall_('setLoop', value);
  25731. this.options_.loop = value;
  25732. return;
  25733. }
  25734. return this.techGet_('loop');
  25735. }
  25736. /**
  25737. * Get or set the poster image source url
  25738. *
  25739. * @fires Player#posterchange
  25740. *
  25741. * @param {string} [src]
  25742. * Poster image source URL
  25743. *
  25744. * @return {string|undefined}
  25745. * - The current value of poster when getting
  25746. * - Nothing when setting
  25747. */
  25748. poster(src) {
  25749. if (src === undefined) {
  25750. return this.poster_;
  25751. }
  25752. // The correct way to remove a poster is to set as an empty string
  25753. // other falsey values will throw errors
  25754. if (!src) {
  25755. src = '';
  25756. }
  25757. if (src === this.poster_) {
  25758. return;
  25759. }
  25760. // update the internal poster variable
  25761. this.poster_ = src;
  25762. // update the tech's poster
  25763. this.techCall_('setPoster', src);
  25764. this.isPosterFromTech_ = false;
  25765. // alert components that the poster has been set
  25766. /**
  25767. * This event fires when the poster image is changed on the player.
  25768. *
  25769. * @event Player#posterchange
  25770. * @type {Event}
  25771. */
  25772. this.trigger('posterchange');
  25773. }
  25774. /**
  25775. * Some techs (e.g. YouTube) can provide a poster source in an
  25776. * asynchronous way. We want the poster component to use this
  25777. * poster source so that it covers up the tech's controls.
  25778. * (YouTube's play button). However we only want to use this
  25779. * source if the player user hasn't set a poster through
  25780. * the normal APIs.
  25781. *
  25782. * @fires Player#posterchange
  25783. * @listens Tech#posterchange
  25784. * @private
  25785. */
  25786. handleTechPosterChange_() {
  25787. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  25788. const newPoster = this.tech_.poster() || '';
  25789. if (newPoster !== this.poster_) {
  25790. this.poster_ = newPoster;
  25791. this.isPosterFromTech_ = true;
  25792. // Let components know the poster has changed
  25793. this.trigger('posterchange');
  25794. }
  25795. }
  25796. }
  25797. /**
  25798. * Get or set whether or not the controls are showing.
  25799. *
  25800. * @fires Player#controlsenabled
  25801. *
  25802. * @param {boolean} [bool]
  25803. * - true to turn controls on
  25804. * - false to turn controls off
  25805. *
  25806. * @return {boolean|undefined}
  25807. * - The current value of controls when getting
  25808. * - Nothing when setting
  25809. */
  25810. controls(bool) {
  25811. if (bool === undefined) {
  25812. return !!this.controls_;
  25813. }
  25814. bool = !!bool;
  25815. // Don't trigger a change event unless it actually changed
  25816. if (this.controls_ === bool) {
  25817. return;
  25818. }
  25819. this.controls_ = bool;
  25820. if (this.usingNativeControls()) {
  25821. this.techCall_('setControls', bool);
  25822. }
  25823. if (this.controls_) {
  25824. this.removeClass('vjs-controls-disabled');
  25825. this.addClass('vjs-controls-enabled');
  25826. /**
  25827. * @event Player#controlsenabled
  25828. * @type {Event}
  25829. */
  25830. this.trigger('controlsenabled');
  25831. if (!this.usingNativeControls()) {
  25832. this.addTechControlsListeners_();
  25833. }
  25834. } else {
  25835. this.removeClass('vjs-controls-enabled');
  25836. this.addClass('vjs-controls-disabled');
  25837. /**
  25838. * @event Player#controlsdisabled
  25839. * @type {Event}
  25840. */
  25841. this.trigger('controlsdisabled');
  25842. if (!this.usingNativeControls()) {
  25843. this.removeTechControlsListeners_();
  25844. }
  25845. }
  25846. }
  25847. /**
  25848. * Toggle native controls on/off. Native controls are the controls built into
  25849. * devices (e.g. default iPhone controls) or other techs
  25850. * (e.g. Vimeo Controls)
  25851. * **This should only be set by the current tech, because only the tech knows
  25852. * if it can support native controls**
  25853. *
  25854. * @fires Player#usingnativecontrols
  25855. * @fires Player#usingcustomcontrols
  25856. *
  25857. * @param {boolean} [bool]
  25858. * - true to turn native controls on
  25859. * - false to turn native controls off
  25860. *
  25861. * @return {boolean|undefined}
  25862. * - The current value of native controls when getting
  25863. * - Nothing when setting
  25864. */
  25865. usingNativeControls(bool) {
  25866. if (bool === undefined) {
  25867. return !!this.usingNativeControls_;
  25868. }
  25869. bool = !!bool;
  25870. // Don't trigger a change event unless it actually changed
  25871. if (this.usingNativeControls_ === bool) {
  25872. return;
  25873. }
  25874. this.usingNativeControls_ = bool;
  25875. if (this.usingNativeControls_) {
  25876. this.addClass('vjs-using-native-controls');
  25877. /**
  25878. * player is using the native device controls
  25879. *
  25880. * @event Player#usingnativecontrols
  25881. * @type {Event}
  25882. */
  25883. this.trigger('usingnativecontrols');
  25884. } else {
  25885. this.removeClass('vjs-using-native-controls');
  25886. /**
  25887. * player is using the custom HTML controls
  25888. *
  25889. * @event Player#usingcustomcontrols
  25890. * @type {Event}
  25891. */
  25892. this.trigger('usingcustomcontrols');
  25893. }
  25894. }
  25895. /**
  25896. * Set or get the current MediaError
  25897. *
  25898. * @fires Player#error
  25899. *
  25900. * @param {MediaError|string|number} [err]
  25901. * A MediaError or a string/number to be turned
  25902. * into a MediaError
  25903. *
  25904. * @return {MediaError|null|undefined}
  25905. * - The current MediaError when getting (or null)
  25906. * - Nothing when setting
  25907. */
  25908. error(err) {
  25909. if (err === undefined) {
  25910. return this.error_ || null;
  25911. }
  25912. // allow hooks to modify error object
  25913. hooks('beforeerror').forEach(hookFunction => {
  25914. const newErr = hookFunction(this, err);
  25915. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  25916. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  25917. return;
  25918. }
  25919. err = newErr;
  25920. });
  25921. // Suppress the first error message for no compatible source until
  25922. // user interaction
  25923. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  25924. const triggerSuppressedError = function () {
  25925. this.error(err);
  25926. };
  25927. this.options_.suppressNotSupportedError = false;
  25928. this.any(['click', 'touchstart'], triggerSuppressedError);
  25929. this.one('loadstart', function () {
  25930. this.off(['click', 'touchstart'], triggerSuppressedError);
  25931. });
  25932. return;
  25933. }
  25934. // restoring to default
  25935. if (err === null) {
  25936. this.error_ = null;
  25937. this.removeClass('vjs-error');
  25938. if (this.errorDisplay) {
  25939. this.errorDisplay.close();
  25940. }
  25941. return;
  25942. }
  25943. this.error_ = new MediaError(err);
  25944. // add the vjs-error classname to the player
  25945. this.addClass('vjs-error');
  25946. // log the name of the error type and any message
  25947. // IE11 logs "[object object]" and required you to expand message to see error object
  25948. log.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  25949. /**
  25950. * @event Player#error
  25951. * @type {Event}
  25952. */
  25953. this.trigger('error');
  25954. // notify hooks of the per player error
  25955. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  25956. return;
  25957. }
  25958. /**
  25959. * Report user activity
  25960. *
  25961. * @param {Object} event
  25962. * Event object
  25963. */
  25964. reportUserActivity(event) {
  25965. this.userActivity_ = true;
  25966. }
  25967. /**
  25968. * Get/set if user is active
  25969. *
  25970. * @fires Player#useractive
  25971. * @fires Player#userinactive
  25972. *
  25973. * @param {boolean} [bool]
  25974. * - true if the user is active
  25975. * - false if the user is inactive
  25976. *
  25977. * @return {boolean|undefined}
  25978. * - The current value of userActive when getting
  25979. * - Nothing when setting
  25980. */
  25981. userActive(bool) {
  25982. if (bool === undefined) {
  25983. return this.userActive_;
  25984. }
  25985. bool = !!bool;
  25986. if (bool === this.userActive_) {
  25987. return;
  25988. }
  25989. this.userActive_ = bool;
  25990. if (this.userActive_) {
  25991. this.userActivity_ = true;
  25992. this.removeClass('vjs-user-inactive');
  25993. this.addClass('vjs-user-active');
  25994. /**
  25995. * @event Player#useractive
  25996. * @type {Event}
  25997. */
  25998. this.trigger('useractive');
  25999. return;
  26000. }
  26001. // Chrome/Safari/IE have bugs where when you change the cursor it can
  26002. // trigger a mousemove event. This causes an issue when you're hiding
  26003. // the cursor when the user is inactive, and a mousemove signals user
  26004. // activity. Making it impossible to go into inactive mode. Specifically
  26005. // this happens in fullscreen when we really need to hide the cursor.
  26006. //
  26007. // When this gets resolved in ALL browsers it can be removed
  26008. // https://code.google.com/p/chromium/issues/detail?id=103041
  26009. if (this.tech_) {
  26010. this.tech_.one('mousemove', function (e) {
  26011. e.stopPropagation();
  26012. e.preventDefault();
  26013. });
  26014. }
  26015. this.userActivity_ = false;
  26016. this.removeClass('vjs-user-active');
  26017. this.addClass('vjs-user-inactive');
  26018. /**
  26019. * @event Player#userinactive
  26020. * @type {Event}
  26021. */
  26022. this.trigger('userinactive');
  26023. }
  26024. /**
  26025. * Listen for user activity based on timeout value
  26026. *
  26027. * @private
  26028. */
  26029. listenForUserActivity_() {
  26030. let mouseInProgress;
  26031. let lastMoveX;
  26032. let lastMoveY;
  26033. const handleActivity = bind_(this, this.reportUserActivity);
  26034. const handleMouseMove = function (e) {
  26035. // #1068 - Prevent mousemove spamming
  26036. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  26037. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  26038. lastMoveX = e.screenX;
  26039. lastMoveY = e.screenY;
  26040. handleActivity();
  26041. }
  26042. };
  26043. const handleMouseDown = function () {
  26044. handleActivity();
  26045. // For as long as the they are touching the device or have their mouse down,
  26046. // we consider them active even if they're not moving their finger or mouse.
  26047. // So we want to continue to update that they are active
  26048. this.clearInterval(mouseInProgress);
  26049. // Setting userActivity=true now and setting the interval to the same time
  26050. // as the activityCheck interval (250) should ensure we never miss the
  26051. // next activityCheck
  26052. mouseInProgress = this.setInterval(handleActivity, 250);
  26053. };
  26054. const handleMouseUpAndMouseLeave = function (event) {
  26055. handleActivity();
  26056. // Stop the interval that maintains activity if the mouse/touch is down
  26057. this.clearInterval(mouseInProgress);
  26058. };
  26059. // Any mouse movement will be considered user activity
  26060. this.on('mousedown', handleMouseDown);
  26061. this.on('mousemove', handleMouseMove);
  26062. this.on('mouseup', handleMouseUpAndMouseLeave);
  26063. this.on('mouseleave', handleMouseUpAndMouseLeave);
  26064. const controlBar = this.getChild('controlBar');
  26065. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  26066. // controlBar would no longer be hidden by default timeout.
  26067. if (controlBar && !IS_IOS && !IS_ANDROID) {
  26068. controlBar.on('mouseenter', function (event) {
  26069. if (this.player().options_.inactivityTimeout !== 0) {
  26070. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  26071. }
  26072. this.player().options_.inactivityTimeout = 0;
  26073. });
  26074. controlBar.on('mouseleave', function (event) {
  26075. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  26076. });
  26077. }
  26078. // Listen for keyboard navigation
  26079. // Shouldn't need to use inProgress interval because of key repeat
  26080. this.on('keydown', handleActivity);
  26081. this.on('keyup', handleActivity);
  26082. // Run an interval every 250 milliseconds instead of stuffing everything into
  26083. // the mousemove/touchmove function itself, to prevent performance degradation.
  26084. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  26085. // then gets picked up by this loop
  26086. // http://ejohn.org/blog/learning-from-twitter/
  26087. let inactivityTimeout;
  26088. /** @this Player */
  26089. const activityCheck = function () {
  26090. // Check to see if mouse/touch activity has happened
  26091. if (!this.userActivity_) {
  26092. return;
  26093. }
  26094. // Reset the activity tracker
  26095. this.userActivity_ = false;
  26096. // If the user state was inactive, set the state to active
  26097. this.userActive(true);
  26098. // Clear any existing inactivity timeout to start the timer over
  26099. this.clearTimeout(inactivityTimeout);
  26100. const timeout = this.options_.inactivityTimeout;
  26101. if (timeout <= 0) {
  26102. return;
  26103. }
  26104. // In <timeout> milliseconds, if no more activity has occurred the
  26105. // user will be considered inactive
  26106. inactivityTimeout = this.setTimeout(function () {
  26107. // Protect against the case where the inactivityTimeout can trigger just
  26108. // before the next user activity is picked up by the activity check loop
  26109. // causing a flicker
  26110. if (!this.userActivity_) {
  26111. this.userActive(false);
  26112. }
  26113. }, timeout);
  26114. };
  26115. this.setInterval(activityCheck, 250);
  26116. }
  26117. /**
  26118. * Gets or sets the current playback rate. A playback rate of
  26119. * 1.0 represents normal speed and 0.5 would indicate half-speed
  26120. * playback, for instance.
  26121. *
  26122. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  26123. *
  26124. * @param {number} [rate]
  26125. * New playback rate to set.
  26126. *
  26127. * @return {number|undefined}
  26128. * - The current playback rate when getting or 1.0
  26129. * - Nothing when setting
  26130. */
  26131. playbackRate(rate) {
  26132. if (rate !== undefined) {
  26133. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  26134. // that is registered above
  26135. this.techCall_('setPlaybackRate', rate);
  26136. return;
  26137. }
  26138. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  26139. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  26140. }
  26141. return 1.0;
  26142. }
  26143. /**
  26144. * Gets or sets the current default playback rate. A default playback rate of
  26145. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  26146. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  26147. * not the current playbackRate.
  26148. *
  26149. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  26150. *
  26151. * @param {number} [rate]
  26152. * New default playback rate to set.
  26153. *
  26154. * @return {number|undefined}
  26155. * - The default playback rate when getting or 1.0
  26156. * - Nothing when setting
  26157. */
  26158. defaultPlaybackRate(rate) {
  26159. if (rate !== undefined) {
  26160. return this.techCall_('setDefaultPlaybackRate', rate);
  26161. }
  26162. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  26163. return this.techGet_('defaultPlaybackRate');
  26164. }
  26165. return 1.0;
  26166. }
  26167. /**
  26168. * Gets or sets the audio flag
  26169. *
  26170. * @param {boolean} [bool]
  26171. * - true signals that this is an audio player
  26172. * - false signals that this is not an audio player
  26173. *
  26174. * @return {boolean|undefined}
  26175. * - The current value of isAudio when getting
  26176. * - Nothing when setting
  26177. */
  26178. isAudio(bool) {
  26179. if (bool !== undefined) {
  26180. this.isAudio_ = !!bool;
  26181. return;
  26182. }
  26183. return !!this.isAudio_;
  26184. }
  26185. updatePlayerHeightOnAudioOnlyMode_() {
  26186. const controlBar = this.getChild('ControlBar');
  26187. if (!controlBar || this.audioOnlyCache_.controlBarHeight === controlBar.currentHeight()) {
  26188. return;
  26189. }
  26190. this.audioOnlyCache_.controlBarHeight = controlBar.currentHeight();
  26191. this.height(this.audioOnlyCache_.controlBarHeight);
  26192. }
  26193. enableAudioOnlyUI_() {
  26194. // Update styling immediately to show the control bar so we can get its height
  26195. this.addClass('vjs-audio-only-mode');
  26196. const playerChildren = this.children();
  26197. const controlBar = this.getChild('ControlBar');
  26198. const controlBarHeight = controlBar && controlBar.currentHeight();
  26199. // Hide all player components except the control bar. Control bar components
  26200. // needed only for video are hidden with CSS
  26201. playerChildren.forEach(child => {
  26202. if (child === controlBar) {
  26203. return;
  26204. }
  26205. if (child.el_ && !child.hasClass('vjs-hidden')) {
  26206. child.hide();
  26207. this.audioOnlyCache_.hiddenChildren.push(child);
  26208. }
  26209. });
  26210. this.audioOnlyCache_.playerHeight = this.currentHeight();
  26211. this.audioOnlyCache_.controlBarHeight = controlBarHeight;
  26212. this.on('playerresize', this.boundUpdatePlayerHeightOnAudioOnlyMode_);
  26213. // Set the player height the same as the control bar
  26214. this.height(controlBarHeight);
  26215. this.trigger('audioonlymodechange');
  26216. }
  26217. disableAudioOnlyUI_() {
  26218. this.removeClass('vjs-audio-only-mode');
  26219. this.off('playerresize', this.boundUpdatePlayerHeightOnAudioOnlyMode_);
  26220. // Show player components that were previously hidden
  26221. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  26222. // Reset player height
  26223. this.height(this.audioOnlyCache_.playerHeight);
  26224. this.trigger('audioonlymodechange');
  26225. }
  26226. /**
  26227. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  26228. *
  26229. * Setting this to `true` will hide all player components except the control bar,
  26230. * as well as control bar components needed only for video.
  26231. *
  26232. * @param {boolean} [value]
  26233. * The value to set audioOnlyMode to.
  26234. *
  26235. * @return {Promise|boolean}
  26236. * A Promise is returned when setting the state, and a boolean when getting
  26237. * the present state
  26238. */
  26239. audioOnlyMode(value) {
  26240. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  26241. return this.audioOnlyMode_;
  26242. }
  26243. this.audioOnlyMode_ = value;
  26244. // Enable Audio Only Mode
  26245. if (value) {
  26246. const exitPromises = [];
  26247. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  26248. if (this.isInPictureInPicture()) {
  26249. exitPromises.push(this.exitPictureInPicture());
  26250. }
  26251. if (this.isFullscreen()) {
  26252. exitPromises.push(this.exitFullscreen());
  26253. }
  26254. if (this.audioPosterMode()) {
  26255. exitPromises.push(this.audioPosterMode(false));
  26256. }
  26257. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  26258. }
  26259. // Disable Audio Only Mode
  26260. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  26261. }
  26262. enablePosterModeUI_() {
  26263. // Hide the video element and show the poster image to enable posterModeUI
  26264. const tech = this.tech_ && this.tech_;
  26265. tech.hide();
  26266. this.addClass('vjs-audio-poster-mode');
  26267. this.trigger('audiopostermodechange');
  26268. }
  26269. disablePosterModeUI_() {
  26270. // Show the video element and hide the poster image to disable posterModeUI
  26271. const tech = this.tech_ && this.tech_;
  26272. tech.show();
  26273. this.removeClass('vjs-audio-poster-mode');
  26274. this.trigger('audiopostermodechange');
  26275. }
  26276. /**
  26277. * Get the current audioPosterMode state or set audioPosterMode to true or false
  26278. *
  26279. * @param {boolean} [value]
  26280. * The value to set audioPosterMode to.
  26281. *
  26282. * @return {Promise|boolean}
  26283. * A Promise is returned when setting the state, and a boolean when getting
  26284. * the present state
  26285. */
  26286. audioPosterMode(value) {
  26287. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  26288. return this.audioPosterMode_;
  26289. }
  26290. this.audioPosterMode_ = value;
  26291. if (value) {
  26292. if (this.audioOnlyMode()) {
  26293. const audioOnlyModePromise = this.audioOnlyMode(false);
  26294. return audioOnlyModePromise.then(() => {
  26295. // enable audio poster mode after audio only mode is disabled
  26296. this.enablePosterModeUI_();
  26297. });
  26298. }
  26299. return Promise.resolve().then(() => {
  26300. // enable audio poster mode
  26301. this.enablePosterModeUI_();
  26302. });
  26303. }
  26304. return Promise.resolve().then(() => {
  26305. // disable audio poster mode
  26306. this.disablePosterModeUI_();
  26307. });
  26308. }
  26309. /**
  26310. * A helper method for adding a {@link TextTrack} to our
  26311. * {@link TextTrackList}.
  26312. *
  26313. * In addition to the W3C settings we allow adding additional info through options.
  26314. *
  26315. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  26316. *
  26317. * @param {string} [kind]
  26318. * the kind of TextTrack you are adding
  26319. *
  26320. * @param {string} [label]
  26321. * the label to give the TextTrack label
  26322. *
  26323. * @param {string} [language]
  26324. * the language to set on the TextTrack
  26325. *
  26326. * @return {TextTrack|undefined}
  26327. * the TextTrack that was added or undefined
  26328. * if there is no tech
  26329. */
  26330. addTextTrack(kind, label, language) {
  26331. if (this.tech_) {
  26332. return this.tech_.addTextTrack(kind, label, language);
  26333. }
  26334. }
  26335. /**
  26336. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  26337. *
  26338. * @param {Object} options
  26339. * Options to pass to {@link HTMLTrackElement} during creation. See
  26340. * {@link HTMLTrackElement} for object properties that you should use.
  26341. *
  26342. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  26343. * from the TextTrackList and HtmlTrackElementList
  26344. * after a source change
  26345. *
  26346. * @return {HtmlTrackElement}
  26347. * the HTMLTrackElement that was created and added
  26348. * to the HtmlTrackElementList and the remote
  26349. * TextTrackList
  26350. *
  26351. */
  26352. addRemoteTextTrack(options, manualCleanup) {
  26353. if (this.tech_) {
  26354. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  26355. }
  26356. }
  26357. /**
  26358. * Remove a remote {@link TextTrack} from the respective
  26359. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  26360. *
  26361. * @param {Object} track
  26362. * Remote {@link TextTrack} to remove
  26363. *
  26364. * @return {undefined}
  26365. * does not return anything
  26366. */
  26367. removeRemoteTextTrack(obj = {}) {
  26368. let {
  26369. track
  26370. } = obj;
  26371. if (!track) {
  26372. track = obj;
  26373. }
  26374. // destructure the input into an object with a track argument, defaulting to arguments[0]
  26375. // default the whole argument to an empty object if nothing was passed in
  26376. if (this.tech_) {
  26377. return this.tech_.removeRemoteTextTrack(track);
  26378. }
  26379. }
  26380. /**
  26381. * Gets available media playback quality metrics as specified by the W3C's Media
  26382. * Playback Quality API.
  26383. *
  26384. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  26385. *
  26386. * @return {Object|undefined}
  26387. * An object with supported media playback quality metrics or undefined if there
  26388. * is no tech or the tech does not support it.
  26389. */
  26390. getVideoPlaybackQuality() {
  26391. return this.techGet_('getVideoPlaybackQuality');
  26392. }
  26393. /**
  26394. * Get video width
  26395. *
  26396. * @return {number}
  26397. * current video width
  26398. */
  26399. videoWidth() {
  26400. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  26401. }
  26402. /**
  26403. * Get video height
  26404. *
  26405. * @return {number}
  26406. * current video height
  26407. */
  26408. videoHeight() {
  26409. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  26410. }
  26411. /**
  26412. * Set or get the player's language code.
  26413. *
  26414. * Changing the language will trigger
  26415. * [languagechange]{@link Player#event:languagechange}
  26416. * which Components can use to update control text.
  26417. * ClickableComponent will update its control text by default on
  26418. * [languagechange]{@link Player#event:languagechange}.
  26419. *
  26420. * @fires Player#languagechange
  26421. *
  26422. * @param {string} [code]
  26423. * the language code to set the player to
  26424. *
  26425. * @return {string|undefined}
  26426. * - The current language code when getting
  26427. * - Nothing when setting
  26428. */
  26429. language(code) {
  26430. if (code === undefined) {
  26431. return this.language_;
  26432. }
  26433. if (this.language_ !== String(code).toLowerCase()) {
  26434. this.language_ = String(code).toLowerCase();
  26435. // during first init, it's possible some things won't be evented
  26436. if (isEvented(this)) {
  26437. /**
  26438. * fires when the player language change
  26439. *
  26440. * @event Player#languagechange
  26441. * @type {Event}
  26442. */
  26443. this.trigger('languagechange');
  26444. }
  26445. }
  26446. }
  26447. /**
  26448. * Get the player's language dictionary
  26449. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  26450. * Languages specified directly in the player options have precedence
  26451. *
  26452. * @return {Array}
  26453. * An array of of supported languages
  26454. */
  26455. languages() {
  26456. return merge(Player.prototype.options_.languages, this.languages_);
  26457. }
  26458. /**
  26459. * returns a JavaScript object representing the current track
  26460. * information. **DOES not return it as JSON**
  26461. *
  26462. * @return {Object}
  26463. * Object representing the current of track info
  26464. */
  26465. toJSON() {
  26466. const options = merge(this.options_);
  26467. const tracks = options.tracks;
  26468. options.tracks = [];
  26469. for (let i = 0; i < tracks.length; i++) {
  26470. let track = tracks[i];
  26471. // deep merge tracks and null out player so no circular references
  26472. track = merge(track);
  26473. track.player = undefined;
  26474. options.tracks[i] = track;
  26475. }
  26476. return options;
  26477. }
  26478. /**
  26479. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  26480. * component) that immediately overlays the player with arbitrary
  26481. * content and removes itself when closed.
  26482. *
  26483. * @param {string|Function|Element|Array|null} content
  26484. * Same as {@link ModalDialog#content}'s param of the same name.
  26485. * The most straight-forward usage is to provide a string or DOM
  26486. * element.
  26487. *
  26488. * @param {Object} [options]
  26489. * Extra options which will be passed on to the {@link ModalDialog}.
  26490. *
  26491. * @return {ModalDialog}
  26492. * the {@link ModalDialog} that was created
  26493. */
  26494. createModal(content, options) {
  26495. options = options || {};
  26496. options.content = content || '';
  26497. const modal = new ModalDialog(this, options);
  26498. this.addChild(modal);
  26499. modal.on('dispose', () => {
  26500. this.removeChild(modal);
  26501. });
  26502. modal.open();
  26503. return modal;
  26504. }
  26505. /**
  26506. * Change breakpoint classes when the player resizes.
  26507. *
  26508. * @private
  26509. */
  26510. updateCurrentBreakpoint_() {
  26511. if (!this.responsive()) {
  26512. return;
  26513. }
  26514. const currentBreakpoint = this.currentBreakpoint();
  26515. const currentWidth = this.currentWidth();
  26516. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  26517. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  26518. const maxWidth = this.breakpoints_[candidateBreakpoint];
  26519. if (currentWidth <= maxWidth) {
  26520. // The current breakpoint did not change, nothing to do.
  26521. if (currentBreakpoint === candidateBreakpoint) {
  26522. return;
  26523. }
  26524. // Only remove a class if there is a current breakpoint.
  26525. if (currentBreakpoint) {
  26526. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  26527. }
  26528. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  26529. this.breakpoint_ = candidateBreakpoint;
  26530. break;
  26531. }
  26532. }
  26533. }
  26534. /**
  26535. * Removes the current breakpoint.
  26536. *
  26537. * @private
  26538. */
  26539. removeCurrentBreakpoint_() {
  26540. const className = this.currentBreakpointClass();
  26541. this.breakpoint_ = '';
  26542. if (className) {
  26543. this.removeClass(className);
  26544. }
  26545. }
  26546. /**
  26547. * Get or set breakpoints on the player.
  26548. *
  26549. * Calling this method with an object or `true` will remove any previous
  26550. * custom breakpoints and start from the defaults again.
  26551. *
  26552. * @param {Object|boolean} [breakpoints]
  26553. * If an object is given, it can be used to provide custom
  26554. * breakpoints. If `true` is given, will set default breakpoints.
  26555. * If this argument is not given, will simply return the current
  26556. * breakpoints.
  26557. *
  26558. * @param {number} [breakpoints.tiny]
  26559. * The maximum width for the "vjs-layout-tiny" class.
  26560. *
  26561. * @param {number} [breakpoints.xsmall]
  26562. * The maximum width for the "vjs-layout-x-small" class.
  26563. *
  26564. * @param {number} [breakpoints.small]
  26565. * The maximum width for the "vjs-layout-small" class.
  26566. *
  26567. * @param {number} [breakpoints.medium]
  26568. * The maximum width for the "vjs-layout-medium" class.
  26569. *
  26570. * @param {number} [breakpoints.large]
  26571. * The maximum width for the "vjs-layout-large" class.
  26572. *
  26573. * @param {number} [breakpoints.xlarge]
  26574. * The maximum width for the "vjs-layout-x-large" class.
  26575. *
  26576. * @param {number} [breakpoints.huge]
  26577. * The maximum width for the "vjs-layout-huge" class.
  26578. *
  26579. * @return {Object}
  26580. * An object mapping breakpoint names to maximum width values.
  26581. */
  26582. breakpoints(breakpoints) {
  26583. // Used as a getter.
  26584. if (breakpoints === undefined) {
  26585. return Object.assign(this.breakpoints_);
  26586. }
  26587. this.breakpoint_ = '';
  26588. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  26589. // When breakpoint definitions change, we need to update the currently
  26590. // selected breakpoint.
  26591. this.updateCurrentBreakpoint_();
  26592. // Clone the breakpoints before returning.
  26593. return Object.assign(this.breakpoints_);
  26594. }
  26595. /**
  26596. * Get or set a flag indicating whether or not this player should adjust
  26597. * its UI based on its dimensions.
  26598. *
  26599. * @param {boolean} [value]
  26600. * Should be `true` if the player should adjust its UI based on its
  26601. * dimensions; otherwise, should be `false`.
  26602. *
  26603. * @return {boolean|undefined}
  26604. * Will be `true` if this player should adjust its UI based on its
  26605. * dimensions; otherwise, will be `false`.
  26606. * Nothing if setting
  26607. */
  26608. responsive(value) {
  26609. // Used as a getter.
  26610. if (value === undefined) {
  26611. return this.responsive_;
  26612. }
  26613. value = Boolean(value);
  26614. const current = this.responsive_;
  26615. // Nothing changed.
  26616. if (value === current) {
  26617. return;
  26618. }
  26619. // The value actually changed, set it.
  26620. this.responsive_ = value;
  26621. // Start listening for breakpoints and set the initial breakpoint if the
  26622. // player is now responsive.
  26623. if (value) {
  26624. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  26625. this.updateCurrentBreakpoint_();
  26626. // Stop listening for breakpoints if the player is no longer responsive.
  26627. } else {
  26628. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  26629. this.removeCurrentBreakpoint_();
  26630. }
  26631. return value;
  26632. }
  26633. /**
  26634. * Get current breakpoint name, if any.
  26635. *
  26636. * @return {string}
  26637. * If there is currently a breakpoint set, returns a the key from the
  26638. * breakpoints object matching it. Otherwise, returns an empty string.
  26639. */
  26640. currentBreakpoint() {
  26641. return this.breakpoint_;
  26642. }
  26643. /**
  26644. * Get the current breakpoint class name.
  26645. *
  26646. * @return {string}
  26647. * The matching class name (e.g. `"vjs-layout-tiny"` or
  26648. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  26649. * there is no current breakpoint.
  26650. */
  26651. currentBreakpointClass() {
  26652. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  26653. }
  26654. /**
  26655. * An object that describes a single piece of media.
  26656. *
  26657. * Properties that are not part of this type description will be retained; so,
  26658. * this can be viewed as a generic metadata storage mechanism as well.
  26659. *
  26660. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  26661. * @typedef {Object} Player~MediaObject
  26662. *
  26663. * @property {string} [album]
  26664. * Unused, except if this object is passed to the `MediaSession`
  26665. * API.
  26666. *
  26667. * @property {string} [artist]
  26668. * Unused, except if this object is passed to the `MediaSession`
  26669. * API.
  26670. *
  26671. * @property {Object[]} [artwork]
  26672. * Unused, except if this object is passed to the `MediaSession`
  26673. * API. If not specified, will be populated via the `poster`, if
  26674. * available.
  26675. *
  26676. * @property {string} [poster]
  26677. * URL to an image that will display before playback.
  26678. *
  26679. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  26680. * A single source object, an array of source objects, or a string
  26681. * referencing a URL to a media source. It is _highly recommended_
  26682. * that an object or array of objects is used here, so that source
  26683. * selection algorithms can take the `type` into account.
  26684. *
  26685. * @property {string} [title]
  26686. * Unused, except if this object is passed to the `MediaSession`
  26687. * API.
  26688. *
  26689. * @property {Object[]} [textTracks]
  26690. * An array of objects to be used to create text tracks, following
  26691. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  26692. * For ease of removal, these will be created as "remote" text
  26693. * tracks and set to automatically clean up on source changes.
  26694. *
  26695. * These objects may have properties like `src`, `kind`, `label`,
  26696. * and `language`, see {@link Tech#createRemoteTextTrack}.
  26697. */
  26698. /**
  26699. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  26700. *
  26701. * @param {Player~MediaObject} media
  26702. * A media object.
  26703. *
  26704. * @param {Function} ready
  26705. * A callback to be called when the player is ready.
  26706. */
  26707. loadMedia(media, ready) {
  26708. if (!media || typeof media !== 'object') {
  26709. return;
  26710. }
  26711. const crossOrigin = this.crossOrigin();
  26712. this.reset();
  26713. // Clone the media object so it cannot be mutated from outside.
  26714. this.cache_.media = merge(media);
  26715. const {
  26716. artist,
  26717. artwork,
  26718. description,
  26719. poster,
  26720. src,
  26721. textTracks,
  26722. title
  26723. } = this.cache_.media;
  26724. // If `artwork` is not given, create it using `poster`.
  26725. if (!artwork && poster) {
  26726. this.cache_.media.artwork = [{
  26727. src: poster,
  26728. type: getMimetype(poster)
  26729. }];
  26730. }
  26731. if (crossOrigin) {
  26732. this.crossOrigin(crossOrigin);
  26733. }
  26734. if (src) {
  26735. this.src(src);
  26736. }
  26737. if (poster) {
  26738. this.poster(poster);
  26739. }
  26740. if (Array.isArray(textTracks)) {
  26741. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  26742. }
  26743. if (this.titleBar) {
  26744. this.titleBar.update({
  26745. title,
  26746. description: description || artist || ''
  26747. });
  26748. }
  26749. this.ready(ready);
  26750. }
  26751. /**
  26752. * Get a clone of the current {@link Player~MediaObject} for this player.
  26753. *
  26754. * If the `loadMedia` method has not been used, will attempt to return a
  26755. * {@link Player~MediaObject} based on the current state of the player.
  26756. *
  26757. * @return {Player~MediaObject}
  26758. */
  26759. getMedia() {
  26760. if (!this.cache_.media) {
  26761. const poster = this.poster();
  26762. const src = this.currentSources();
  26763. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  26764. kind: tt.kind,
  26765. label: tt.label,
  26766. language: tt.language,
  26767. src: tt.src
  26768. }));
  26769. const media = {
  26770. src,
  26771. textTracks
  26772. };
  26773. if (poster) {
  26774. media.poster = poster;
  26775. media.artwork = [{
  26776. src: media.poster,
  26777. type: getMimetype(media.poster)
  26778. }];
  26779. }
  26780. return media;
  26781. }
  26782. return merge(this.cache_.media);
  26783. }
  26784. /**
  26785. * Gets tag settings
  26786. *
  26787. * @param {Element} tag
  26788. * The player tag
  26789. *
  26790. * @return {Object}
  26791. * An object containing all of the settings
  26792. * for a player tag
  26793. */
  26794. static getTagSettings(tag) {
  26795. const baseOptions = {
  26796. sources: [],
  26797. tracks: []
  26798. };
  26799. const tagOptions = getAttributes(tag);
  26800. const dataSetup = tagOptions['data-setup'];
  26801. if (hasClass(tag, 'vjs-fill')) {
  26802. tagOptions.fill = true;
  26803. }
  26804. if (hasClass(tag, 'vjs-fluid')) {
  26805. tagOptions.fluid = true;
  26806. }
  26807. // Check if data-setup attr exists.
  26808. if (dataSetup !== null) {
  26809. // Parse options JSON
  26810. try {
  26811. // If empty string, make it a parsable json object.
  26812. Object.assign(tagOptions, JSON.parse(dataSetup || '{}'));
  26813. } catch (e) {
  26814. log.error('data-setup', e);
  26815. }
  26816. }
  26817. Object.assign(baseOptions, tagOptions);
  26818. // Get tag children settings
  26819. if (tag.hasChildNodes()) {
  26820. const children = tag.childNodes;
  26821. for (let i = 0, j = children.length; i < j; i++) {
  26822. const child = children[i];
  26823. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  26824. const childName = child.nodeName.toLowerCase();
  26825. if (childName === 'source') {
  26826. baseOptions.sources.push(getAttributes(child));
  26827. } else if (childName === 'track') {
  26828. baseOptions.tracks.push(getAttributes(child));
  26829. }
  26830. }
  26831. }
  26832. return baseOptions;
  26833. }
  26834. /**
  26835. * Set debug mode to enable/disable logs at info level.
  26836. *
  26837. * @param {boolean} enabled
  26838. * @fires Player#debugon
  26839. * @fires Player#debugoff
  26840. * @return {boolean|undefined}
  26841. */
  26842. debug(enabled) {
  26843. if (enabled === undefined) {
  26844. return this.debugEnabled_;
  26845. }
  26846. if (enabled) {
  26847. this.trigger('debugon');
  26848. this.previousLogLevel_ = this.log.level;
  26849. this.log.level('debug');
  26850. this.debugEnabled_ = true;
  26851. } else {
  26852. this.trigger('debugoff');
  26853. this.log.level(this.previousLogLevel_);
  26854. this.previousLogLevel_ = undefined;
  26855. this.debugEnabled_ = false;
  26856. }
  26857. }
  26858. /**
  26859. * Set or get current playback rates.
  26860. * Takes an array and updates the playback rates menu with the new items.
  26861. * Pass in an empty array to hide the menu.
  26862. * Values other than arrays are ignored.
  26863. *
  26864. * @fires Player#playbackrateschange
  26865. * @param {number[]} [newRates]
  26866. * The new rates that the playback rates menu should update to.
  26867. * An empty array will hide the menu
  26868. * @return {number[]} When used as a getter will return the current playback rates
  26869. */
  26870. playbackRates(newRates) {
  26871. if (newRates === undefined) {
  26872. return this.cache_.playbackRates;
  26873. }
  26874. // ignore any value that isn't an array
  26875. if (!Array.isArray(newRates)) {
  26876. return;
  26877. }
  26878. // ignore any arrays that don't only contain numbers
  26879. if (!newRates.every(rate => typeof rate === 'number')) {
  26880. return;
  26881. }
  26882. this.cache_.playbackRates = newRates;
  26883. /**
  26884. * fires when the playback rates in a player are changed
  26885. *
  26886. * @event Player#playbackrateschange
  26887. * @type {Event}
  26888. */
  26889. this.trigger('playbackrateschange');
  26890. }
  26891. /**
  26892. * Reports whether or not a player has a plugin available.
  26893. *
  26894. * This does not report whether or not the plugin has ever been initialized
  26895. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  26896. *
  26897. * @method hasPlugin
  26898. * @param {string} name
  26899. * The name of a plugin.
  26900. *
  26901. * @return {boolean}
  26902. * Whether or not this player has the requested plugin available.
  26903. */
  26904. /**
  26905. * Reports whether or not a player is using a plugin by name.
  26906. *
  26907. * For basic plugins, this only reports whether the plugin has _ever_ been
  26908. * initialized on this player.
  26909. *
  26910. * @method Player#usingPlugin
  26911. * @param {string} name
  26912. * The name of a plugin.
  26913. *
  26914. * @return {boolean}
  26915. * Whether or not this player is using the requested plugin.
  26916. */
  26917. }
  26918. /**
  26919. * Get the {@link VideoTrackList}
  26920. *
  26921. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  26922. *
  26923. * @return {VideoTrackList}
  26924. * the current video track list
  26925. *
  26926. * @method Player.prototype.videoTracks
  26927. */
  26928. /**
  26929. * Get the {@link AudioTrackList}
  26930. *
  26931. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  26932. *
  26933. * @return {AudioTrackList}
  26934. * the current audio track list
  26935. *
  26936. * @method Player.prototype.audioTracks
  26937. */
  26938. /**
  26939. * Get the {@link TextTrackList}
  26940. *
  26941. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  26942. *
  26943. * @return {TextTrackList}
  26944. * the current text track list
  26945. *
  26946. * @method Player.prototype.textTracks
  26947. */
  26948. /**
  26949. * Get the remote {@link TextTrackList}
  26950. *
  26951. * @return {TextTrackList}
  26952. * The current remote text track list
  26953. *
  26954. * @method Player.prototype.remoteTextTracks
  26955. */
  26956. /**
  26957. * Get the remote {@link HtmlTrackElementList} tracks.
  26958. *
  26959. * @return {HtmlTrackElementList}
  26960. * The current remote text track element list
  26961. *
  26962. * @method Player.prototype.remoteTextTrackEls
  26963. */
  26964. ALL.names.forEach(function (name) {
  26965. const props = ALL[name];
  26966. Player.prototype[props.getterName] = function () {
  26967. if (this.tech_) {
  26968. return this.tech_[props.getterName]();
  26969. }
  26970. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  26971. // these will be passed to the tech during loading
  26972. this[props.privateName] = this[props.privateName] || new props.ListClass();
  26973. return this[props.privateName];
  26974. };
  26975. });
  26976. /**
  26977. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  26978. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  26979. * behavior.
  26980. *
  26981. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  26982. *
  26983. * @param {string} [value]
  26984. * The value to set the `Player`'s crossorigin to. If an argument is
  26985. * given, must be one of `anonymous` or `use-credentials`.
  26986. *
  26987. * @return {string|undefined}
  26988. * - The current crossorigin value of the `Player` when getting.
  26989. * - undefined when setting
  26990. */
  26991. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  26992. /**
  26993. * Global enumeration of players.
  26994. *
  26995. * The keys are the player IDs and the values are either the {@link Player}
  26996. * instance or `null` for disposed players.
  26997. *
  26998. * @type {Object}
  26999. */
  27000. Player.players = {};
  27001. const navigator = window.navigator;
  27002. /*
  27003. * Player instance options, surfaced using options
  27004. * options = Player.prototype.options_
  27005. * Make changes in options, not here.
  27006. *
  27007. * @type {Object}
  27008. * @private
  27009. */
  27010. Player.prototype.options_ = {
  27011. // Default order of fallback technology
  27012. techOrder: Tech.defaultTechOrder_,
  27013. html5: {},
  27014. // enable sourceset by default
  27015. enableSourceset: true,
  27016. // default inactivity timeout
  27017. inactivityTimeout: 2000,
  27018. // default playback rates
  27019. playbackRates: [],
  27020. // Add playback rate selection by adding rates
  27021. // 'playbackRates': [0.5, 1, 1.5, 2],
  27022. liveui: false,
  27023. // Included control sets
  27024. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  27025. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  27026. // locales and their language translations
  27027. languages: {},
  27028. // Default message to show when a video cannot be played.
  27029. notSupportedMessage: 'No compatible source was found for this media.',
  27030. normalizeAutoplay: false,
  27031. fullscreen: {
  27032. options: {
  27033. navigationUI: 'hide'
  27034. }
  27035. },
  27036. breakpoints: {},
  27037. responsive: false,
  27038. audioOnlyMode: false,
  27039. audioPosterMode: false,
  27040. spatialNavigation: {
  27041. enabled: false,
  27042. horizontalSeek: false
  27043. },
  27044. // Default smooth seeking to false
  27045. enableSmoothSeeking: false,
  27046. disableSeekWhileScrubbingOnMobile: false
  27047. };
  27048. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  27049. Player.prototype[`handleTech${toTitleCase(event)}_`] = function () {
  27050. return this.trigger(event);
  27051. };
  27052. });
  27053. /**
  27054. * Fired when the player has initial duration and dimension information
  27055. *
  27056. * @event Player#loadedmetadata
  27057. * @type {Event}
  27058. */
  27059. /**
  27060. * Fired when the player has downloaded data at the current playback position
  27061. *
  27062. * @event Player#loadeddata
  27063. * @type {Event}
  27064. */
  27065. /**
  27066. * Fired when the current playback position has changed *
  27067. * During playback this is fired every 15-250 milliseconds, depending on the
  27068. * playback technology in use.
  27069. *
  27070. * @event Player#timeupdate
  27071. * @type {Event}
  27072. */
  27073. /**
  27074. * Fired when the volume changes
  27075. *
  27076. * @event Player#volumechange
  27077. * @type {Event}
  27078. */
  27079. Component.registerComponent('Player', Player);
  27080. /**
  27081. * @file plugin.js
  27082. */
  27083. /**
  27084. * The base plugin name.
  27085. *
  27086. * @private
  27087. * @constant
  27088. * @type {string}
  27089. */
  27090. const BASE_PLUGIN_NAME = 'plugin';
  27091. /**
  27092. * The key on which a player's active plugins cache is stored.
  27093. *
  27094. * @private
  27095. * @constant
  27096. * @type {string}
  27097. */
  27098. const PLUGIN_CACHE_KEY = 'activePlugins_';
  27099. /**
  27100. * Stores registered plugins in a private space.
  27101. *
  27102. * @private
  27103. * @type {Object}
  27104. */
  27105. const pluginStorage = {};
  27106. /**
  27107. * Reports whether or not a plugin has been registered.
  27108. *
  27109. * @private
  27110. * @param {string} name
  27111. * The name of a plugin.
  27112. *
  27113. * @return {boolean}
  27114. * Whether or not the plugin has been registered.
  27115. */
  27116. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  27117. /**
  27118. * Get a single registered plugin by name.
  27119. *
  27120. * @private
  27121. * @param {string} name
  27122. * The name of a plugin.
  27123. *
  27124. * @return {typeof Plugin|Function|undefined}
  27125. * The plugin (or undefined).
  27126. */
  27127. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  27128. /**
  27129. * Marks a plugin as "active" on a player.
  27130. *
  27131. * Also, ensures that the player has an object for tracking active plugins.
  27132. *
  27133. * @private
  27134. * @param {Player} player
  27135. * A Video.js player instance.
  27136. *
  27137. * @param {string} name
  27138. * The name of a plugin.
  27139. */
  27140. const markPluginAsActive = (player, name) => {
  27141. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  27142. player[PLUGIN_CACHE_KEY][name] = true;
  27143. };
  27144. /**
  27145. * Triggers a pair of plugin setup events.
  27146. *
  27147. * @private
  27148. * @param {Player} player
  27149. * A Video.js player instance.
  27150. *
  27151. * @param {PluginEventHash} hash
  27152. * A plugin event hash.
  27153. *
  27154. * @param {boolean} [before]
  27155. * If true, prefixes the event name with "before". In other words,
  27156. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  27157. */
  27158. const triggerSetupEvent = (player, hash, before) => {
  27159. const eventName = (before ? 'before' : '') + 'pluginsetup';
  27160. player.trigger(eventName, hash);
  27161. player.trigger(eventName + ':' + hash.name, hash);
  27162. };
  27163. /**
  27164. * Takes a basic plugin function and returns a wrapper function which marks
  27165. * on the player that the plugin has been activated.
  27166. *
  27167. * @private
  27168. * @param {string} name
  27169. * The name of the plugin.
  27170. *
  27171. * @param {Function} plugin
  27172. * The basic plugin.
  27173. *
  27174. * @return {Function}
  27175. * A wrapper function for the given plugin.
  27176. */
  27177. const createBasicPlugin = function (name, plugin) {
  27178. const basicPluginWrapper = function () {
  27179. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  27180. // regardless, but we want the hash to be consistent with the hash provided
  27181. // for advanced plugins.
  27182. //
  27183. // The only potentially counter-intuitive thing here is the `instance` in
  27184. // the "pluginsetup" event is the value returned by the `plugin` function.
  27185. triggerSetupEvent(this, {
  27186. name,
  27187. plugin,
  27188. instance: null
  27189. }, true);
  27190. const instance = plugin.apply(this, arguments);
  27191. markPluginAsActive(this, name);
  27192. triggerSetupEvent(this, {
  27193. name,
  27194. plugin,
  27195. instance
  27196. });
  27197. return instance;
  27198. };
  27199. Object.keys(plugin).forEach(function (prop) {
  27200. basicPluginWrapper[prop] = plugin[prop];
  27201. });
  27202. return basicPluginWrapper;
  27203. };
  27204. /**
  27205. * Takes a plugin sub-class and returns a factory function for generating
  27206. * instances of it.
  27207. *
  27208. * This factory function will replace itself with an instance of the requested
  27209. * sub-class of Plugin.
  27210. *
  27211. * @private
  27212. * @param {string} name
  27213. * The name of the plugin.
  27214. *
  27215. * @param {Plugin} PluginSubClass
  27216. * The advanced plugin.
  27217. *
  27218. * @return {Function}
  27219. */
  27220. const createPluginFactory = (name, PluginSubClass) => {
  27221. // Add a `name` property to the plugin prototype so that each plugin can
  27222. // refer to itself by name.
  27223. PluginSubClass.prototype.name = name;
  27224. return function (...args) {
  27225. triggerSetupEvent(this, {
  27226. name,
  27227. plugin: PluginSubClass,
  27228. instance: null
  27229. }, true);
  27230. const instance = new PluginSubClass(...[this, ...args]);
  27231. // The plugin is replaced by a function that returns the current instance.
  27232. this[name] = () => instance;
  27233. triggerSetupEvent(this, instance.getEventHash());
  27234. return instance;
  27235. };
  27236. };
  27237. /**
  27238. * Parent class for all advanced plugins.
  27239. *
  27240. * @mixes module:evented~EventedMixin
  27241. * @mixes module:stateful~StatefulMixin
  27242. * @fires Player#beforepluginsetup
  27243. * @fires Player#beforepluginsetup:$name
  27244. * @fires Player#pluginsetup
  27245. * @fires Player#pluginsetup:$name
  27246. * @listens Player#dispose
  27247. * @throws {Error}
  27248. * If attempting to instantiate the base {@link Plugin} class
  27249. * directly instead of via a sub-class.
  27250. */
  27251. class Plugin {
  27252. /**
  27253. * Creates an instance of this class.
  27254. *
  27255. * Sub-classes should call `super` to ensure plugins are properly initialized.
  27256. *
  27257. * @param {Player} player
  27258. * A Video.js player instance.
  27259. */
  27260. constructor(player) {
  27261. if (this.constructor === Plugin) {
  27262. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  27263. }
  27264. this.player = player;
  27265. if (!this.log) {
  27266. this.log = this.player.log.createLogger(this.name);
  27267. }
  27268. // Make this object evented, but remove the added `trigger` method so we
  27269. // use the prototype version instead.
  27270. evented(this);
  27271. delete this.trigger;
  27272. stateful(this, this.constructor.defaultState);
  27273. markPluginAsActive(player, this.name);
  27274. // Auto-bind the dispose method so we can use it as a listener and unbind
  27275. // it later easily.
  27276. this.dispose = this.dispose.bind(this);
  27277. // If the player is disposed, dispose the plugin.
  27278. player.on('dispose', this.dispose);
  27279. }
  27280. /**
  27281. * Get the version of the plugin that was set on <pluginName>.VERSION
  27282. */
  27283. version() {
  27284. return this.constructor.VERSION;
  27285. }
  27286. /**
  27287. * Each event triggered by plugins includes a hash of additional data with
  27288. * conventional properties.
  27289. *
  27290. * This returns that object or mutates an existing hash.
  27291. *
  27292. * @param {Object} [hash={}]
  27293. * An object to be used as event an event hash.
  27294. *
  27295. * @return {PluginEventHash}
  27296. * An event hash object with provided properties mixed-in.
  27297. */
  27298. getEventHash(hash = {}) {
  27299. hash.name = this.name;
  27300. hash.plugin = this.constructor;
  27301. hash.instance = this;
  27302. return hash;
  27303. }
  27304. /**
  27305. * Triggers an event on the plugin object and overrides
  27306. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  27307. *
  27308. * @param {string|Object} event
  27309. * An event type or an object with a type property.
  27310. *
  27311. * @param {Object} [hash={}]
  27312. * Additional data hash to merge with a
  27313. * {@link PluginEventHash|PluginEventHash}.
  27314. *
  27315. * @return {boolean}
  27316. * Whether or not default was prevented.
  27317. */
  27318. trigger(event, hash = {}) {
  27319. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  27320. }
  27321. /**
  27322. * Handles "statechanged" events on the plugin. No-op by default, override by
  27323. * subclassing.
  27324. *
  27325. * @abstract
  27326. * @param {Event} e
  27327. * An event object provided by a "statechanged" event.
  27328. *
  27329. * @param {Object} e.changes
  27330. * An object describing changes that occurred with the "statechanged"
  27331. * event.
  27332. */
  27333. handleStateChanged(e) {}
  27334. /**
  27335. * Disposes a plugin.
  27336. *
  27337. * Subclasses can override this if they want, but for the sake of safety,
  27338. * it's probably best to subscribe the "dispose" event.
  27339. *
  27340. * @fires Plugin#dispose
  27341. */
  27342. dispose() {
  27343. const {
  27344. name,
  27345. player
  27346. } = this;
  27347. /**
  27348. * Signals that a advanced plugin is about to be disposed.
  27349. *
  27350. * @event Plugin#dispose
  27351. * @type {Event}
  27352. */
  27353. this.trigger('dispose');
  27354. this.off();
  27355. player.off('dispose', this.dispose);
  27356. // Eliminate any possible sources of leaking memory by clearing up
  27357. // references between the player and the plugin instance and nulling out
  27358. // the plugin's state and replacing methods with a function that throws.
  27359. player[PLUGIN_CACHE_KEY][name] = false;
  27360. this.player = this.state = null;
  27361. // Finally, replace the plugin name on the player with a new factory
  27362. // function, so that the plugin is ready to be set up again.
  27363. player[name] = createPluginFactory(name, pluginStorage[name]);
  27364. }
  27365. /**
  27366. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  27367. *
  27368. * @param {string|Function} plugin
  27369. * If a string, matches the name of a plugin. If a function, will be
  27370. * tested directly.
  27371. *
  27372. * @return {boolean}
  27373. * Whether or not a plugin is a basic plugin.
  27374. */
  27375. static isBasic(plugin) {
  27376. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  27377. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  27378. }
  27379. /**
  27380. * Register a Video.js plugin.
  27381. *
  27382. * @param {string} name
  27383. * The name of the plugin to be registered. Must be a string and
  27384. * must not match an existing plugin or a method on the `Player`
  27385. * prototype.
  27386. *
  27387. * @param {typeof Plugin|Function} plugin
  27388. * A sub-class of `Plugin` or a function for basic plugins.
  27389. *
  27390. * @return {typeof Plugin|Function}
  27391. * For advanced plugins, a factory function for that plugin. For
  27392. * basic plugins, a wrapper function that initializes the plugin.
  27393. */
  27394. static registerPlugin(name, plugin) {
  27395. if (typeof name !== 'string') {
  27396. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  27397. }
  27398. if (pluginExists(name)) {
  27399. log.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  27400. } else if (Player.prototype.hasOwnProperty(name)) {
  27401. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  27402. }
  27403. if (typeof plugin !== 'function') {
  27404. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  27405. }
  27406. pluginStorage[name] = plugin;
  27407. // Add a player prototype method for all sub-classed plugins (but not for
  27408. // the base Plugin class).
  27409. if (name !== BASE_PLUGIN_NAME) {
  27410. if (Plugin.isBasic(plugin)) {
  27411. Player.prototype[name] = createBasicPlugin(name, plugin);
  27412. } else {
  27413. Player.prototype[name] = createPluginFactory(name, plugin);
  27414. }
  27415. }
  27416. return plugin;
  27417. }
  27418. /**
  27419. * De-register a Video.js plugin.
  27420. *
  27421. * @param {string} name
  27422. * The name of the plugin to be de-registered. Must be a string that
  27423. * matches an existing plugin.
  27424. *
  27425. * @throws {Error}
  27426. * If an attempt is made to de-register the base plugin.
  27427. */
  27428. static deregisterPlugin(name) {
  27429. if (name === BASE_PLUGIN_NAME) {
  27430. throw new Error('Cannot de-register base plugin.');
  27431. }
  27432. if (pluginExists(name)) {
  27433. delete pluginStorage[name];
  27434. delete Player.prototype[name];
  27435. }
  27436. }
  27437. /**
  27438. * Gets an object containing multiple Video.js plugins.
  27439. *
  27440. * @param {Array} [names]
  27441. * If provided, should be an array of plugin names. Defaults to _all_
  27442. * plugin names.
  27443. *
  27444. * @return {Object|undefined}
  27445. * An object containing plugin(s) associated with their name(s) or
  27446. * `undefined` if no matching plugins exist).
  27447. */
  27448. static getPlugins(names = Object.keys(pluginStorage)) {
  27449. let result;
  27450. names.forEach(name => {
  27451. const plugin = getPlugin(name);
  27452. if (plugin) {
  27453. result = result || {};
  27454. result[name] = plugin;
  27455. }
  27456. });
  27457. return result;
  27458. }
  27459. /**
  27460. * Gets a plugin's version, if available
  27461. *
  27462. * @param {string} name
  27463. * The name of a plugin.
  27464. *
  27465. * @return {string}
  27466. * The plugin's version or an empty string.
  27467. */
  27468. static getPluginVersion(name) {
  27469. const plugin = getPlugin(name);
  27470. return plugin && plugin.VERSION || '';
  27471. }
  27472. }
  27473. /**
  27474. * Gets a plugin by name if it exists.
  27475. *
  27476. * @static
  27477. * @method getPlugin
  27478. * @memberOf Plugin
  27479. * @param {string} name
  27480. * The name of a plugin.
  27481. *
  27482. * @returns {typeof Plugin|Function|undefined}
  27483. * The plugin (or `undefined`).
  27484. */
  27485. Plugin.getPlugin = getPlugin;
  27486. /**
  27487. * The name of the base plugin class as it is registered.
  27488. *
  27489. * @type {string}
  27490. */
  27491. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  27492. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  27493. /**
  27494. * Documented in player.js
  27495. *
  27496. * @ignore
  27497. */
  27498. Player.prototype.usingPlugin = function (name) {
  27499. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  27500. };
  27501. /**
  27502. * Documented in player.js
  27503. *
  27504. * @ignore
  27505. */
  27506. Player.prototype.hasPlugin = function (name) {
  27507. return !!pluginExists(name);
  27508. };
  27509. /**
  27510. * Signals that a plugin is about to be set up on a player.
  27511. *
  27512. * @event Player#beforepluginsetup
  27513. * @type {PluginEventHash}
  27514. */
  27515. /**
  27516. * Signals that a plugin is about to be set up on a player - by name. The name
  27517. * is the name of the plugin.
  27518. *
  27519. * @event Player#beforepluginsetup:$name
  27520. * @type {PluginEventHash}
  27521. */
  27522. /**
  27523. * Signals that a plugin has just been set up on a player.
  27524. *
  27525. * @event Player#pluginsetup
  27526. * @type {PluginEventHash}
  27527. */
  27528. /**
  27529. * Signals that a plugin has just been set up on a player - by name. The name
  27530. * is the name of the plugin.
  27531. *
  27532. * @event Player#pluginsetup:$name
  27533. * @type {PluginEventHash}
  27534. */
  27535. /**
  27536. * @typedef {Object} PluginEventHash
  27537. *
  27538. * @property {string} instance
  27539. * For basic plugins, the return value of the plugin function. For
  27540. * advanced plugins, the plugin instance on which the event is fired.
  27541. *
  27542. * @property {string} name
  27543. * The name of the plugin.
  27544. *
  27545. * @property {string} plugin
  27546. * For basic plugins, the plugin function. For advanced plugins, the
  27547. * plugin class/constructor.
  27548. */
  27549. /**
  27550. * @file deprecate.js
  27551. * @module deprecate
  27552. */
  27553. /**
  27554. * Decorate a function with a deprecation message the first time it is called.
  27555. *
  27556. * @param {string} message
  27557. * A deprecation message to log the first time the returned function
  27558. * is called.
  27559. *
  27560. * @param {Function} fn
  27561. * The function to be deprecated.
  27562. *
  27563. * @return {Function}
  27564. * A wrapper function that will log a deprecation warning the first
  27565. * time it is called. The return value will be the return value of
  27566. * the wrapped function.
  27567. */
  27568. function deprecate(message, fn) {
  27569. let warned = false;
  27570. return function (...args) {
  27571. if (!warned) {
  27572. log.warn(message);
  27573. }
  27574. warned = true;
  27575. return fn.apply(this, args);
  27576. };
  27577. }
  27578. /**
  27579. * Internal function used to mark a function as deprecated in the next major
  27580. * version with consistent messaging.
  27581. *
  27582. * @param {number} major The major version where it will be removed
  27583. * @param {string} oldName The old function name
  27584. * @param {string} newName The new function name
  27585. * @param {Function} fn The function to deprecate
  27586. * @return {Function} The decorated function
  27587. */
  27588. function deprecateForMajor(major, oldName, newName, fn) {
  27589. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  27590. }
  27591. var VjsErrors = {
  27592. NetworkBadStatus: 'networkbadstatus',
  27593. NetworkRequestFailed: 'networkrequestfailed',
  27594. NetworkRequestAborted: 'networkrequestaborted',
  27595. NetworkRequestTimeout: 'networkrequesttimeout',
  27596. NetworkBodyParserFailed: 'networkbodyparserfailed',
  27597. StreamingHlsPlaylistParserError: 'streaminghlsplaylistparsererror',
  27598. StreamingDashManifestParserError: 'streamingdashmanifestparsererror',
  27599. StreamingContentSteeringParserError: 'streamingcontentsteeringparsererror',
  27600. StreamingVttParserError: 'streamingvttparsererror',
  27601. StreamingFailedToSelectNextSegment: 'streamingfailedtoselectnextsegment',
  27602. StreamingFailedToDecryptSegment: 'streamingfailedtodecryptsegment',
  27603. StreamingFailedToTransmuxSegment: 'streamingfailedtotransmuxsegment',
  27604. StreamingFailedToAppendSegment: 'streamingfailedtoappendsegment',
  27605. StreamingCodecsChangeError: 'streamingcodecschangeerror'
  27606. };
  27607. /**
  27608. * @file video.js
  27609. * @module videojs
  27610. */
  27611. /** @import { PlayerReadyCallback } from './player' */
  27612. /**
  27613. * Normalize an `id` value by trimming off a leading `#`
  27614. *
  27615. * @private
  27616. * @param {string} id
  27617. * A string, maybe with a leading `#`.
  27618. *
  27619. * @return {string}
  27620. * The string, without any leading `#`.
  27621. */
  27622. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  27623. /**
  27624. * The `videojs()` function doubles as the main function for users to create a
  27625. * {@link Player} instance as well as the main library namespace.
  27626. *
  27627. * It can also be used as a getter for a pre-existing {@link Player} instance.
  27628. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  27629. * purpose because it avoids any potential for unintended initialization.
  27630. *
  27631. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  27632. * of our JSDoc template, we cannot properly document this as both a function
  27633. * and a namespace, so its function signature is documented here.
  27634. *
  27635. * #### Arguments
  27636. * ##### id
  27637. * string|Element, **required**
  27638. *
  27639. * Video element or video element ID.
  27640. *
  27641. * ##### options
  27642. * Object, optional
  27643. *
  27644. * Options object for providing settings.
  27645. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  27646. *
  27647. * ##### ready
  27648. * {@link Component~ReadyCallback}, optional
  27649. *
  27650. * A function to be called when the {@link Player} and {@link Tech} are ready.
  27651. *
  27652. * #### Return Value
  27653. *
  27654. * The `videojs()` function returns a {@link Player} instance.
  27655. *
  27656. * @namespace
  27657. *
  27658. * @borrows AudioTrack as AudioTrack
  27659. * @borrows Component.getComponent as getComponent
  27660. * @borrows module:events.on as on
  27661. * @borrows module:events.one as one
  27662. * @borrows module:events.off as off
  27663. * @borrows module:events.trigger as trigger
  27664. * @borrows EventTarget as EventTarget
  27665. * @borrows module:middleware.use as use
  27666. * @borrows Player.players as players
  27667. * @borrows Plugin.registerPlugin as registerPlugin
  27668. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  27669. * @borrows Plugin.getPlugins as getPlugins
  27670. * @borrows Plugin.getPlugin as getPlugin
  27671. * @borrows Plugin.getPluginVersion as getPluginVersion
  27672. * @borrows Tech.getTech as getTech
  27673. * @borrows Tech.registerTech as registerTech
  27674. * @borrows TextTrack as TextTrack
  27675. * @borrows VideoTrack as VideoTrack
  27676. *
  27677. * @param {string|Element} id
  27678. * Video element or video element ID.
  27679. *
  27680. * @param {Object} [options]
  27681. * Options object for providing settings.
  27682. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  27683. *
  27684. * @param {PlayerReadyCallback} [ready]
  27685. * A function to be called when the {@link Player} and {@link Tech} are
  27686. * ready.
  27687. *
  27688. * @return {Player}
  27689. * The `videojs()` function returns a {@link Player|Player} instance.
  27690. */
  27691. function videojs(id, options, ready) {
  27692. let player = videojs.getPlayer(id);
  27693. if (player) {
  27694. if (options) {
  27695. log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  27696. }
  27697. if (ready) {
  27698. player.ready(ready);
  27699. }
  27700. return player;
  27701. }
  27702. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  27703. if (!isEl(el)) {
  27704. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  27705. }
  27706. // document.body.contains(el) will only check if el is contained within that one document.
  27707. // This causes problems for elements in iframes.
  27708. // Instead, use the element's ownerDocument instead of the global document.
  27709. // This will make sure that the element is indeed in the dom of that document.
  27710. // Additionally, check that the document in question has a default view.
  27711. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  27712. // If element is inside Shadow DOM (e.g. is part of a Custom element), ownerDocument.body
  27713. // always returns false. Instead, use the Shadow DOM root.
  27714. const inShadowDom = 'getRootNode' in el ? el.getRootNode() instanceof window.ShadowRoot : false;
  27715. const rootNode = inShadowDom ? el.getRootNode() : el.ownerDocument.body;
  27716. if (!el.ownerDocument.defaultView || !rootNode.contains(el)) {
  27717. log.warn('The element supplied is not included in the DOM');
  27718. }
  27719. options = options || {};
  27720. // Store a copy of the el before modification, if it is to be restored in destroy()
  27721. // If div ingest, store the parent div
  27722. if (options.restoreEl === true) {
  27723. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  27724. }
  27725. hooks('beforesetup').forEach(hookFunction => {
  27726. const opts = hookFunction(el, merge(options));
  27727. if (!isObject(opts) || Array.isArray(opts)) {
  27728. log.error('please return an object in beforesetup hooks');
  27729. return;
  27730. }
  27731. options = merge(options, opts);
  27732. });
  27733. // We get the current "Player" component here in case an integration has
  27734. // replaced it with a custom player.
  27735. const PlayerComponent = Component.getComponent('Player');
  27736. player = new PlayerComponent(el, options, ready);
  27737. hooks('setup').forEach(hookFunction => hookFunction(player));
  27738. return player;
  27739. }
  27740. videojs.hooks_ = hooks_;
  27741. videojs.hooks = hooks;
  27742. videojs.hook = hook;
  27743. videojs.hookOnce = hookOnce;
  27744. videojs.removeHook = removeHook;
  27745. // Add default styles
  27746. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  27747. let style = $('.vjs-styles-defaults');
  27748. if (!style) {
  27749. style = createStyleElement('vjs-styles-defaults');
  27750. const head = $('head');
  27751. if (head) {
  27752. head.insertBefore(style, head.firstChild);
  27753. }
  27754. setTextContent(style, `
  27755. .video-js {
  27756. width: 300px;
  27757. height: 150px;
  27758. }
  27759. .vjs-fluid:not(.vjs-audio-only-mode) {
  27760. padding-top: 56.25%
  27761. }
  27762. `);
  27763. }
  27764. }
  27765. // Run Auto-load players
  27766. // You have to wait at least once in case this script is loaded after your
  27767. // video in the DOM (weird behavior only with minified version)
  27768. autoSetupTimeout(1, videojs);
  27769. /**
  27770. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  27771. *
  27772. * @type {string}
  27773. */
  27774. videojs.VERSION = version;
  27775. /**
  27776. * The global options object. These are the settings that take effect
  27777. * if no overrides are specified when the player is created.
  27778. *
  27779. * @type {Object}
  27780. */
  27781. videojs.options = Player.prototype.options_;
  27782. /**
  27783. * Get an object with the currently created players, keyed by player ID
  27784. *
  27785. * @return {Object}
  27786. * The created players
  27787. */
  27788. videojs.getPlayers = () => Player.players;
  27789. /**
  27790. * Get a single player based on an ID or DOM element.
  27791. *
  27792. * This is useful if you want to check if an element or ID has an associated
  27793. * Video.js player, but not create one if it doesn't.
  27794. *
  27795. * @param {string|Element} id
  27796. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  27797. * or a string matching the `id` of such an element.
  27798. *
  27799. * @return {Player|undefined}
  27800. * A player instance or `undefined` if there is no player instance
  27801. * matching the argument.
  27802. */
  27803. videojs.getPlayer = id => {
  27804. const players = Player.players;
  27805. let tag;
  27806. if (typeof id === 'string') {
  27807. const nId = normalizeId(id);
  27808. const player = players[nId];
  27809. if (player) {
  27810. return player;
  27811. }
  27812. tag = $('#' + nId);
  27813. } else {
  27814. tag = id;
  27815. }
  27816. if (isEl(tag)) {
  27817. const {
  27818. player,
  27819. playerId
  27820. } = tag;
  27821. // Element may have a `player` property referring to an already created
  27822. // player instance. If so, return that.
  27823. if (player || players[playerId]) {
  27824. return player || players[playerId];
  27825. }
  27826. }
  27827. };
  27828. /**
  27829. * Returns an array of all current players.
  27830. *
  27831. * @return {Array}
  27832. * An array of all players. The array will be in the order that
  27833. * `Object.keys` provides, which could potentially vary between
  27834. * JavaScript engines.
  27835. *
  27836. */
  27837. videojs.getAllPlayers = () =>
  27838. // Disposed players leave a key with a `null` value, so we need to make sure
  27839. // we filter those out.
  27840. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  27841. videojs.players = Player.players;
  27842. videojs.getComponent = Component.getComponent;
  27843. /**
  27844. * Register a component so it can referred to by name. Used when adding to other
  27845. * components, either through addChild `component.addChild('myComponent')` or through
  27846. * default children options `{ children: ['myComponent'] }`.
  27847. *
  27848. * > NOTE: You could also just initialize the component before adding.
  27849. * `component.addChild(new MyComponent());`
  27850. *
  27851. * @param {string} name
  27852. * The class name of the component
  27853. *
  27854. * @param {typeof Component} comp
  27855. * The component class
  27856. *
  27857. * @return {typeof Component}
  27858. * The newly registered component
  27859. */
  27860. videojs.registerComponent = (name, comp) => {
  27861. if (Tech.isTech(comp)) {
  27862. log.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  27863. }
  27864. return Component.registerComponent.call(Component, name, comp);
  27865. };
  27866. videojs.getTech = Tech.getTech;
  27867. videojs.registerTech = Tech.registerTech;
  27868. videojs.use = use;
  27869. /**
  27870. * An object that can be returned by a middleware to signify
  27871. * that the middleware is being terminated.
  27872. *
  27873. * @type {object}
  27874. * @property {object} middleware.TERMINATOR
  27875. */
  27876. Object.defineProperty(videojs, 'middleware', {
  27877. value: {},
  27878. writeable: false,
  27879. enumerable: true
  27880. });
  27881. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  27882. value: TERMINATOR,
  27883. writeable: false,
  27884. enumerable: true
  27885. });
  27886. /**
  27887. * A reference to the {@link module:browser|browser utility module} as an object.
  27888. *
  27889. * @type {Object}
  27890. * @see {@link module:browser|browser}
  27891. */
  27892. videojs.browser = browser;
  27893. /**
  27894. * A reference to the {@link module:obj|obj utility module} as an object.
  27895. *
  27896. * @type {Object}
  27897. * @see {@link module:obj|obj}
  27898. */
  27899. videojs.obj = Obj;
  27900. /**
  27901. * Deprecated reference to the {@link module:obj.merge|merge function}
  27902. *
  27903. * @type {Function}
  27904. * @see {@link module:obj.merge|merge}
  27905. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  27906. */
  27907. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge);
  27908. /**
  27909. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  27910. *
  27911. * @type {Function}
  27912. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  27913. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  27914. */
  27915. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  27916. /**
  27917. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  27918. *
  27919. * @type {Function}
  27920. * @see {@link module:fn.bind_|fn.bind_}
  27921. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  27922. */
  27923. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  27924. videojs.registerPlugin = Plugin.registerPlugin;
  27925. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  27926. /**
  27927. * Deprecated method to register a plugin with Video.js
  27928. *
  27929. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  27930. *
  27931. * @param {string} name
  27932. * The plugin name
  27933. *
  27934. * @param {typeof Plugin|Function} plugin
  27935. * The plugin sub-class or function
  27936. *
  27937. * @return {typeof Plugin|Function}
  27938. */
  27939. videojs.plugin = (name, plugin) => {
  27940. log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  27941. return Plugin.registerPlugin(name, plugin);
  27942. };
  27943. videojs.getPlugins = Plugin.getPlugins;
  27944. videojs.getPlugin = Plugin.getPlugin;
  27945. videojs.getPluginVersion = Plugin.getPluginVersion;
  27946. /**
  27947. * Adding languages so that they're available to all players.
  27948. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  27949. *
  27950. * @param {string} code
  27951. * The language code or dictionary property
  27952. *
  27953. * @param {Object} data
  27954. * The data values to be translated
  27955. *
  27956. * @return {Object}
  27957. * The resulting language dictionary object
  27958. */
  27959. videojs.addLanguage = function (code, data) {
  27960. code = ('' + code).toLowerCase();
  27961. videojs.options.languages = merge(videojs.options.languages, {
  27962. [code]: data
  27963. });
  27964. return videojs.options.languages[code];
  27965. };
  27966. /**
  27967. * A reference to the {@link module:log|log utility module} as an object.
  27968. *
  27969. * @type {Function}
  27970. * @see {@link module:log|log}
  27971. */
  27972. videojs.log = log;
  27973. videojs.createLogger = createLogger;
  27974. /**
  27975. * A reference to the {@link module:time|time utility module} as an object.
  27976. *
  27977. * @type {Object}
  27978. * @see {@link module:time|time}
  27979. */
  27980. videojs.time = Time;
  27981. /**
  27982. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  27983. *
  27984. * @type {Function}
  27985. * @see {@link module:time.createTimeRanges|createTimeRanges}
  27986. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  27987. */
  27988. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges);
  27989. /**
  27990. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  27991. *
  27992. * @type {Function}
  27993. * @see {@link module:time.createTimeRanges|createTimeRanges}
  27994. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  27995. */
  27996. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges);
  27997. /**
  27998. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  27999. *
  28000. * @type {Function}
  28001. * @see {@link module:time.formatTime|formatTime}
  28002. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  28003. */
  28004. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  28005. /**
  28006. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  28007. *
  28008. * @type {Function}
  28009. * @see {@link module:time.setFormatTime|setFormatTime}
  28010. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  28011. */
  28012. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  28013. /**
  28014. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  28015. *
  28016. * @type {Function}
  28017. * @see {@link module:time.resetFormatTime|resetFormatTime}
  28018. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  28019. */
  28020. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  28021. /**
  28022. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  28023. *
  28024. * @type {Function}
  28025. * @see {@link module:url.parseUrl|parseUrl}
  28026. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  28027. */
  28028. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  28029. /**
  28030. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  28031. *
  28032. * @type {Function}
  28033. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  28034. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  28035. */
  28036. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  28037. videojs.EventTarget = EventTarget;
  28038. videojs.any = any;
  28039. videojs.on = on;
  28040. videojs.one = one;
  28041. videojs.off = off;
  28042. videojs.trigger = trigger;
  28043. /**
  28044. * A cross-browser XMLHttpRequest wrapper.
  28045. *
  28046. * @function
  28047. * @param {Object} options
  28048. * Settings for the request.
  28049. *
  28050. * @return {XMLHttpRequest|XDomainRequest}
  28051. * The request object.
  28052. *
  28053. * @see https://github.com/Raynos/xhr
  28054. */
  28055. videojs.xhr = lib;
  28056. videojs.TextTrack = TextTrack;
  28057. videojs.AudioTrack = AudioTrack;
  28058. videojs.VideoTrack = VideoTrack;
  28059. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  28060. videojs[k] = function () {
  28061. log.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  28062. return Dom[k].apply(null, arguments);
  28063. };
  28064. });
  28065. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  28066. /**
  28067. * A reference to the {@link module:dom|DOM utility module} as an object.
  28068. *
  28069. * @type {Object}
  28070. * @see {@link module:dom|dom}
  28071. */
  28072. videojs.dom = Dom;
  28073. /**
  28074. * A reference to the {@link module:fn|fn utility module} as an object.
  28075. *
  28076. * @type {Object}
  28077. * @see {@link module:fn|fn}
  28078. */
  28079. videojs.fn = Fn;
  28080. /**
  28081. * A reference to the {@link module:num|num utility module} as an object.
  28082. *
  28083. * @type {Object}
  28084. * @see {@link module:num|num}
  28085. */
  28086. videojs.num = Num;
  28087. /**
  28088. * A reference to the {@link module:str|str utility module} as an object.
  28089. *
  28090. * @type {Object}
  28091. * @see {@link module:str|str}
  28092. */
  28093. videojs.str = Str;
  28094. /**
  28095. * A reference to the {@link module:url|URL utility module} as an object.
  28096. *
  28097. * @type {Object}
  28098. * @see {@link module:url|url}
  28099. */
  28100. videojs.url = Url;
  28101. // The list of possible error types to occur in video.js
  28102. videojs.Error = VjsErrors;
  28103. return videojs;
  28104. }));