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.

28472 lines
898 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 vtt = {};
  8208. /**
  8209. * @file tech.js
  8210. */
  8211. /** @import { TimeRange } from '../utils/time' */
  8212. /**
  8213. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  8214. * that just contains the src url alone.
  8215. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  8216. * `var SourceString = 'http://example.com/some-video.mp4';`
  8217. *
  8218. * @typedef {Object|string} SourceObject
  8219. *
  8220. * @property {string} src
  8221. * The url to the source
  8222. *
  8223. * @property {string} type
  8224. * The mime type of the source
  8225. */
  8226. /**
  8227. * A function used by {@link Tech} to create a new {@link TextTrack}.
  8228. *
  8229. * @private
  8230. *
  8231. * @param {Tech} self
  8232. * An instance of the Tech class.
  8233. *
  8234. * @param {string} kind
  8235. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  8236. *
  8237. * @param {string} [label]
  8238. * Label to identify the text track
  8239. *
  8240. * @param {string} [language]
  8241. * Two letter language abbreviation
  8242. *
  8243. * @param {Object} [options={}]
  8244. * An object with additional text track options
  8245. *
  8246. * @return {TextTrack}
  8247. * The text track that was created.
  8248. */
  8249. function createTrackHelper(self, kind, label, language, options = {}) {
  8250. const tracks = self.textTracks();
  8251. options.kind = kind;
  8252. if (label) {
  8253. options.label = label;
  8254. }
  8255. if (language) {
  8256. options.language = language;
  8257. }
  8258. options.tech = self;
  8259. const track = new ALL.text.TrackClass(options);
  8260. tracks.addTrack(track);
  8261. return track;
  8262. }
  8263. /**
  8264. * This is the base class for media playback technology controllers, such as
  8265. * {@link HTML5}
  8266. *
  8267. * @extends Component
  8268. */
  8269. class Tech extends Component {
  8270. /**
  8271. * Create an instance of this Tech.
  8272. *
  8273. * @param {Object} [options]
  8274. * The key/value store of player options.
  8275. *
  8276. * @param {Function} [ready]
  8277. * Callback function to call when the `HTML5` Tech is ready.
  8278. */
  8279. constructor(options = {}, ready = function () {}) {
  8280. // we don't want the tech to report user activity automatically.
  8281. // This is done manually in addControlsListeners
  8282. options.reportTouchActivity = false;
  8283. super(null, options, ready);
  8284. this.onDurationChange_ = e => this.onDurationChange(e);
  8285. this.trackProgress_ = e => this.trackProgress(e);
  8286. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  8287. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  8288. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  8289. this.queuedHanders_ = new Set();
  8290. // keep track of whether the current source has played at all to
  8291. // implement a very limited played()
  8292. this.hasStarted_ = false;
  8293. this.on('playing', function () {
  8294. this.hasStarted_ = true;
  8295. });
  8296. this.on('loadstart', function () {
  8297. this.hasStarted_ = false;
  8298. });
  8299. ALL.names.forEach(name => {
  8300. const props = ALL[name];
  8301. if (options && options[props.getterName]) {
  8302. this[props.privateName] = options[props.getterName];
  8303. }
  8304. });
  8305. // Manually track progress in cases where the browser/tech doesn't report it.
  8306. if (!this.featuresProgressEvents) {
  8307. this.manualProgressOn();
  8308. }
  8309. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  8310. if (!this.featuresTimeupdateEvents) {
  8311. this.manualTimeUpdatesOn();
  8312. }
  8313. ['Text', 'Audio', 'Video'].forEach(track => {
  8314. if (options[`native${track}Tracks`] === false) {
  8315. this[`featuresNative${track}Tracks`] = false;
  8316. }
  8317. });
  8318. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  8319. this.featuresNativeTextTracks = false;
  8320. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  8321. this.featuresNativeTextTracks = true;
  8322. }
  8323. if (!this.featuresNativeTextTracks) {
  8324. this.emulateTextTracks();
  8325. }
  8326. this.preloadTextTracks = options.preloadTextTracks !== false;
  8327. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  8328. this.initTrackListeners();
  8329. // Turn on component tap events only if not using native controls
  8330. if (!options.nativeControlsForTouch) {
  8331. this.emitTapEvents();
  8332. }
  8333. if (this.constructor) {
  8334. this.name_ = this.constructor.name || 'Unknown Tech';
  8335. }
  8336. }
  8337. /**
  8338. * A special function to trigger source set in a way that will allow player
  8339. * to re-trigger if the player or tech are not ready yet.
  8340. *
  8341. * @fires Tech#sourceset
  8342. * @param {string} src The source string at the time of the source changing.
  8343. */
  8344. triggerSourceset(src) {
  8345. if (!this.isReady_) {
  8346. // on initial ready we have to trigger source set
  8347. // 1ms after ready so that player can watch for it.
  8348. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  8349. }
  8350. /**
  8351. * Fired when the source is set on the tech causing the media element
  8352. * to reload.
  8353. *
  8354. * @see {@link Player#event:sourceset}
  8355. * @event Tech#sourceset
  8356. * @type {Event}
  8357. */
  8358. this.trigger({
  8359. src,
  8360. type: 'sourceset'
  8361. });
  8362. }
  8363. /* Fallbacks for unsupported event types
  8364. ================================================================================ */
  8365. /**
  8366. * Polyfill the `progress` event for browsers that don't support it natively.
  8367. *
  8368. * @see {@link Tech#trackProgress}
  8369. */
  8370. manualProgressOn() {
  8371. this.on('durationchange', this.onDurationChange_);
  8372. this.manualProgress = true;
  8373. // Trigger progress watching when a source begins loading
  8374. this.one('ready', this.trackProgress_);
  8375. }
  8376. /**
  8377. * Turn off the polyfill for `progress` events that was created in
  8378. * {@link Tech#manualProgressOn}
  8379. */
  8380. manualProgressOff() {
  8381. this.manualProgress = false;
  8382. this.stopTrackingProgress();
  8383. this.off('durationchange', this.onDurationChange_);
  8384. }
  8385. /**
  8386. * This is used to trigger a `progress` event when the buffered percent changes. It
  8387. * sets an interval function that will be called every 500 milliseconds to check if the
  8388. * buffer end percent has changed.
  8389. *
  8390. * > This function is called by {@link Tech#manualProgressOn}
  8391. *
  8392. * @param {Event} event
  8393. * The `ready` event that caused this to run.
  8394. *
  8395. * @listens Tech#ready
  8396. * @fires Tech#progress
  8397. */
  8398. trackProgress(event) {
  8399. this.stopTrackingProgress();
  8400. this.progressInterval = this.setInterval(bind_(this, function () {
  8401. // Don't trigger unless buffered amount is greater than last time
  8402. const numBufferedPercent = this.bufferedPercent();
  8403. if (this.bufferedPercent_ !== numBufferedPercent) {
  8404. /**
  8405. * See {@link Player#progress}
  8406. *
  8407. * @event Tech#progress
  8408. * @type {Event}
  8409. */
  8410. this.trigger('progress');
  8411. }
  8412. this.bufferedPercent_ = numBufferedPercent;
  8413. if (numBufferedPercent === 1) {
  8414. this.stopTrackingProgress();
  8415. }
  8416. }), 500);
  8417. }
  8418. /**
  8419. * Update our internal duration on a `durationchange` event by calling
  8420. * {@link Tech#duration}.
  8421. *
  8422. * @param {Event} event
  8423. * The `durationchange` event that caused this to run.
  8424. *
  8425. * @listens Tech#durationchange
  8426. */
  8427. onDurationChange(event) {
  8428. this.duration_ = this.duration();
  8429. }
  8430. /**
  8431. * Get and create a `TimeRange` object for buffering.
  8432. *
  8433. * @return {TimeRange}
  8434. * The time range object that was created.
  8435. */
  8436. buffered() {
  8437. return createTimeRanges(0, 0);
  8438. }
  8439. /**
  8440. * Get the percentage of the current video that is currently buffered.
  8441. *
  8442. * @return {number}
  8443. * A number from 0 to 1 that represents the decimal percentage of the
  8444. * video that is buffered.
  8445. *
  8446. */
  8447. bufferedPercent() {
  8448. return bufferedPercent(this.buffered(), this.duration_);
  8449. }
  8450. /**
  8451. * Turn off the polyfill for `progress` events that was created in
  8452. * {@link Tech#manualProgressOn}
  8453. * Stop manually tracking progress events by clearing the interval that was set in
  8454. * {@link Tech#trackProgress}.
  8455. */
  8456. stopTrackingProgress() {
  8457. this.clearInterval(this.progressInterval);
  8458. }
  8459. /**
  8460. * Polyfill the `timeupdate` event for browsers that don't support it.
  8461. *
  8462. * @see {@link Tech#trackCurrentTime}
  8463. */
  8464. manualTimeUpdatesOn() {
  8465. this.manualTimeUpdates = true;
  8466. this.on('play', this.trackCurrentTime_);
  8467. this.on('pause', this.stopTrackingCurrentTime_);
  8468. }
  8469. /**
  8470. * Turn off the polyfill for `timeupdate` events that was created in
  8471. * {@link Tech#manualTimeUpdatesOn}
  8472. */
  8473. manualTimeUpdatesOff() {
  8474. this.manualTimeUpdates = false;
  8475. this.stopTrackingCurrentTime();
  8476. this.off('play', this.trackCurrentTime_);
  8477. this.off('pause', this.stopTrackingCurrentTime_);
  8478. }
  8479. /**
  8480. * Sets up an interval function to track current time and trigger `timeupdate` every
  8481. * 250 milliseconds.
  8482. *
  8483. * @listens Tech#play
  8484. * @triggers Tech#timeupdate
  8485. */
  8486. trackCurrentTime() {
  8487. if (this.currentTimeInterval) {
  8488. this.stopTrackingCurrentTime();
  8489. }
  8490. this.currentTimeInterval = this.setInterval(function () {
  8491. /**
  8492. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  8493. *
  8494. * @event Tech#timeupdate
  8495. * @type {Event}
  8496. */
  8497. this.trigger({
  8498. type: 'timeupdate',
  8499. target: this,
  8500. manuallyTriggered: true
  8501. });
  8502. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  8503. }, 250);
  8504. }
  8505. /**
  8506. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  8507. * `timeupdate` event is no longer triggered.
  8508. *
  8509. * @listens {Tech#pause}
  8510. */
  8511. stopTrackingCurrentTime() {
  8512. this.clearInterval(this.currentTimeInterval);
  8513. // #1002 - if the video ends right before the next timeupdate would happen,
  8514. // the progress bar won't make it all the way to the end
  8515. this.trigger({
  8516. type: 'timeupdate',
  8517. target: this,
  8518. manuallyTriggered: true
  8519. });
  8520. }
  8521. /**
  8522. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  8523. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  8524. *
  8525. * @fires Component#dispose
  8526. */
  8527. dispose() {
  8528. // clear out all tracks because we can't reuse them between techs
  8529. this.clearTracks(NORMAL.names);
  8530. // Turn off any manual progress or timeupdate tracking
  8531. if (this.manualProgress) {
  8532. this.manualProgressOff();
  8533. }
  8534. if (this.manualTimeUpdates) {
  8535. this.manualTimeUpdatesOff();
  8536. }
  8537. super.dispose();
  8538. }
  8539. /**
  8540. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  8541. *
  8542. * > Note: Techs without source handlers should call this between sources for `video`
  8543. * & `audio` tracks. You don't want to use them between tracks!
  8544. *
  8545. * @param {string[]|string} types
  8546. * TrackList names to clear, valid names are `video`, `audio`, and
  8547. * `text`.
  8548. */
  8549. clearTracks(types) {
  8550. types = [].concat(types);
  8551. // clear out all tracks because we can't reuse them between techs
  8552. types.forEach(type => {
  8553. const list = this[`${type}Tracks`]() || [];
  8554. let i = list.length;
  8555. while (i--) {
  8556. const track = list[i];
  8557. if (type === 'text') {
  8558. this.removeRemoteTextTrack(track);
  8559. }
  8560. list.removeTrack(track);
  8561. }
  8562. });
  8563. }
  8564. /**
  8565. * Remove any TextTracks added via addRemoteTextTrack that are
  8566. * flagged for automatic garbage collection
  8567. */
  8568. cleanupAutoTextTracks() {
  8569. const list = this.autoRemoteTextTracks_ || [];
  8570. let i = list.length;
  8571. while (i--) {
  8572. const track = list[i];
  8573. this.removeRemoteTextTrack(track);
  8574. }
  8575. }
  8576. /**
  8577. * Reset the tech, which will removes all sources and reset the internal readyState.
  8578. *
  8579. * @abstract
  8580. */
  8581. reset() {}
  8582. /**
  8583. * Get the value of `crossOrigin` from the tech.
  8584. *
  8585. * @abstract
  8586. *
  8587. * @see {Html5#crossOrigin}
  8588. */
  8589. crossOrigin() {}
  8590. /**
  8591. * Set the value of `crossOrigin` on the tech.
  8592. *
  8593. * @abstract
  8594. *
  8595. * @param {string} crossOrigin the crossOrigin value
  8596. * @see {Html5#setCrossOrigin}
  8597. */
  8598. setCrossOrigin() {}
  8599. /**
  8600. * Get or set an error on the Tech.
  8601. *
  8602. * @param {MediaError} [err]
  8603. * Error to set on the Tech
  8604. *
  8605. * @return {MediaError|null}
  8606. * The current error object on the tech, or null if there isn't one.
  8607. */
  8608. error(err) {
  8609. if (err !== undefined) {
  8610. this.error_ = new MediaError(err);
  8611. this.trigger('error');
  8612. }
  8613. return this.error_;
  8614. }
  8615. /**
  8616. * Returns the `TimeRange`s that have been played through for the current source.
  8617. *
  8618. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  8619. * It only checks whether the source has played at all or not.
  8620. *
  8621. * @return {TimeRange}
  8622. * - A single time range if this video has played
  8623. * - An empty set of ranges if not.
  8624. */
  8625. played() {
  8626. if (this.hasStarted_) {
  8627. return createTimeRanges(0, 0);
  8628. }
  8629. return createTimeRanges();
  8630. }
  8631. /**
  8632. * Start playback
  8633. *
  8634. * @abstract
  8635. *
  8636. * @see {Html5#play}
  8637. */
  8638. play() {}
  8639. /**
  8640. * Set whether we are scrubbing or not
  8641. *
  8642. * @abstract
  8643. * @param {boolean} _isScrubbing
  8644. * - true for we are currently scrubbing
  8645. * - false for we are no longer scrubbing
  8646. *
  8647. * @see {Html5#setScrubbing}
  8648. */
  8649. setScrubbing(_isScrubbing) {}
  8650. /**
  8651. * Get whether we are scrubbing or not
  8652. *
  8653. * @abstract
  8654. *
  8655. * @see {Html5#scrubbing}
  8656. */
  8657. scrubbing() {}
  8658. /**
  8659. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  8660. * previously called.
  8661. *
  8662. * @param {number} _seconds
  8663. * Set the current time of the media to this.
  8664. * @fires Tech#timeupdate
  8665. */
  8666. setCurrentTime(_seconds) {
  8667. // improve the accuracy of manual timeupdates
  8668. if (this.manualTimeUpdates) {
  8669. /**
  8670. * A manual `timeupdate` event.
  8671. *
  8672. * @event Tech#timeupdate
  8673. * @type {Event}
  8674. */
  8675. this.trigger({
  8676. type: 'timeupdate',
  8677. target: this,
  8678. manuallyTriggered: true
  8679. });
  8680. }
  8681. }
  8682. /**
  8683. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  8684. * {@link TextTrackList} events.
  8685. *
  8686. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  8687. *
  8688. * @fires Tech#audiotrackchange
  8689. * @fires Tech#videotrackchange
  8690. * @fires Tech#texttrackchange
  8691. */
  8692. initTrackListeners() {
  8693. /**
  8694. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  8695. *
  8696. * @event Tech#audiotrackchange
  8697. * @type {Event}
  8698. */
  8699. /**
  8700. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  8701. *
  8702. * @event Tech#videotrackchange
  8703. * @type {Event}
  8704. */
  8705. /**
  8706. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  8707. *
  8708. * @event Tech#texttrackchange
  8709. * @type {Event}
  8710. */
  8711. NORMAL.names.forEach(name => {
  8712. const props = NORMAL[name];
  8713. const trackListChanges = () => {
  8714. this.trigger(`${name}trackchange`);
  8715. };
  8716. const tracks = this[props.getterName]();
  8717. tracks.addEventListener('removetrack', trackListChanges);
  8718. tracks.addEventListener('addtrack', trackListChanges);
  8719. this.on('dispose', () => {
  8720. tracks.removeEventListener('removetrack', trackListChanges);
  8721. tracks.removeEventListener('addtrack', trackListChanges);
  8722. });
  8723. });
  8724. }
  8725. /**
  8726. * Emulate TextTracks using vtt.js if necessary
  8727. *
  8728. * @fires Tech#vttjsloaded
  8729. * @fires Tech#vttjserror
  8730. */
  8731. addWebVttScript_() {
  8732. if (window.WebVTT) {
  8733. return;
  8734. }
  8735. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  8736. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  8737. // before inserting the WebVTT script
  8738. if (document.body.contains(this.el())) {
  8739. // load via require if available and vtt.js script location was not passed in
  8740. // as an option. novtt builds will turn the above require call into an empty object
  8741. // which will cause this if check to always fail.
  8742. if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {
  8743. this.trigger('vttjsloaded');
  8744. return;
  8745. }
  8746. // load vtt.js via the script location option or the cdn of no location was
  8747. // passed in
  8748. const script = document.createElement('script');
  8749. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  8750. script.onload = () => {
  8751. /**
  8752. * Fired when vtt.js is loaded.
  8753. *
  8754. * @event Tech#vttjsloaded
  8755. * @type {Event}
  8756. */
  8757. this.trigger('vttjsloaded');
  8758. };
  8759. script.onerror = () => {
  8760. /**
  8761. * Fired when vtt.js was not loaded due to an error
  8762. *
  8763. * @event Tech#vttjsloaded
  8764. * @type {Event}
  8765. */
  8766. this.trigger('vttjserror');
  8767. };
  8768. this.on('dispose', () => {
  8769. script.onload = null;
  8770. script.onerror = null;
  8771. });
  8772. // but have not loaded yet and we set it to true before the inject so that
  8773. // we don't overwrite the injected window.WebVTT if it loads right away
  8774. window.WebVTT = true;
  8775. this.el().parentNode.appendChild(script);
  8776. } else {
  8777. this.ready(this.addWebVttScript_);
  8778. }
  8779. }
  8780. /**
  8781. * Emulate texttracks
  8782. *
  8783. */
  8784. emulateTextTracks() {
  8785. const tracks = this.textTracks();
  8786. const remoteTracks = this.remoteTextTracks();
  8787. const handleAddTrack = e => tracks.addTrack(e.track);
  8788. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  8789. remoteTracks.on('addtrack', handleAddTrack);
  8790. remoteTracks.on('removetrack', handleRemoveTrack);
  8791. this.addWebVttScript_();
  8792. const updateDisplay = () => this.trigger('texttrackchange');
  8793. const textTracksChanges = () => {
  8794. updateDisplay();
  8795. for (let i = 0; i < tracks.length; i++) {
  8796. const track = tracks[i];
  8797. track.removeEventListener('cuechange', updateDisplay);
  8798. if (track.mode === 'showing') {
  8799. track.addEventListener('cuechange', updateDisplay);
  8800. }
  8801. }
  8802. };
  8803. textTracksChanges();
  8804. tracks.addEventListener('change', textTracksChanges);
  8805. tracks.addEventListener('addtrack', textTracksChanges);
  8806. tracks.addEventListener('removetrack', textTracksChanges);
  8807. this.on('dispose', function () {
  8808. remoteTracks.off('addtrack', handleAddTrack);
  8809. remoteTracks.off('removetrack', handleRemoveTrack);
  8810. tracks.removeEventListener('change', textTracksChanges);
  8811. tracks.removeEventListener('addtrack', textTracksChanges);
  8812. tracks.removeEventListener('removetrack', textTracksChanges);
  8813. for (let i = 0; i < tracks.length; i++) {
  8814. const track = tracks[i];
  8815. track.removeEventListener('cuechange', updateDisplay);
  8816. }
  8817. });
  8818. }
  8819. /**
  8820. * Create and returns a remote {@link TextTrack} object.
  8821. *
  8822. * @param {string} kind
  8823. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  8824. *
  8825. * @param {string} [label]
  8826. * Label to identify the text track
  8827. *
  8828. * @param {string} [language]
  8829. * Two letter language abbreviation
  8830. *
  8831. * @return {TextTrack}
  8832. * The TextTrack that gets created.
  8833. */
  8834. addTextTrack(kind, label, language) {
  8835. if (!kind) {
  8836. throw new Error('TextTrack kind is required but was not provided');
  8837. }
  8838. return createTrackHelper(this, kind, label, language);
  8839. }
  8840. /**
  8841. * Create an emulated TextTrack for use by addRemoteTextTrack
  8842. *
  8843. * This is intended to be overridden by classes that inherit from
  8844. * Tech in order to create native or custom TextTracks.
  8845. *
  8846. * @param {Object} options
  8847. * The object should contain the options to initialize the TextTrack with.
  8848. *
  8849. * @param {string} [options.kind]
  8850. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  8851. *
  8852. * @param {string} [options.label].
  8853. * Label to identify the text track
  8854. *
  8855. * @param {string} [options.language]
  8856. * Two letter language abbreviation.
  8857. *
  8858. * @return {HTMLTrackElement}
  8859. * The track element that gets created.
  8860. */
  8861. createRemoteTextTrack(options) {
  8862. const track = merge(options, {
  8863. tech: this
  8864. });
  8865. return new REMOTE.remoteTextEl.TrackClass(track);
  8866. }
  8867. /**
  8868. * Creates a remote text track object and returns an html track element.
  8869. *
  8870. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  8871. *
  8872. * @param {Object} options
  8873. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  8874. *
  8875. * @param {boolean} [manualCleanup=false]
  8876. * - When false: the TextTrack will be automatically removed from the video
  8877. * element whenever the source changes
  8878. * - When True: The TextTrack will have to be cleaned up manually
  8879. *
  8880. * @return {HTMLTrackElement}
  8881. * An Html Track Element.
  8882. *
  8883. */
  8884. addRemoteTextTrack(options = {}, manualCleanup) {
  8885. const htmlTrackElement = this.createRemoteTextTrack(options);
  8886. if (typeof manualCleanup !== 'boolean') {
  8887. manualCleanup = false;
  8888. }
  8889. // store HTMLTrackElement and TextTrack to remote list
  8890. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  8891. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  8892. if (manualCleanup === false) {
  8893. // create the TextTrackList if it doesn't exist
  8894. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  8895. }
  8896. return htmlTrackElement;
  8897. }
  8898. /**
  8899. * Remove a remote text track from the remote `TextTrackList`.
  8900. *
  8901. * @param {TextTrack} track
  8902. * `TextTrack` to remove from the `TextTrackList`
  8903. */
  8904. removeRemoteTextTrack(track) {
  8905. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  8906. // remove HTMLTrackElement and TextTrack from remote list
  8907. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  8908. this.remoteTextTracks().removeTrack(track);
  8909. this.autoRemoteTextTracks_.removeTrack(track);
  8910. }
  8911. /**
  8912. * Gets available media playback quality metrics as specified by the W3C's Media
  8913. * Playback Quality API.
  8914. *
  8915. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  8916. *
  8917. * @return {Object}
  8918. * An object with supported media playback quality metrics
  8919. *
  8920. * @abstract
  8921. */
  8922. getVideoPlaybackQuality() {
  8923. return {};
  8924. }
  8925. /**
  8926. * Attempt to create a floating video window always on top of other windows
  8927. * so that users may continue consuming media while they interact with other
  8928. * content sites, or applications on their device.
  8929. *
  8930. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  8931. *
  8932. * @return {Promise|undefined}
  8933. * A promise with a Picture-in-Picture window if the browser supports
  8934. * Promises (or one was passed in as an option). It returns undefined
  8935. * otherwise.
  8936. *
  8937. * @abstract
  8938. */
  8939. requestPictureInPicture() {
  8940. return Promise.reject();
  8941. }
  8942. /**
  8943. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  8944. * Defaults to true, as it should be considered disabled if the tech does not support pip
  8945. *
  8946. * @abstract
  8947. */
  8948. disablePictureInPicture() {
  8949. return true;
  8950. }
  8951. /**
  8952. * A method to set or unset the 'disablePictureInPicture' <video> property.
  8953. *
  8954. * @abstract
  8955. */
  8956. setDisablePictureInPicture() {}
  8957. /**
  8958. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  8959. *
  8960. * @param {function} cb
  8961. * @return {number} request id
  8962. */
  8963. requestVideoFrameCallback(cb) {
  8964. const id = newGUID();
  8965. if (!this.isReady_ || this.paused()) {
  8966. this.queuedHanders_.add(id);
  8967. this.one('playing', () => {
  8968. if (this.queuedHanders_.has(id)) {
  8969. this.queuedHanders_.delete(id);
  8970. cb();
  8971. }
  8972. });
  8973. } else {
  8974. this.requestNamedAnimationFrame(id, cb);
  8975. }
  8976. return id;
  8977. }
  8978. /**
  8979. * A fallback implementation of cancelVideoFrameCallback
  8980. *
  8981. * @param {number} id id of callback to be cancelled
  8982. */
  8983. cancelVideoFrameCallback(id) {
  8984. if (this.queuedHanders_.has(id)) {
  8985. this.queuedHanders_.delete(id);
  8986. } else {
  8987. this.cancelNamedAnimationFrame(id);
  8988. }
  8989. }
  8990. /**
  8991. * A method to set a poster from a `Tech`.
  8992. *
  8993. * @abstract
  8994. */
  8995. setPoster() {}
  8996. /**
  8997. * A method to check for the presence of the 'playsinline' <video> attribute.
  8998. *
  8999. * @abstract
  9000. */
  9001. playsinline() {}
  9002. /**
  9003. * A method to set or unset the 'playsinline' <video> attribute.
  9004. *
  9005. * @abstract
  9006. */
  9007. setPlaysinline() {}
  9008. /**
  9009. * Attempt to force override of native audio tracks.
  9010. *
  9011. * @param {boolean} override - If set to true native audio will be overridden,
  9012. * otherwise native audio will potentially be used.
  9013. *
  9014. * @abstract
  9015. */
  9016. overrideNativeAudioTracks(override) {}
  9017. /**
  9018. * Attempt to force override of native video tracks.
  9019. *
  9020. * @param {boolean} override - If set to true native video will be overridden,
  9021. * otherwise native video will potentially be used.
  9022. *
  9023. * @abstract
  9024. */
  9025. overrideNativeVideoTracks(override) {}
  9026. /**
  9027. * Check if the tech can support the given mime-type.
  9028. *
  9029. * The base tech does not support any type, but source handlers might
  9030. * overwrite this.
  9031. *
  9032. * @param {string} _type
  9033. * The mimetype to check for support
  9034. *
  9035. * @return {string}
  9036. * 'probably', 'maybe', or empty string
  9037. *
  9038. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  9039. *
  9040. * @abstract
  9041. */
  9042. canPlayType(_type) {
  9043. return '';
  9044. }
  9045. /**
  9046. * Check if the type is supported by this tech.
  9047. *
  9048. * The base tech does not support any type, but source handlers might
  9049. * overwrite this.
  9050. *
  9051. * @param {string} _type
  9052. * The media type to check
  9053. * @return {string} Returns the native video element's response
  9054. */
  9055. static canPlayType(_type) {
  9056. return '';
  9057. }
  9058. /**
  9059. * Check if the tech can support the given source
  9060. *
  9061. * @param {Object} srcObj
  9062. * The source object
  9063. * @param {Object} options
  9064. * The options passed to the tech
  9065. * @return {string} 'probably', 'maybe', or '' (empty string)
  9066. */
  9067. static canPlaySource(srcObj, options) {
  9068. return Tech.canPlayType(srcObj.type);
  9069. }
  9070. /*
  9071. * Return whether the argument is a Tech or not.
  9072. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  9073. *
  9074. * @param {Object} component
  9075. * The item to check
  9076. *
  9077. * @return {boolean}
  9078. * Whether it is a tech or not
  9079. * - True if it is a tech
  9080. * - False if it is not
  9081. */
  9082. static isTech(component) {
  9083. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  9084. }
  9085. /**
  9086. * Registers a `Tech` into a shared list for videojs.
  9087. *
  9088. * @param {string} name
  9089. * Name of the `Tech` to register.
  9090. *
  9091. * @param {Object} tech
  9092. * The `Tech` class to register.
  9093. */
  9094. static registerTech(name, tech) {
  9095. if (!Tech.techs_) {
  9096. Tech.techs_ = {};
  9097. }
  9098. if (!Tech.isTech(tech)) {
  9099. throw new Error(`Tech ${name} must be a Tech`);
  9100. }
  9101. if (!Tech.canPlayType) {
  9102. throw new Error('Techs must have a static canPlayType method on them');
  9103. }
  9104. if (!Tech.canPlaySource) {
  9105. throw new Error('Techs must have a static canPlaySource method on them');
  9106. }
  9107. name = toTitleCase(name);
  9108. Tech.techs_[name] = tech;
  9109. Tech.techs_[toLowerCase(name)] = tech;
  9110. if (name !== 'Tech') {
  9111. // camel case the techName for use in techOrder
  9112. Tech.defaultTechOrder_.push(name);
  9113. }
  9114. return tech;
  9115. }
  9116. /**
  9117. * Get a `Tech` from the shared list by name.
  9118. *
  9119. * @param {string} name
  9120. * `camelCase` or `TitleCase` name of the Tech to get
  9121. *
  9122. * @return {Tech|undefined}
  9123. * The `Tech` or undefined if there was no tech with the name requested.
  9124. */
  9125. static getTech(name) {
  9126. if (!name) {
  9127. return;
  9128. }
  9129. if (Tech.techs_ && Tech.techs_[name]) {
  9130. return Tech.techs_[name];
  9131. }
  9132. name = toTitleCase(name);
  9133. if (window && window.videojs && window.videojs[name]) {
  9134. log.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  9135. return window.videojs[name];
  9136. }
  9137. }
  9138. }
  9139. /**
  9140. * Get the {@link VideoTrackList}
  9141. *
  9142. * @returns {VideoTrackList}
  9143. * @method Tech.prototype.videoTracks
  9144. */
  9145. /**
  9146. * Get the {@link AudioTrackList}
  9147. *
  9148. * @returns {AudioTrackList}
  9149. * @method Tech.prototype.audioTracks
  9150. */
  9151. /**
  9152. * Get the {@link TextTrackList}
  9153. *
  9154. * @returns {TextTrackList}
  9155. * @method Tech.prototype.textTracks
  9156. */
  9157. /**
  9158. * Get the remote element {@link TextTrackList}
  9159. *
  9160. * @returns {TextTrackList}
  9161. * @method Tech.prototype.remoteTextTracks
  9162. */
  9163. /**
  9164. * Get the remote element {@link HtmlTrackElementList}
  9165. *
  9166. * @returns {HtmlTrackElementList}
  9167. * @method Tech.prototype.remoteTextTrackEls
  9168. */
  9169. ALL.names.forEach(function (name) {
  9170. const props = ALL[name];
  9171. Tech.prototype[props.getterName] = function () {
  9172. this[props.privateName] = this[props.privateName] || new props.ListClass();
  9173. return this[props.privateName];
  9174. };
  9175. });
  9176. /**
  9177. * List of associated text tracks
  9178. *
  9179. * @type {TextTrackList}
  9180. * @private
  9181. * @property Tech#textTracks_
  9182. */
  9183. /**
  9184. * List of associated audio tracks.
  9185. *
  9186. * @type {AudioTrackList}
  9187. * @private
  9188. * @property Tech#audioTracks_
  9189. */
  9190. /**
  9191. * List of associated video tracks.
  9192. *
  9193. * @type {VideoTrackList}
  9194. * @private
  9195. * @property Tech#videoTracks_
  9196. */
  9197. /**
  9198. * Boolean indicating whether the `Tech` supports volume control.
  9199. *
  9200. * @type {boolean}
  9201. * @default
  9202. */
  9203. Tech.prototype.featuresVolumeControl = true;
  9204. /**
  9205. * Boolean indicating whether the `Tech` supports muting volume.
  9206. *
  9207. * @type {boolean}
  9208. * @default
  9209. */
  9210. Tech.prototype.featuresMuteControl = true;
  9211. /**
  9212. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  9213. * Resizing plugins using request fullscreen reloads the plugin
  9214. *
  9215. * @type {boolean}
  9216. * @default
  9217. */
  9218. Tech.prototype.featuresFullscreenResize = false;
  9219. /**
  9220. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  9221. * plays. Examples:
  9222. * - Set player to play 2x (twice) as fast
  9223. * - Set player to play 0.5x (half) as fast
  9224. *
  9225. * @type {boolean}
  9226. * @default
  9227. */
  9228. Tech.prototype.featuresPlaybackRate = false;
  9229. /**
  9230. * Boolean indicating whether the `Tech` supports the `progress` event.
  9231. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  9232. *
  9233. * @type {boolean}
  9234. * @default
  9235. */
  9236. Tech.prototype.featuresProgressEvents = false;
  9237. /**
  9238. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  9239. *
  9240. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  9241. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  9242. * a new source.
  9243. *
  9244. * @type {boolean}
  9245. * @default
  9246. */
  9247. Tech.prototype.featuresSourceset = false;
  9248. /**
  9249. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  9250. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  9251. *
  9252. * @type {boolean}
  9253. * @default
  9254. */
  9255. Tech.prototype.featuresTimeupdateEvents = false;
  9256. /**
  9257. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  9258. * This will help us integrate with native `TextTrack`s if the browser supports them.
  9259. *
  9260. * @type {boolean}
  9261. * @default
  9262. */
  9263. Tech.prototype.featuresNativeTextTracks = false;
  9264. /**
  9265. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  9266. *
  9267. * @type {boolean}
  9268. * @default
  9269. */
  9270. Tech.prototype.featuresVideoFrameCallback = false;
  9271. /**
  9272. * A functional mixin for techs that want to use the Source Handler pattern.
  9273. * Source handlers are scripts for handling specific formats.
  9274. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  9275. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  9276. * Example: `Tech.withSourceHandlers.call(MyTech);`
  9277. *
  9278. * @param {Tech} _Tech
  9279. * The tech to add source handler functions to.
  9280. *
  9281. * @mixes Tech~SourceHandlerAdditions
  9282. */
  9283. Tech.withSourceHandlers = function (_Tech) {
  9284. /**
  9285. * Register a source handler
  9286. *
  9287. * @param {Function} handler
  9288. * The source handler class
  9289. *
  9290. * @param {number} [index]
  9291. * Register it at the following index
  9292. */
  9293. _Tech.registerSourceHandler = function (handler, index) {
  9294. let handlers = _Tech.sourceHandlers;
  9295. if (!handlers) {
  9296. handlers = _Tech.sourceHandlers = [];
  9297. }
  9298. if (index === undefined) {
  9299. // add to the end of the list
  9300. index = handlers.length;
  9301. }
  9302. handlers.splice(index, 0, handler);
  9303. };
  9304. /**
  9305. * Check if the tech can support the given type. Also checks the
  9306. * Techs sourceHandlers.
  9307. *
  9308. * @param {string} type
  9309. * The mimetype to check.
  9310. *
  9311. * @return {string}
  9312. * 'probably', 'maybe', or '' (empty string)
  9313. */
  9314. _Tech.canPlayType = function (type) {
  9315. const handlers = _Tech.sourceHandlers || [];
  9316. let can;
  9317. for (let i = 0; i < handlers.length; i++) {
  9318. can = handlers[i].canPlayType(type);
  9319. if (can) {
  9320. return can;
  9321. }
  9322. }
  9323. return '';
  9324. };
  9325. /**
  9326. * Returns the first source handler that supports the source.
  9327. *
  9328. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  9329. *
  9330. * @param {SourceObject} source
  9331. * The source object
  9332. *
  9333. * @param {Object} options
  9334. * The options passed to the tech
  9335. *
  9336. * @return {SourceHandler|null}
  9337. * The first source handler that supports the source or null if
  9338. * no SourceHandler supports the source
  9339. */
  9340. _Tech.selectSourceHandler = function (source, options) {
  9341. const handlers = _Tech.sourceHandlers || [];
  9342. let can;
  9343. for (let i = 0; i < handlers.length; i++) {
  9344. can = handlers[i].canHandleSource(source, options);
  9345. if (can) {
  9346. return handlers[i];
  9347. }
  9348. }
  9349. return null;
  9350. };
  9351. /**
  9352. * Check if the tech can support the given source.
  9353. *
  9354. * @param {SourceObject} srcObj
  9355. * The source object
  9356. *
  9357. * @param {Object} options
  9358. * The options passed to the tech
  9359. *
  9360. * @return {string}
  9361. * 'probably', 'maybe', or '' (empty string)
  9362. */
  9363. _Tech.canPlaySource = function (srcObj, options) {
  9364. const sh = _Tech.selectSourceHandler(srcObj, options);
  9365. if (sh) {
  9366. return sh.canHandleSource(srcObj, options);
  9367. }
  9368. return '';
  9369. };
  9370. /**
  9371. * When using a source handler, prefer its implementation of
  9372. * any function normally provided by the tech.
  9373. */
  9374. const deferrable = ['seekable', 'seeking', 'duration'];
  9375. /**
  9376. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  9377. * function if it exists, with a fallback to the Techs seekable function.
  9378. *
  9379. * @method _Tech.seekable
  9380. */
  9381. /**
  9382. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  9383. * function if it exists, otherwise it will fallback to the techs duration function.
  9384. *
  9385. * @method _Tech.duration
  9386. */
  9387. deferrable.forEach(function (fnName) {
  9388. const originalFn = this[fnName];
  9389. if (typeof originalFn !== 'function') {
  9390. return;
  9391. }
  9392. this[fnName] = function () {
  9393. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  9394. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  9395. }
  9396. return originalFn.apply(this, arguments);
  9397. };
  9398. }, _Tech.prototype);
  9399. /**
  9400. * Create a function for setting the source using a source object
  9401. * and source handlers.
  9402. * Should never be called unless a source handler was found.
  9403. *
  9404. * @param {SourceObject} source
  9405. * A source object with src and type keys
  9406. */
  9407. _Tech.prototype.setSource = function (source) {
  9408. let sh = _Tech.selectSourceHandler(source, this.options_);
  9409. if (!sh) {
  9410. // Fall back to a native source handler when unsupported sources are
  9411. // deliberately set
  9412. if (_Tech.nativeSourceHandler) {
  9413. sh = _Tech.nativeSourceHandler;
  9414. } else {
  9415. log.error('No source handler found for the current source.');
  9416. }
  9417. }
  9418. // Dispose any existing source handler
  9419. this.disposeSourceHandler();
  9420. this.off('dispose', this.disposeSourceHandler_);
  9421. if (sh !== _Tech.nativeSourceHandler) {
  9422. this.currentSource_ = source;
  9423. }
  9424. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  9425. this.one('dispose', this.disposeSourceHandler_);
  9426. };
  9427. /**
  9428. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  9429. *
  9430. * @listens Tech#dispose
  9431. */
  9432. _Tech.prototype.disposeSourceHandler = function () {
  9433. // if we have a source and get another one
  9434. // then we are loading something new
  9435. // than clear all of our current tracks
  9436. if (this.currentSource_) {
  9437. this.clearTracks(['audio', 'video']);
  9438. this.currentSource_ = null;
  9439. }
  9440. // always clean up auto-text tracks
  9441. this.cleanupAutoTextTracks();
  9442. if (this.sourceHandler_) {
  9443. if (this.sourceHandler_.dispose) {
  9444. this.sourceHandler_.dispose();
  9445. }
  9446. this.sourceHandler_ = null;
  9447. }
  9448. };
  9449. };
  9450. // The base Tech class needs to be registered as a Component. It is the only
  9451. // Tech that can be registered as a Component.
  9452. Component.registerComponent('Tech', Tech);
  9453. Tech.registerTech('Tech', Tech);
  9454. /**
  9455. * A list of techs that should be added to techOrder on Players
  9456. *
  9457. * @private
  9458. */
  9459. Tech.defaultTechOrder_ = [];
  9460. /**
  9461. * @file middleware.js
  9462. * @module middleware
  9463. */
  9464. /** @import Player from '../player' */
  9465. /** @import Tech from '../tech/tech' */
  9466. const middlewares = {};
  9467. const middlewareInstances = {};
  9468. const TERMINATOR = {};
  9469. /**
  9470. * A middleware object is a plain JavaScript object that has methods that
  9471. * match the {@link Tech} methods found in the lists of allowed
  9472. * {@link module:middleware.allowedGetters|getters},
  9473. * {@link module:middleware.allowedSetters|setters}, and
  9474. * {@link module:middleware.allowedMediators|mediators}.
  9475. *
  9476. * @typedef {Object} MiddlewareObject
  9477. */
  9478. /**
  9479. * A middleware factory function that should return a
  9480. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  9481. *
  9482. * This factory will be called for each player when needed, with the player
  9483. * passed in as an argument.
  9484. *
  9485. * @callback MiddlewareFactory
  9486. * @param {Player} player
  9487. * A Video.js player.
  9488. */
  9489. /**
  9490. * Define a middleware that the player should use by way of a factory function
  9491. * that returns a middleware object.
  9492. *
  9493. * @param {string} type
  9494. * The MIME type to match or `"*"` for all MIME types.
  9495. *
  9496. * @param {MiddlewareFactory} middleware
  9497. * A middleware factory function that will be executed for
  9498. * matching types.
  9499. */
  9500. function use(type, middleware) {
  9501. middlewares[type] = middlewares[type] || [];
  9502. middlewares[type].push(middleware);
  9503. }
  9504. /**
  9505. * Asynchronously sets a source using middleware by recursing through any
  9506. * matching middlewares and calling `setSource` on each, passing along the
  9507. * previous returned value each time.
  9508. *
  9509. * @param {Player} player
  9510. * A {@link Player} instance.
  9511. *
  9512. * @param {Tech~SourceObject} src
  9513. * A source object.
  9514. *
  9515. * @param {Function}
  9516. * The next middleware to run.
  9517. */
  9518. function setSource(player, src, next) {
  9519. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  9520. }
  9521. /**
  9522. * When the tech is set, passes the tech to each middleware's `setTech` method.
  9523. *
  9524. * @param {Object[]} middleware
  9525. * An array of middleware instances.
  9526. *
  9527. * @param {Tech} tech
  9528. * A Video.js tech.
  9529. */
  9530. function setTech(middleware, tech) {
  9531. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  9532. }
  9533. /**
  9534. * Calls a getter on the tech first, through each middleware
  9535. * from right to left to the player.
  9536. *
  9537. * @param {Object[]} middleware
  9538. * An array of middleware instances.
  9539. *
  9540. * @param {Tech} tech
  9541. * The current tech.
  9542. *
  9543. * @param {string} method
  9544. * A method name.
  9545. *
  9546. * @return {*}
  9547. * The final value from the tech after middleware has intercepted it.
  9548. */
  9549. function get(middleware, tech, method) {
  9550. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  9551. }
  9552. /**
  9553. * Takes the argument given to the player and calls the setter method on each
  9554. * middleware from left to right to the tech.
  9555. *
  9556. * @param {Object[]} middleware
  9557. * An array of middleware instances.
  9558. *
  9559. * @param {Tech} tech
  9560. * The current tech.
  9561. *
  9562. * @param {string} method
  9563. * A method name.
  9564. *
  9565. * @param {*} arg
  9566. * The value to set on the tech.
  9567. *
  9568. * @return {*}
  9569. * The return value of the `method` of the `tech`.
  9570. */
  9571. function set(middleware, tech, method, arg) {
  9572. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  9573. }
  9574. /**
  9575. * Takes the argument given to the player and calls the `call` version of the
  9576. * method on each middleware from left to right.
  9577. *
  9578. * Then, call the passed in method on the tech and return the result unchanged
  9579. * back to the player, through middleware, this time from right to left.
  9580. *
  9581. * @param {Object[]} middleware
  9582. * An array of middleware instances.
  9583. *
  9584. * @param {Tech} tech
  9585. * The current tech.
  9586. *
  9587. * @param {string} method
  9588. * A method name.
  9589. *
  9590. * @param {*} arg
  9591. * The value to set on the tech.
  9592. *
  9593. * @return {*}
  9594. * The return value of the `method` of the `tech`, regardless of the
  9595. * return values of middlewares.
  9596. */
  9597. function mediate(middleware, tech, method, arg = null) {
  9598. const callMethod = 'call' + toTitleCase(method);
  9599. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  9600. const terminated = middlewareValue === TERMINATOR;
  9601. // deprecated. The `null` return value should instead return TERMINATOR to
  9602. // prevent confusion if a techs method actually returns null.
  9603. const returnValue = terminated ? null : tech[method](middlewareValue);
  9604. executeRight(middleware, method, returnValue, terminated);
  9605. return returnValue;
  9606. }
  9607. /**
  9608. * Enumeration of allowed getters where the keys are method names.
  9609. *
  9610. * @type {Object}
  9611. */
  9612. const allowedGetters = {
  9613. buffered: 1,
  9614. currentTime: 1,
  9615. duration: 1,
  9616. muted: 1,
  9617. played: 1,
  9618. paused: 1,
  9619. seekable: 1,
  9620. volume: 1,
  9621. ended: 1
  9622. };
  9623. /**
  9624. * Enumeration of allowed setters where the keys are method names.
  9625. *
  9626. * @type {Object}
  9627. */
  9628. const allowedSetters = {
  9629. setCurrentTime: 1,
  9630. setMuted: 1,
  9631. setVolume: 1
  9632. };
  9633. /**
  9634. * Enumeration of allowed mediators where the keys are method names.
  9635. *
  9636. * @type {Object}
  9637. */
  9638. const allowedMediators = {
  9639. play: 1,
  9640. pause: 1
  9641. };
  9642. function middlewareIterator(method) {
  9643. return (value, mw) => {
  9644. // if the previous middleware terminated, pass along the termination
  9645. if (value === TERMINATOR) {
  9646. return TERMINATOR;
  9647. }
  9648. if (mw[method]) {
  9649. return mw[method](value);
  9650. }
  9651. return value;
  9652. };
  9653. }
  9654. function executeRight(mws, method, value, terminated) {
  9655. for (let i = mws.length - 1; i >= 0; i--) {
  9656. const mw = mws[i];
  9657. if (mw[method]) {
  9658. mw[method](terminated, value);
  9659. }
  9660. }
  9661. }
  9662. /**
  9663. * Clear the middleware cache for a player.
  9664. *
  9665. * @param {Player} player
  9666. * A {@link Player} instance.
  9667. */
  9668. function clearCacheForPlayer(player) {
  9669. if (middlewareInstances.hasOwnProperty(player.id())) {
  9670. delete middlewareInstances[player.id()];
  9671. }
  9672. }
  9673. /**
  9674. * {
  9675. * [playerId]: [[mwFactory, mwInstance], ...]
  9676. * }
  9677. *
  9678. * @private
  9679. */
  9680. function getOrCreateFactory(player, mwFactory) {
  9681. const mws = middlewareInstances[player.id()];
  9682. let mw = null;
  9683. if (mws === undefined || mws === null) {
  9684. mw = mwFactory(player);
  9685. middlewareInstances[player.id()] = [[mwFactory, mw]];
  9686. return mw;
  9687. }
  9688. for (let i = 0; i < mws.length; i++) {
  9689. const [mwf, mwi] = mws[i];
  9690. if (mwf !== mwFactory) {
  9691. continue;
  9692. }
  9693. mw = mwi;
  9694. }
  9695. if (mw === null) {
  9696. mw = mwFactory(player);
  9697. mws.push([mwFactory, mw]);
  9698. }
  9699. return mw;
  9700. }
  9701. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  9702. const [mwFactory, ...mwrest] = middleware;
  9703. // if mwFactory is a string, then we're at a fork in the road
  9704. if (typeof mwFactory === 'string') {
  9705. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  9706. // if we have an mwFactory, call it with the player to get the mw,
  9707. // then call the mw's setSource method
  9708. } else if (mwFactory) {
  9709. const mw = getOrCreateFactory(player, mwFactory);
  9710. // if setSource isn't present, implicitly select this middleware
  9711. if (!mw.setSource) {
  9712. acc.push(mw);
  9713. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9714. }
  9715. mw.setSource(Object.assign({}, src), function (err, _src) {
  9716. // something happened, try the next middleware on the current level
  9717. // make sure to use the old src
  9718. if (err) {
  9719. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9720. }
  9721. // we've succeeded, now we need to go deeper
  9722. acc.push(mw);
  9723. // if it's the same type, continue down the current chain
  9724. // otherwise, we want to go down the new chain
  9725. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  9726. });
  9727. } else if (mwrest.length) {
  9728. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9729. } else if (lastRun) {
  9730. next(src, acc);
  9731. } else {
  9732. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  9733. }
  9734. }
  9735. /** @import Player from '../player' */
  9736. /**
  9737. * Mimetypes
  9738. *
  9739. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  9740. * @typedef Mimetypes~Kind
  9741. * @enum
  9742. */
  9743. const MimetypesKind = {
  9744. opus: 'video/ogg',
  9745. ogv: 'video/ogg',
  9746. mp4: 'video/mp4',
  9747. mov: 'video/mp4',
  9748. m4v: 'video/mp4',
  9749. mkv: 'video/x-matroska',
  9750. m4a: 'audio/mp4',
  9751. mp3: 'audio/mpeg',
  9752. aac: 'audio/aac',
  9753. caf: 'audio/x-caf',
  9754. flac: 'audio/flac',
  9755. oga: 'audio/ogg',
  9756. wav: 'audio/wav',
  9757. m3u8: 'application/x-mpegURL',
  9758. mpd: 'application/dash+xml',
  9759. jpg: 'image/jpeg',
  9760. jpeg: 'image/jpeg',
  9761. gif: 'image/gif',
  9762. png: 'image/png',
  9763. svg: 'image/svg+xml',
  9764. webp: 'image/webp'
  9765. };
  9766. /**
  9767. * Get the mimetype of a given src url if possible
  9768. *
  9769. * @param {string} src
  9770. * The url to the src
  9771. *
  9772. * @return {string}
  9773. * return the mimetype if it was known or empty string otherwise
  9774. */
  9775. const getMimetype = function (src = '') {
  9776. const ext = getFileExtension(src);
  9777. const mimetype = MimetypesKind[ext.toLowerCase()];
  9778. return mimetype || '';
  9779. };
  9780. /**
  9781. * Find the mime type of a given source string if possible. Uses the player
  9782. * source cache.
  9783. *
  9784. * @param {Player} player
  9785. * The player object
  9786. *
  9787. * @param {string} src
  9788. * The source string
  9789. *
  9790. * @return {string}
  9791. * The type that was found
  9792. */
  9793. const findMimetype = (player, src) => {
  9794. if (!src) {
  9795. return '';
  9796. }
  9797. // 1. check for the type in the `source` cache
  9798. if (player.cache_.source.src === src && player.cache_.source.type) {
  9799. return player.cache_.source.type;
  9800. }
  9801. // 2. see if we have this source in our `currentSources` cache
  9802. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  9803. if (matchingSources.length) {
  9804. return matchingSources[0].type;
  9805. }
  9806. // 3. look for the src url in source elements and use the type there
  9807. const sources = player.$$('source');
  9808. for (let i = 0; i < sources.length; i++) {
  9809. const s = sources[i];
  9810. if (s.type && s.src && s.src === src) {
  9811. return s.type;
  9812. }
  9813. }
  9814. // 4. finally fallback to our list of mime types based on src url extension
  9815. return getMimetype(src);
  9816. };
  9817. /**
  9818. * @module filter-source
  9819. */
  9820. /**
  9821. * Filter out single bad source objects or multiple source objects in an
  9822. * array. Also flattens nested source object arrays into a 1 dimensional
  9823. * array of source objects.
  9824. *
  9825. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  9826. * The src object to filter
  9827. *
  9828. * @return {Tech~SourceObject[]}
  9829. * An array of sourceobjects containing only valid sources
  9830. *
  9831. * @private
  9832. */
  9833. const filterSource = function (src) {
  9834. // traverse array
  9835. if (Array.isArray(src)) {
  9836. let newsrc = [];
  9837. src.forEach(function (srcobj) {
  9838. srcobj = filterSource(srcobj);
  9839. if (Array.isArray(srcobj)) {
  9840. newsrc = newsrc.concat(srcobj);
  9841. } else if (isObject(srcobj)) {
  9842. newsrc.push(srcobj);
  9843. }
  9844. });
  9845. src = newsrc;
  9846. } else if (typeof src === 'string' && src.trim()) {
  9847. // convert string into object
  9848. src = [fixSource({
  9849. src
  9850. })];
  9851. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  9852. // src is already valid
  9853. src = [fixSource(src)];
  9854. } else {
  9855. // invalid source, turn it into an empty array
  9856. src = [];
  9857. }
  9858. return src;
  9859. };
  9860. /**
  9861. * Checks src mimetype, adding it when possible
  9862. *
  9863. * @param {Tech~SourceObject} src
  9864. * The src object to check
  9865. * @return {Tech~SourceObject}
  9866. * src Object with known type
  9867. */
  9868. function fixSource(src) {
  9869. if (!src.type) {
  9870. const mimetype = getMimetype(src.src);
  9871. if (mimetype) {
  9872. src.type = mimetype;
  9873. }
  9874. }
  9875. return src;
  9876. }
  9877. 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=\
  9878. // /**
  9879. // Determine the keycode for the 'back' key based on the platform
  9880. const backKeyCode = IS_TIZEN ? 10009 : IS_WEBOS ? 461 : 8;
  9881. const SpatialNavKeyCodes = {
  9882. codes: {
  9883. play: 415,
  9884. pause: 19,
  9885. ff: 417,
  9886. rw: 412,
  9887. back: backKeyCode
  9888. },
  9889. names: {
  9890. 415: 'play',
  9891. 19: 'pause',
  9892. 417: 'ff',
  9893. 412: 'rw',
  9894. [backKeyCode]: 'back'
  9895. },
  9896. isEventKey(event, keyName) {
  9897. keyName = keyName.toLowerCase();
  9898. if (this.names[event.keyCode] && this.names[event.keyCode] === keyName) {
  9899. return true;
  9900. }
  9901. return false;
  9902. },
  9903. getEventName(event) {
  9904. if (this.names[event.keyCode]) {
  9905. return this.names[event.keyCode];
  9906. } else if (this.codes[event.code]) {
  9907. const code = this.codes[event.code];
  9908. return this.names[code];
  9909. }
  9910. return null;
  9911. }
  9912. };
  9913. /**
  9914. * @file spatial-navigation.js
  9915. */
  9916. /** @import Component from './component' */
  9917. /** @import Player from './player' */
  9918. // The number of seconds the `step*` functions move the timeline.
  9919. const STEP_SECONDS$1 = 5;
  9920. /**
  9921. * Spatial Navigation in Video.js enhances user experience and accessibility on smartTV devices,
  9922. * enabling seamless navigation through interactive elements within the player using remote control arrow keys.
  9923. * This functionality allows users to effortlessly navigate through focusable components.
  9924. *
  9925. * @extends EventTarget
  9926. */
  9927. class SpatialNavigation extends EventTarget {
  9928. /**
  9929. * Constructs a SpatialNavigation instance with initial settings.
  9930. * Sets up the player instance, and prepares the spatial navigation system.
  9931. *
  9932. * @class
  9933. * @param {Player} player - The Video.js player instance to which the spatial navigation is attached.
  9934. */
  9935. constructor(player) {
  9936. super();
  9937. this.player_ = player;
  9938. this.focusableComponents = [];
  9939. this.isListening_ = false;
  9940. this.isPaused_ = false;
  9941. this.onKeyDown_ = this.onKeyDown_.bind(this);
  9942. this.lastFocusedComponent_ = null;
  9943. }
  9944. /**
  9945. * Starts the spatial navigation by adding a keydown event listener to the video container.
  9946. * This method ensures that the event listener is added only once.
  9947. */
  9948. start() {
  9949. // If the listener is already active, exit early.
  9950. if (this.isListening_) {
  9951. return;
  9952. }
  9953. // Add the event listener since the listener is not yet active.
  9954. this.player_.on('keydown', this.onKeyDown_);
  9955. this.player_.on('modalKeydown', this.onKeyDown_);
  9956. // Listen for source change events
  9957. this.player_.on('loadedmetadata', () => {
  9958. this.focus(this.updateFocusableComponents()[0]);
  9959. });
  9960. this.player_.on('modalclose', () => {
  9961. this.refocusComponent();
  9962. });
  9963. this.player_.on('focusin', this.handlePlayerFocus_.bind(this));
  9964. this.player_.on('focusout', this.handlePlayerBlur_.bind(this));
  9965. this.isListening_ = true;
  9966. if (this.player_.errorDisplay) {
  9967. this.player_.errorDisplay.on('aftermodalfill', () => {
  9968. this.updateFocusableComponents();
  9969. if (this.focusableComponents.length) {
  9970. // The modal has focusable components:
  9971. if (this.focusableComponents.length > 1) {
  9972. // The modal has close button + some additional buttons.
  9973. // Focusing first additional button:
  9974. this.focusableComponents[1].focus();
  9975. } else {
  9976. // The modal has only close button,
  9977. // Focusing it:
  9978. this.focusableComponents[0].focus();
  9979. }
  9980. }
  9981. });
  9982. }
  9983. }
  9984. /**
  9985. * Stops the spatial navigation by removing the keydown event listener from the video container.
  9986. * Also sets the `isListening_` flag to false.
  9987. */
  9988. stop() {
  9989. this.player_.off('keydown', this.onKeyDown_);
  9990. this.isListening_ = false;
  9991. }
  9992. /**
  9993. * Responds to keydown events for spatial navigation and media control.
  9994. *
  9995. * Determines if spatial navigation or media control is active and handles key inputs accordingly.
  9996. *
  9997. * @param {KeyboardEvent} event - The keydown event to be handled.
  9998. */
  9999. onKeyDown_(event) {
  10000. // Determine if the event is a custom modalKeydown event
  10001. const actualEvent = event.originalEvent ? event.originalEvent : event;
  10002. if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(actualEvent.key)) {
  10003. // Handle directional navigation
  10004. if (this.isPaused_) {
  10005. return;
  10006. }
  10007. actualEvent.preventDefault();
  10008. // "ArrowLeft" => "left" etc
  10009. const direction = actualEvent.key.substring(5).toLowerCase();
  10010. this.move(direction);
  10011. } else if (SpatialNavKeyCodes.isEventKey(actualEvent, 'play') || SpatialNavKeyCodes.isEventKey(actualEvent, 'pause') || SpatialNavKeyCodes.isEventKey(actualEvent, 'ff') || SpatialNavKeyCodes.isEventKey(actualEvent, 'rw')) {
  10012. // Handle media actions
  10013. actualEvent.preventDefault();
  10014. const action = SpatialNavKeyCodes.getEventName(actualEvent);
  10015. this.performMediaAction_(action);
  10016. } else if (SpatialNavKeyCodes.isEventKey(actualEvent, 'Back') && event.target && typeof event.target.closeable === 'function' && event.target.closeable()) {
  10017. actualEvent.preventDefault();
  10018. event.target.close();
  10019. }
  10020. }
  10021. /**
  10022. * Performs media control actions based on the given key input.
  10023. *
  10024. * Controls the playback and seeking functionalities of the media player.
  10025. *
  10026. * @param {string} key - The key representing the media action to be performed.
  10027. * Accepted keys: 'play', 'pause', 'ff' (fast-forward), 'rw' (rewind).
  10028. */
  10029. performMediaAction_(key) {
  10030. if (this.player_) {
  10031. switch (key) {
  10032. case 'play':
  10033. if (this.player_.paused()) {
  10034. this.player_.play();
  10035. }
  10036. break;
  10037. case 'pause':
  10038. if (!this.player_.paused()) {
  10039. this.player_.pause();
  10040. }
  10041. break;
  10042. case 'ff':
  10043. this.userSeek_(this.player_.currentTime() + STEP_SECONDS$1);
  10044. break;
  10045. case 'rw':
  10046. this.userSeek_(this.player_.currentTime() - STEP_SECONDS$1);
  10047. break;
  10048. }
  10049. }
  10050. }
  10051. /**
  10052. * Prevent liveThreshold from causing seeks to seem like they
  10053. * are not happening from a user perspective.
  10054. *
  10055. * @param {number} ct
  10056. * current time to seek to
  10057. */
  10058. userSeek_(ct) {
  10059. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  10060. this.player_.liveTracker.nextSeekedFromUser();
  10061. }
  10062. this.player_.currentTime(ct);
  10063. }
  10064. /**
  10065. * Pauses the spatial navigation functionality.
  10066. * This method sets a flag that can be used to temporarily disable the navigation logic.
  10067. */
  10068. pause() {
  10069. this.isPaused_ = true;
  10070. }
  10071. /**
  10072. * Resumes the spatial navigation functionality if it has been paused.
  10073. * This method resets the pause flag, re-enabling the navigation logic.
  10074. */
  10075. resume() {
  10076. this.isPaused_ = false;
  10077. }
  10078. /**
  10079. * Handles Player Blur.
  10080. *
  10081. * @param {string|Event|Object} event
  10082. * The name of the event, an `Event`, or an object with a key of type set to
  10083. * an event name.
  10084. *
  10085. * Calls for handling of the Player Blur if:
  10086. * *The next focused element is not a child of current focused element &
  10087. * The next focused element is not a child of the Player.
  10088. * *There is no next focused element
  10089. */
  10090. handlePlayerBlur_(event) {
  10091. const nextFocusedElement = event.relatedTarget;
  10092. let isChildrenOfPlayer = null;
  10093. const currentComponent = this.getCurrentComponent(event.target);
  10094. if (nextFocusedElement) {
  10095. isChildrenOfPlayer = Boolean(nextFocusedElement.closest('.video-js'));
  10096. // If nextFocusedElement is the 'TextTrackSettings' component
  10097. if (nextFocusedElement.classList.contains('vjs-text-track-settings') && !this.isPaused_) {
  10098. this.searchForTrackSelect_();
  10099. }
  10100. }
  10101. if (!event.currentTarget.contains(event.relatedTarget) && !isChildrenOfPlayer || !nextFocusedElement) {
  10102. if (currentComponent && currentComponent.name() === 'CloseButton') {
  10103. this.refocusComponent();
  10104. } else {
  10105. this.pause();
  10106. if (currentComponent && currentComponent.el()) {
  10107. // Store last focused component
  10108. this.lastFocusedComponent_ = currentComponent;
  10109. }
  10110. }
  10111. }
  10112. }
  10113. /**
  10114. * Handles the Player focus event.
  10115. *
  10116. * Calls for handling of the Player Focus if current element is focusable.
  10117. */
  10118. handlePlayerFocus_() {
  10119. if (this.getCurrentComponent() && this.getCurrentComponent().getIsFocusable()) {
  10120. this.resume();
  10121. }
  10122. }
  10123. /**
  10124. * Gets a set of focusable components.
  10125. *
  10126. * @return {Array}
  10127. * Returns an array of focusable components.
  10128. */
  10129. updateFocusableComponents() {
  10130. const player = this.player_;
  10131. const focusableComponents = [];
  10132. /**
  10133. * Searches for children candidates.
  10134. *
  10135. * Pushes Components to array of 'focusableComponents'.
  10136. * Calls itself if there is children elements inside iterated component.
  10137. *
  10138. * @param {Array} componentsArray - The array of components to search for focusable children.
  10139. */
  10140. function searchForChildrenCandidates(componentsArray) {
  10141. for (const i of componentsArray) {
  10142. if (i.hasOwnProperty('el_') && i.getIsFocusable() && i.getIsAvailableToBeFocused(i.el())) {
  10143. focusableComponents.push(i);
  10144. }
  10145. if (i.hasOwnProperty('children_') && i.children_.length > 0) {
  10146. searchForChildrenCandidates(i.children_);
  10147. }
  10148. }
  10149. }
  10150. // Iterate inside all children components of the player.
  10151. player.children_.forEach(value => {
  10152. if (value.hasOwnProperty('el_')) {
  10153. // If component has required functions 'getIsFocusable' & 'getIsAvailableToBeFocused', is focusable & available to be focused.
  10154. if (value.getIsFocusable && value.getIsAvailableToBeFocused && value.getIsFocusable() && value.getIsAvailableToBeFocused(value.el())) {
  10155. focusableComponents.push(value);
  10156. return;
  10157. // If component has posible children components as candidates.
  10158. } else if (value.hasOwnProperty('children_') && value.children_.length > 0) {
  10159. searchForChildrenCandidates(value.children_);
  10160. // If component has posible item components as candidates.
  10161. } else if (value.hasOwnProperty('items') && value.items.length > 0) {
  10162. searchForChildrenCandidates(value.items);
  10163. // If there is a suitable child element within the component's DOM element.
  10164. } else if (this.findSuitableDOMChild(value)) {
  10165. focusableComponents.push(value);
  10166. }
  10167. }
  10168. // TODO - Refactor the following logic after refactor of videojs-errors elements to be components is done.
  10169. if (value.name_ === 'ErrorDisplay' && value.opened_) {
  10170. const buttonContainer = value.el_.querySelector('.vjs-errors-ok-button-container');
  10171. if (buttonContainer) {
  10172. const modalButtons = buttonContainer.querySelectorAll('button');
  10173. modalButtons.forEach((element, index) => {
  10174. // Add elements as objects to be handled by the spatial navigation
  10175. focusableComponents.push({
  10176. name: () => {
  10177. return 'ModalButton' + (index + 1);
  10178. },
  10179. el: () => element,
  10180. getPositions: () => {
  10181. const rect = element.getBoundingClientRect();
  10182. // Creating objects that mirror DOMRectReadOnly for boundingClientRect and center
  10183. const boundingClientRect = {
  10184. x: rect.x,
  10185. y: rect.y,
  10186. width: rect.width,
  10187. height: rect.height,
  10188. top: rect.top,
  10189. right: rect.right,
  10190. bottom: rect.bottom,
  10191. left: rect.left
  10192. };
  10193. // Calculating the center position
  10194. const center = {
  10195. x: rect.left + rect.width / 2,
  10196. y: rect.top + rect.height / 2,
  10197. width: 0,
  10198. height: 0,
  10199. top: rect.top + rect.height / 2,
  10200. right: rect.left + rect.width / 2,
  10201. bottom: rect.top + rect.height / 2,
  10202. left: rect.left + rect.width / 2
  10203. };
  10204. return {
  10205. boundingClientRect,
  10206. center
  10207. };
  10208. },
  10209. // Asume that the following are always focusable
  10210. getIsAvailableToBeFocused: () => true,
  10211. getIsFocusable: el => true,
  10212. focus: () => element.focus()
  10213. });
  10214. });
  10215. }
  10216. }
  10217. });
  10218. this.focusableComponents = focusableComponents;
  10219. return this.focusableComponents;
  10220. }
  10221. /**
  10222. * Finds a suitable child element within the provided component's DOM element.
  10223. *
  10224. * @param {Object} component - The component containing the DOM element to search within.
  10225. * @return {HTMLElement|null} Returns the suitable child element if found, or null if not found.
  10226. */
  10227. findSuitableDOMChild(component) {
  10228. /**
  10229. * Recursively searches for a suitable child node that can be focused within a given component.
  10230. * It first checks if the provided node itself can be focused according to the component's
  10231. * `getIsFocusable` and `getIsAvailableToBeFocused` methods. If not, it recursively searches
  10232. * through the node's children to find a suitable child node that meets the focusability criteria.
  10233. *
  10234. * @param {HTMLElement} node - The DOM node to start the search from.
  10235. * @return {HTMLElement|null} The first child node that is focusable and available to be focused,
  10236. * or `null` if no suitable child is found.
  10237. */
  10238. function searchForSuitableChild(node) {
  10239. if (component.getIsFocusable(node) && component.getIsAvailableToBeFocused(node)) {
  10240. return node;
  10241. }
  10242. for (let i = 0; i < node.children.length; i++) {
  10243. const child = node.children[i];
  10244. const suitableChild = searchForSuitableChild(child);
  10245. if (suitableChild) {
  10246. return suitableChild;
  10247. }
  10248. }
  10249. return null;
  10250. }
  10251. if (component.el()) {
  10252. return searchForSuitableChild(component.el());
  10253. }
  10254. return null;
  10255. }
  10256. /**
  10257. * Gets the currently focused component from the list of focusable components.
  10258. * If a target element is provided, it uses that element to find the corresponding
  10259. * component. If no target is provided, it defaults to using the document's currently
  10260. * active element.
  10261. *
  10262. * @param {HTMLElement} [target] - The DOM element to check against the focusable components.
  10263. * If not provided, `document.activeElement` is used.
  10264. * @return {Component|null} - Returns the focused component if found among the focusable components,
  10265. * otherwise returns null if no matching component is found.
  10266. */
  10267. getCurrentComponent(target) {
  10268. this.updateFocusableComponents();
  10269. // eslint-disable-next-line
  10270. const curComp = target || document.activeElement;
  10271. if (this.focusableComponents.length) {
  10272. for (const i of this.focusableComponents) {
  10273. // If component Node is equal to the current active element.
  10274. if (i.el() === curComp) {
  10275. return i;
  10276. }
  10277. }
  10278. }
  10279. }
  10280. /**
  10281. * Adds a component to the array of focusable components.
  10282. *
  10283. * @param {Component} component
  10284. * The `Component` to be added.
  10285. */
  10286. add(component) {
  10287. const focusableComponents = [...this.focusableComponents];
  10288. if (component.hasOwnProperty('el_') && component.getIsFocusable() && component.getIsAvailableToBeFocused(component.el())) {
  10289. focusableComponents.push(component);
  10290. }
  10291. this.focusableComponents = focusableComponents;
  10292. // Trigger the notification manually
  10293. this.trigger({
  10294. type: 'focusableComponentsChanged',
  10295. focusableComponents: this.focusableComponents
  10296. });
  10297. }
  10298. /**
  10299. * Removes component from the array of focusable components.
  10300. *
  10301. * @param {Component} component - The component to be removed from the focusable components array.
  10302. */
  10303. remove(component) {
  10304. for (let i = 0; i < this.focusableComponents.length; i++) {
  10305. if (this.focusableComponents[i].name() === component.name()) {
  10306. this.focusableComponents.splice(i, 1);
  10307. // Trigger the notification manually
  10308. this.trigger({
  10309. type: 'focusableComponentsChanged',
  10310. focusableComponents: this.focusableComponents
  10311. });
  10312. return;
  10313. }
  10314. }
  10315. }
  10316. /**
  10317. * Clears array of focusable components.
  10318. */
  10319. clear() {
  10320. // Check if the array is already empty to avoid unnecessary event triggering
  10321. if (this.focusableComponents.length > 0) {
  10322. // Clear the array
  10323. this.focusableComponents = [];
  10324. // Trigger the notification manually
  10325. this.trigger({
  10326. type: 'focusableComponentsChanged',
  10327. focusableComponents: this.focusableComponents
  10328. });
  10329. }
  10330. }
  10331. /**
  10332. * Navigates to the next focusable component based on the specified direction.
  10333. *
  10334. * @param {string} direction 'up', 'down', 'left', 'right'
  10335. */
  10336. move(direction) {
  10337. const currentFocusedComponent = this.getCurrentComponent();
  10338. if (!currentFocusedComponent) {
  10339. return;
  10340. }
  10341. const currentPositions = currentFocusedComponent.getPositions();
  10342. const candidates = this.focusableComponents.filter(component => component !== currentFocusedComponent && this.isInDirection_(currentPositions.boundingClientRect, component.getPositions().boundingClientRect, direction));
  10343. const bestCandidate = this.findBestCandidate_(currentPositions.center, candidates, direction);
  10344. if (bestCandidate) {
  10345. this.focus(bestCandidate);
  10346. } else {
  10347. this.trigger({
  10348. type: 'endOfFocusableComponents',
  10349. direction,
  10350. focusedComponent: currentFocusedComponent
  10351. });
  10352. }
  10353. }
  10354. /**
  10355. * Finds the best candidate on the current center position,
  10356. * the list of candidates, and the specified navigation direction.
  10357. *
  10358. * @param {Object} currentCenter The center position of the current focused component element.
  10359. * @param {Array} candidates An array of candidate components to receive focus.
  10360. * @param {string} direction The direction of navigation ('up', 'down', 'left', 'right').
  10361. * @return {Object|null} The component that is the best candidate for receiving focus.
  10362. */
  10363. findBestCandidate_(currentCenter, candidates, direction) {
  10364. let minDistance = Infinity;
  10365. let bestCandidate = null;
  10366. for (const candidate of candidates) {
  10367. const candidateCenter = candidate.getPositions().center;
  10368. const distance = this.calculateDistance_(currentCenter, candidateCenter, direction);
  10369. if (distance < minDistance) {
  10370. minDistance = distance;
  10371. bestCandidate = candidate;
  10372. }
  10373. }
  10374. return bestCandidate;
  10375. }
  10376. /**
  10377. * Determines if a target rectangle is in the specified navigation direction
  10378. * relative to a source rectangle.
  10379. *
  10380. * @param {Object} srcRect The bounding rectangle of the source element.
  10381. * @param {Object} targetRect The bounding rectangle of the target element.
  10382. * @param {string} direction The navigation direction ('up', 'down', 'left', 'right').
  10383. * @return {boolean} True if the target is in the specified direction relative to the source.
  10384. */
  10385. isInDirection_(srcRect, targetRect, direction) {
  10386. switch (direction) {
  10387. case 'right':
  10388. return targetRect.left >= srcRect.right;
  10389. case 'left':
  10390. return targetRect.right <= srcRect.left;
  10391. case 'down':
  10392. return targetRect.top >= srcRect.bottom;
  10393. case 'up':
  10394. return targetRect.bottom <= srcRect.top;
  10395. default:
  10396. return false;
  10397. }
  10398. }
  10399. /**
  10400. * Focus the last focused component saved before blur on player.
  10401. */
  10402. refocusComponent() {
  10403. if (this.lastFocusedComponent_) {
  10404. // If user is not active, set it to active.
  10405. if (!this.player_.userActive()) {
  10406. this.player_.userActive(true);
  10407. }
  10408. this.updateFocusableComponents();
  10409. // Search inside array of 'focusableComponents' for a match of name of
  10410. // the last focused component.
  10411. for (let i = 0; i < this.focusableComponents.length; i++) {
  10412. if (this.focusableComponents[i].name() === this.lastFocusedComponent_.name()) {
  10413. this.focus(this.focusableComponents[i]);
  10414. return;
  10415. }
  10416. }
  10417. } else {
  10418. this.focus(this.updateFocusableComponents()[0]);
  10419. }
  10420. }
  10421. /**
  10422. * Focuses on a given component.
  10423. * If the component is available to be focused, it focuses on the component.
  10424. * If not, it attempts to find a suitable DOM child within the component and focuses on it.
  10425. *
  10426. * @param {Component} component - The component to be focused.
  10427. */
  10428. focus(component) {
  10429. if (typeof component !== 'object') {
  10430. return;
  10431. }
  10432. if (component.getIsAvailableToBeFocused(component.el())) {
  10433. component.focus();
  10434. } else if (this.findSuitableDOMChild(component)) {
  10435. this.findSuitableDOMChild(component).focus();
  10436. }
  10437. }
  10438. /**
  10439. * Calculates the distance between two points, adjusting the calculation based on
  10440. * the specified navigation direction.
  10441. *
  10442. * @param {Object} center1 The center point of the first element.
  10443. * @param {Object} center2 The center point of the second element.
  10444. * @param {string} direction The direction of navigation ('up', 'down', 'left', 'right').
  10445. * @return {number} The calculated distance between the two centers.
  10446. */
  10447. calculateDistance_(center1, center2, direction) {
  10448. const dx = Math.abs(center1.x - center2.x);
  10449. const dy = Math.abs(center1.y - center2.y);
  10450. let distance;
  10451. switch (direction) {
  10452. case 'right':
  10453. case 'left':
  10454. // Higher weight for vertical distance in horizontal navigation.
  10455. distance = dx + dy * 100;
  10456. break;
  10457. case 'up':
  10458. // Strongly prioritize vertical proximity for UP navigation.
  10459. // Adjust the weight to ensure that elements directly above are favored.
  10460. distance = dy * 2 + dx * 0.5;
  10461. break;
  10462. case 'down':
  10463. // More balanced weight for vertical and horizontal distances.
  10464. // Adjust the weights here to find the best balance.
  10465. distance = dy * 5 + dx;
  10466. break;
  10467. default:
  10468. distance = dx + dy;
  10469. }
  10470. return distance;
  10471. }
  10472. /**
  10473. * This gets called by 'handlePlayerBlur_' if 'spatialNavigation' is enabled.
  10474. * Searches for the first 'TextTrackSelect' inside of modal to focus.
  10475. *
  10476. * @private
  10477. */
  10478. searchForTrackSelect_() {
  10479. const spatialNavigation = this;
  10480. for (const component of spatialNavigation.updateFocusableComponents()) {
  10481. if (component.constructor.name === 'TextTrackSelect') {
  10482. spatialNavigation.focus(component);
  10483. break;
  10484. }
  10485. }
  10486. }
  10487. }
  10488. /**
  10489. * @file loader.js
  10490. */
  10491. /** @import Player from '../player' */
  10492. /**
  10493. * The `MediaLoader` is the `Component` that decides which playback technology to load
  10494. * when a player is initialized.
  10495. *
  10496. * @extends Component
  10497. */
  10498. class MediaLoader extends Component {
  10499. /**
  10500. * Create an instance of this class.
  10501. *
  10502. * @param {Player} player
  10503. * The `Player` that this class should attach to.
  10504. *
  10505. * @param {Object} [options]
  10506. * The key/value store of player options.
  10507. *
  10508. * @param {Function} [ready]
  10509. * The function that is run when this component is ready.
  10510. */
  10511. constructor(player, options, ready) {
  10512. // MediaLoader has no element
  10513. const options_ = merge({
  10514. createEl: false
  10515. }, options);
  10516. super(player, options_, ready);
  10517. // If there are no sources when the player is initialized,
  10518. // load the first supported playback technology.
  10519. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  10520. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  10521. const techName = toTitleCase(j[i]);
  10522. let tech = Tech.getTech(techName);
  10523. // Support old behavior of techs being registered as components.
  10524. // Remove once that deprecated behavior is removed.
  10525. if (!techName) {
  10526. tech = Component.getComponent(techName);
  10527. }
  10528. // Check if the browser supports this technology
  10529. if (tech && tech.isSupported()) {
  10530. player.loadTech_(techName);
  10531. break;
  10532. }
  10533. }
  10534. } else {
  10535. // Loop through playback technologies (e.g. HTML5) and check for support.
  10536. // Then load the best source.
  10537. // A few assumptions here:
  10538. // All playback technologies respect preload false.
  10539. player.src(options.playerOptions.sources);
  10540. }
  10541. }
  10542. }
  10543. Component.registerComponent('MediaLoader', MediaLoader);
  10544. /**
  10545. * @file clickable-component.js
  10546. */
  10547. /** @import Player from './player' */
  10548. /**
  10549. * Component which is clickable or keyboard actionable, but is not a
  10550. * native HTML button.
  10551. *
  10552. * @extends Component
  10553. */
  10554. class ClickableComponent extends Component {
  10555. /**
  10556. * Creates an instance of this class.
  10557. *
  10558. * @param {Player} player
  10559. * The `Player` that this class should be attached to.
  10560. *
  10561. * @param {Object} [options]
  10562. * The key/value store of component options.
  10563. *
  10564. * @param {function} [options.clickHandler]
  10565. * The function to call when the button is clicked / activated
  10566. *
  10567. * @param {string} [options.controlText]
  10568. * The text to set on the button
  10569. *
  10570. * @param {string} [options.className]
  10571. * A class or space separated list of classes to add the component
  10572. *
  10573. */
  10574. constructor(player, options) {
  10575. super(player, options);
  10576. if (this.options_.controlText) {
  10577. this.controlText(this.options_.controlText);
  10578. }
  10579. this.handleMouseOver_ = e => this.handleMouseOver(e);
  10580. this.handleMouseOut_ = e => this.handleMouseOut(e);
  10581. this.handleClick_ = e => this.handleClick(e);
  10582. this.handleKeyDown_ = e => this.handleKeyDown(e);
  10583. this.emitTapEvents();
  10584. this.enable();
  10585. }
  10586. /**
  10587. * Create the `ClickableComponent`s DOM element.
  10588. *
  10589. * @param {string} [tag=div]
  10590. * The element's node type.
  10591. *
  10592. * @param {Object} [props={}]
  10593. * An object of properties that should be set on the element.
  10594. *
  10595. * @param {Object} [attributes={}]
  10596. * An object of attributes that should be set on the element.
  10597. *
  10598. * @return {Element}
  10599. * The element that gets created.
  10600. */
  10601. createEl(tag = 'div', props = {}, attributes = {}) {
  10602. props = Object.assign({
  10603. className: this.buildCSSClass(),
  10604. tabIndex: 0
  10605. }, props);
  10606. if (tag === 'button') {
  10607. log.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  10608. }
  10609. // Add ARIA attributes for clickable element which is not a native HTML button
  10610. attributes = Object.assign({
  10611. role: 'button'
  10612. }, attributes);
  10613. this.tabIndex_ = props.tabIndex;
  10614. const el = createEl(tag, props, attributes);
  10615. if (!this.player_.options_.experimentalSvgIcons) {
  10616. el.appendChild(createEl('span', {
  10617. className: 'vjs-icon-placeholder'
  10618. }, {
  10619. 'aria-hidden': true
  10620. }));
  10621. }
  10622. this.createControlTextEl(el);
  10623. return el;
  10624. }
  10625. dispose() {
  10626. // remove controlTextEl_ on dispose
  10627. this.controlTextEl_ = null;
  10628. super.dispose();
  10629. }
  10630. /**
  10631. * Create a control text element on this `ClickableComponent`
  10632. *
  10633. * @param {Element} [el]
  10634. * Parent element for the control text.
  10635. *
  10636. * @return {Element}
  10637. * The control text element that gets created.
  10638. */
  10639. createControlTextEl(el) {
  10640. this.controlTextEl_ = createEl('span', {
  10641. className: 'vjs-control-text'
  10642. }, {
  10643. // let the screen reader user know that the text of the element may change
  10644. 'aria-live': 'polite'
  10645. });
  10646. if (el) {
  10647. el.appendChild(this.controlTextEl_);
  10648. }
  10649. this.controlText(this.controlText_, el);
  10650. return this.controlTextEl_;
  10651. }
  10652. /**
  10653. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  10654. *
  10655. * @param {string} [text]
  10656. * Control text for element.
  10657. *
  10658. * @param {Element} [el=this.el()]
  10659. * Element to set the title on.
  10660. *
  10661. * @return {string}
  10662. * - The control text when getting
  10663. */
  10664. controlText(text, el = this.el()) {
  10665. if (text === undefined) {
  10666. return this.controlText_ || 'Need Text';
  10667. }
  10668. const localizedText = this.localize(text);
  10669. /** @protected */
  10670. this.controlText_ = text;
  10671. textContent(this.controlTextEl_, localizedText);
  10672. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  10673. // Set title attribute if only an icon is shown
  10674. el.setAttribute('title', localizedText);
  10675. }
  10676. }
  10677. /**
  10678. * Builds the default DOM `className`.
  10679. *
  10680. * @return {string}
  10681. * The DOM `className` for this object.
  10682. */
  10683. buildCSSClass() {
  10684. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  10685. }
  10686. /**
  10687. * Enable this `ClickableComponent`
  10688. */
  10689. enable() {
  10690. if (!this.enabled_) {
  10691. this.enabled_ = true;
  10692. this.removeClass('vjs-disabled');
  10693. this.el_.setAttribute('aria-disabled', 'false');
  10694. if (typeof this.tabIndex_ !== 'undefined') {
  10695. this.el_.setAttribute('tabIndex', this.tabIndex_);
  10696. }
  10697. this.on(['tap', 'click'], this.handleClick_);
  10698. this.on('keydown', this.handleKeyDown_);
  10699. }
  10700. }
  10701. /**
  10702. * Disable this `ClickableComponent`
  10703. */
  10704. disable() {
  10705. this.enabled_ = false;
  10706. this.addClass('vjs-disabled');
  10707. this.el_.setAttribute('aria-disabled', 'true');
  10708. if (typeof this.tabIndex_ !== 'undefined') {
  10709. this.el_.removeAttribute('tabIndex');
  10710. }
  10711. this.off('mouseover', this.handleMouseOver_);
  10712. this.off('mouseout', this.handleMouseOut_);
  10713. this.off(['tap', 'click'], this.handleClick_);
  10714. this.off('keydown', this.handleKeyDown_);
  10715. }
  10716. /**
  10717. * Handles language change in ClickableComponent for the player in components
  10718. *
  10719. *
  10720. */
  10721. handleLanguagechange() {
  10722. this.controlText(this.controlText_);
  10723. }
  10724. /**
  10725. * Event handler that is called when a `ClickableComponent` receives a
  10726. * `click` or `tap` event.
  10727. *
  10728. * @param {Event} event
  10729. * The `tap` or `click` event that caused this function to be called.
  10730. *
  10731. * @listens tap
  10732. * @listens click
  10733. * @abstract
  10734. */
  10735. handleClick(event) {
  10736. if (this.options_.clickHandler) {
  10737. this.options_.clickHandler.call(this, arguments);
  10738. }
  10739. }
  10740. /**
  10741. * Event handler that is called when a `ClickableComponent` receives a
  10742. * `keydown` event.
  10743. *
  10744. * By default, if the key is Space or Enter, it will trigger a `click` event.
  10745. *
  10746. * @param {KeyboardEvent} event
  10747. * The `keydown` event that caused this function to be called.
  10748. *
  10749. * @listens keydown
  10750. */
  10751. handleKeyDown(event) {
  10752. // Support Space or Enter key operation to fire a click event. Also,
  10753. // prevent the event from propagating through the DOM and triggering
  10754. // Player hotkeys.
  10755. if (event.key === ' ' || event.key === 'Enter') {
  10756. event.preventDefault();
  10757. event.stopPropagation();
  10758. this.trigger('click');
  10759. } else {
  10760. // Pass keypress handling up for unsupported keys
  10761. super.handleKeyDown(event);
  10762. }
  10763. }
  10764. }
  10765. Component.registerComponent('ClickableComponent', ClickableComponent);
  10766. /**
  10767. * @file poster-image.js
  10768. */
  10769. /** @import Player from './player' */
  10770. /**
  10771. * A `ClickableComponent` that handles showing the poster image for the player.
  10772. *
  10773. * @extends ClickableComponent
  10774. */
  10775. class PosterImage extends ClickableComponent {
  10776. /**
  10777. * Create an instance of this class.
  10778. *
  10779. * @param {Player} player
  10780. * The `Player` that this class should attach to.
  10781. *
  10782. * @param {Object} [options]
  10783. * The key/value store of player options.
  10784. */
  10785. constructor(player, options) {
  10786. super(player, options);
  10787. this.update();
  10788. this.update_ = e => this.update(e);
  10789. player.on('posterchange', this.update_);
  10790. }
  10791. /**
  10792. * Clean up and dispose of the `PosterImage`.
  10793. */
  10794. dispose() {
  10795. this.player().off('posterchange', this.update_);
  10796. super.dispose();
  10797. }
  10798. /**
  10799. * Create the `PosterImage`s DOM element.
  10800. *
  10801. * @return {Element}
  10802. * The element that gets created.
  10803. */
  10804. createEl() {
  10805. // The el is an empty div to keep position in the DOM
  10806. // A picture and img el will be inserted when a source is set
  10807. return createEl('div', {
  10808. className: 'vjs-poster'
  10809. });
  10810. }
  10811. /**
  10812. * Get or set the `PosterImage`'s crossOrigin option.
  10813. *
  10814. * @param {string|null} [value]
  10815. * The value to set the crossOrigin to. If an argument is
  10816. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  10817. *
  10818. * @return {string|null}
  10819. * - The current crossOrigin value of the `Player` when getting.
  10820. * - undefined when setting
  10821. */
  10822. crossOrigin(value) {
  10823. // `null` can be set to unset a value
  10824. if (typeof value === 'undefined') {
  10825. if (this.$('img')) {
  10826. // If the poster's element exists, give its value
  10827. return this.$('img').crossOrigin;
  10828. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  10829. // If not but the tech is ready, query the tech
  10830. return this.player_.crossOrigin();
  10831. }
  10832. // Otherwise check options as the poster is usually set before the state of crossorigin
  10833. // can be retrieved by the getter
  10834. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  10835. }
  10836. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  10837. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  10838. return;
  10839. }
  10840. if (this.$('img')) {
  10841. this.$('img').crossOrigin = value;
  10842. }
  10843. return;
  10844. }
  10845. /**
  10846. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  10847. *
  10848. * @listens Player#posterchange
  10849. *
  10850. * @param {Event} [event]
  10851. * The `Player#posterchange` event that triggered this function.
  10852. */
  10853. update(event) {
  10854. const url = this.player().poster();
  10855. this.setSrc(url);
  10856. // If there's no poster source we should display:none on this component
  10857. // so it's not still clickable or right-clickable
  10858. if (url) {
  10859. this.show();
  10860. } else {
  10861. this.hide();
  10862. }
  10863. }
  10864. /**
  10865. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  10866. * the inner picture and img elementss when needed.
  10867. *
  10868. * @param {string} [url]
  10869. * The URL to the source for the `PosterImage`. If not specified or falsy,
  10870. * any source and ant inner picture/img are removed.
  10871. */
  10872. setSrc(url) {
  10873. if (!url) {
  10874. this.el_.textContent = '';
  10875. return;
  10876. }
  10877. if (!this.$('img')) {
  10878. this.el_.appendChild(createEl('picture', {
  10879. className: 'vjs-poster',
  10880. // Don't want poster to be tabbable.
  10881. tabIndex: -1
  10882. }, {}, createEl('img', {
  10883. loading: 'lazy',
  10884. crossOrigin: this.crossOrigin()
  10885. }, {
  10886. alt: ''
  10887. })));
  10888. }
  10889. this.$('img').src = url;
  10890. }
  10891. /**
  10892. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  10893. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  10894. *
  10895. * @listens tap
  10896. * @listens click
  10897. * @listens keydown
  10898. *
  10899. * @param {Event} event
  10900. + The `click`, `tap` or `keydown` event that caused this function to be called.
  10901. */
  10902. handleClick(event) {
  10903. // We don't want a click to trigger playback when controls are disabled
  10904. if (!this.player_.controls()) {
  10905. return;
  10906. }
  10907. if (this.player_.tech(true)) {
  10908. this.player_.tech(true).focus();
  10909. }
  10910. if (this.player_.paused()) {
  10911. silencePromise(this.player_.play());
  10912. } else {
  10913. this.player_.pause();
  10914. }
  10915. }
  10916. }
  10917. /**
  10918. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  10919. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  10920. * behavior.
  10921. *
  10922. * @param {string|null} [value]
  10923. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  10924. * given, must be one of `anonymous` or `use-credentials`.
  10925. *
  10926. * @return {string|null|undefined}
  10927. * - The current crossorigin value of the `Player` when getting.
  10928. * - undefined when setting
  10929. */
  10930. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  10931. Component.registerComponent('PosterImage', PosterImage);
  10932. /**
  10933. * @file text-track-display.js
  10934. */
  10935. /** @import Player from '../player' */
  10936. const darkGray = '#222';
  10937. const lightGray = '#ccc';
  10938. const fontMap = {
  10939. monospace: 'monospace',
  10940. sansSerif: 'sans-serif',
  10941. serif: 'serif',
  10942. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  10943. monospaceSerif: '"Courier New", monospace',
  10944. proportionalSansSerif: 'sans-serif',
  10945. proportionalSerif: 'serif',
  10946. casual: '"Comic Sans MS", Impact, fantasy',
  10947. script: '"Monotype Corsiva", cursive',
  10948. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  10949. };
  10950. /**
  10951. * Construct an rgba color from a given hex color code.
  10952. *
  10953. * @param {number} color
  10954. * Hex number for color, like #f0e or #f604e2.
  10955. *
  10956. * @param {number} opacity
  10957. * Value for opacity, 0.0 - 1.0.
  10958. *
  10959. * @return {string}
  10960. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  10961. */
  10962. function constructColor(color, opacity) {
  10963. let hex;
  10964. if (color.length === 4) {
  10965. // color looks like "#f0e"
  10966. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  10967. } else if (color.length === 7) {
  10968. // color looks like "#f604e2"
  10969. hex = color.slice(1);
  10970. } else {
  10971. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  10972. }
  10973. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  10974. }
  10975. /**
  10976. * Try to update the style of a DOM element. Some style changes will throw an error,
  10977. * particularly in IE8. Those should be noops.
  10978. *
  10979. * @param {Element} el
  10980. * The DOM element to be styled.
  10981. *
  10982. * @param {string} style
  10983. * The CSS property on the element that should be styled.
  10984. *
  10985. * @param {string} rule
  10986. * The style rule that should be applied to the property.
  10987. *
  10988. * @private
  10989. */
  10990. function tryUpdateStyle(el, style, rule) {
  10991. try {
  10992. el.style[style] = rule;
  10993. } catch (e) {
  10994. // Satisfies linter.
  10995. return;
  10996. }
  10997. }
  10998. /**
  10999. * Converts the CSS top/right/bottom/left property numeric value to string in pixels.
  11000. *
  11001. * @param {number} position
  11002. * The CSS top/right/bottom/left property value.
  11003. *
  11004. * @return {string}
  11005. * The CSS property value that was created, like '10px'.
  11006. *
  11007. * @private
  11008. */
  11009. function getCSSPositionValue(position) {
  11010. return position ? `${position}px` : '';
  11011. }
  11012. /**
  11013. * The component for displaying text track cues.
  11014. *
  11015. * @extends Component
  11016. */
  11017. class TextTrackDisplay extends Component {
  11018. /**
  11019. * Creates an instance of this class.
  11020. *
  11021. * @param {Player} player
  11022. * The `Player` that this class should be attached to.
  11023. *
  11024. * @param {Object} [options]
  11025. * The key/value store of player options.
  11026. *
  11027. * @param {Function} [ready]
  11028. * The function to call when `TextTrackDisplay` is ready.
  11029. */
  11030. constructor(player, options, ready) {
  11031. super(player, options, ready);
  11032. const updateDisplayTextHandler = e => this.updateDisplay(e);
  11033. const updateDisplayHandler = e => {
  11034. this.updateDisplayOverlay();
  11035. this.updateDisplay(e);
  11036. };
  11037. player.on('loadstart', e => this.toggleDisplay(e));
  11038. player.on('texttrackchange', updateDisplayTextHandler);
  11039. player.on('loadedmetadata', e => {
  11040. this.updateDisplayOverlay();
  11041. this.preselectTrack(e);
  11042. });
  11043. // This used to be called during player init, but was causing an error
  11044. // if a track should show by default and the display hadn't loaded yet.
  11045. // Should probably be moved to an external track loader when we support
  11046. // tracks that don't need a display.
  11047. player.ready(bind_(this, function () {
  11048. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  11049. this.hide();
  11050. return;
  11051. }
  11052. player.on('fullscreenchange', updateDisplayHandler);
  11053. player.on('playerresize', updateDisplayHandler);
  11054. const screenOrientation = window.screen.orientation || window;
  11055. const changeOrientationEvent = window.screen.orientation ? 'change' : 'orientationchange';
  11056. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  11057. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  11058. const tracks = this.options_.playerOptions.tracks || [];
  11059. for (let i = 0; i < tracks.length; i++) {
  11060. this.player_.addRemoteTextTrack(tracks[i], true);
  11061. }
  11062. this.preselectTrack();
  11063. }));
  11064. }
  11065. /**
  11066. * Preselect a track following this precedence:
  11067. * - matches the previously selected {@link TextTrack}'s language and kind
  11068. * - matches the previously selected {@link TextTrack}'s language only
  11069. * - is the first default captions track
  11070. * - is the first default descriptions track
  11071. *
  11072. * @listens Player#loadstart
  11073. */
  11074. preselectTrack() {
  11075. const modes = {
  11076. captions: 1,
  11077. subtitles: 1
  11078. };
  11079. const trackList = this.player_.textTracks();
  11080. const userPref = this.player_.cache_.selectedLanguage;
  11081. let firstDesc;
  11082. let firstCaptions;
  11083. let preferredTrack;
  11084. for (let i = 0; i < trackList.length; i++) {
  11085. const track = trackList[i];
  11086. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  11087. // Always choose the track that matches both language and kind
  11088. if (track.kind === userPref.kind) {
  11089. preferredTrack = track;
  11090. // or choose the first track that matches language
  11091. } else if (!preferredTrack) {
  11092. preferredTrack = track;
  11093. }
  11094. // clear everything if offTextTrackMenuItem was clicked
  11095. } else if (userPref && !userPref.enabled) {
  11096. preferredTrack = null;
  11097. firstDesc = null;
  11098. firstCaptions = null;
  11099. } else if (track.default) {
  11100. if (track.kind === 'descriptions' && !firstDesc) {
  11101. firstDesc = track;
  11102. } else if (track.kind in modes && !firstCaptions) {
  11103. firstCaptions = track;
  11104. }
  11105. }
  11106. }
  11107. // The preferredTrack matches the user preference and takes
  11108. // precedence over all the other tracks.
  11109. // So, display the preferredTrack before the first default track
  11110. // and the subtitles/captions track before the descriptions track
  11111. if (preferredTrack) {
  11112. preferredTrack.mode = 'showing';
  11113. } else if (firstCaptions) {
  11114. firstCaptions.mode = 'showing';
  11115. } else if (firstDesc) {
  11116. firstDesc.mode = 'showing';
  11117. }
  11118. }
  11119. /**
  11120. * Turn display of {@link TextTrack}'s from the current state into the other state.
  11121. * There are only two states:
  11122. * - 'shown'
  11123. * - 'hidden'
  11124. *
  11125. * @listens Player#loadstart
  11126. */
  11127. toggleDisplay() {
  11128. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  11129. this.hide();
  11130. } else {
  11131. this.show();
  11132. }
  11133. }
  11134. /**
  11135. * Create the {@link Component}'s DOM element.
  11136. *
  11137. * @return {Element}
  11138. * The element that was created.
  11139. */
  11140. createEl() {
  11141. return super.createEl('div', {
  11142. className: 'vjs-text-track-display'
  11143. }, {
  11144. 'translate': 'yes',
  11145. 'aria-live': 'off',
  11146. 'aria-atomic': 'true'
  11147. });
  11148. }
  11149. /**
  11150. * Clear all displayed {@link TextTrack}s.
  11151. */
  11152. clearDisplay() {
  11153. if (typeof window.WebVTT === 'function') {
  11154. window.WebVTT.processCues(window, [], this.el_);
  11155. }
  11156. }
  11157. /**
  11158. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  11159. * a {@link Player#fullscreenchange} is fired.
  11160. *
  11161. * @listens Player#texttrackchange
  11162. * @listens Player#fullscreenchange
  11163. */
  11164. updateDisplay() {
  11165. const tracks = this.player_.textTracks();
  11166. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  11167. this.clearDisplay();
  11168. if (allowMultipleShowingTracks) {
  11169. const showingTracks = [];
  11170. for (let i = 0; i < tracks.length; ++i) {
  11171. const track = tracks[i];
  11172. if (track.mode !== 'showing') {
  11173. continue;
  11174. }
  11175. showingTracks.push(track);
  11176. }
  11177. this.updateForTrack(showingTracks);
  11178. return;
  11179. }
  11180. // Track display prioritization model: if multiple tracks are 'showing',
  11181. // display the first 'subtitles' or 'captions' track which is 'showing',
  11182. // otherwise display the first 'descriptions' track which is 'showing'
  11183. let descriptionsTrack = null;
  11184. let captionsSubtitlesTrack = null;
  11185. let i = tracks.length;
  11186. while (i--) {
  11187. const track = tracks[i];
  11188. if (track.mode === 'showing') {
  11189. if (track.kind === 'descriptions') {
  11190. descriptionsTrack = track;
  11191. } else {
  11192. captionsSubtitlesTrack = track;
  11193. }
  11194. }
  11195. }
  11196. if (captionsSubtitlesTrack) {
  11197. if (this.getAttribute('aria-live') !== 'off') {
  11198. this.setAttribute('aria-live', 'off');
  11199. }
  11200. this.updateForTrack(captionsSubtitlesTrack);
  11201. } else if (descriptionsTrack) {
  11202. if (this.getAttribute('aria-live') !== 'assertive') {
  11203. this.setAttribute('aria-live', 'assertive');
  11204. }
  11205. this.updateForTrack(descriptionsTrack);
  11206. }
  11207. if (!window.CSS.supports('inset', '10px')) {
  11208. const textTrackDisplay = this.el_;
  11209. const vjsTextTrackCues = textTrackDisplay.querySelectorAll('.vjs-text-track-cue');
  11210. const controlBarHeight = this.player_.controlBar.el_.getBoundingClientRect().height;
  11211. const playerHeight = this.player_.el_.getBoundingClientRect().height;
  11212. // Clear inline style before getting actual height of textTrackDisplay
  11213. textTrackDisplay.style = '';
  11214. // textrack style updates, this styles are required to be inline
  11215. tryUpdateStyle(textTrackDisplay, 'position', 'relative');
  11216. tryUpdateStyle(textTrackDisplay, 'height', playerHeight - controlBarHeight + 'px');
  11217. tryUpdateStyle(textTrackDisplay, 'top', 'unset');
  11218. if (IS_SMART_TV) {
  11219. tryUpdateStyle(textTrackDisplay, 'bottom', playerHeight + 'px');
  11220. } else {
  11221. tryUpdateStyle(textTrackDisplay, 'bottom', '0px');
  11222. }
  11223. // vjsTextTrackCue style updates
  11224. if (vjsTextTrackCues.length > 0) {
  11225. vjsTextTrackCues.forEach(vjsTextTrackCue => {
  11226. // verify if inset styles are inline
  11227. if (vjsTextTrackCue.style.inset) {
  11228. const insetStyles = vjsTextTrackCue.style.inset.split(' ');
  11229. // expected value is always 3
  11230. if (insetStyles.length === 3) {
  11231. Object.assign(vjsTextTrackCue.style, {
  11232. top: insetStyles[0],
  11233. right: insetStyles[1],
  11234. bottom: insetStyles[2],
  11235. left: 'unset'
  11236. });
  11237. }
  11238. }
  11239. });
  11240. }
  11241. }
  11242. }
  11243. /**
  11244. * Updates the displayed TextTrack to be sure it overlays the video when a either
  11245. * a {@link Player#texttrackchange} or a {@link Player#fullscreenchange} is fired.
  11246. */
  11247. updateDisplayOverlay() {
  11248. // inset-inline and inset-block are not supprted on old chrome, but these are
  11249. // only likely to be used on TV devices
  11250. if (!this.player_.videoHeight() || !window.CSS.supports('inset-inline: 10px')) {
  11251. return;
  11252. }
  11253. const playerWidth = this.player_.currentWidth();
  11254. const playerHeight = this.player_.currentHeight();
  11255. const playerAspectRatio = playerWidth / playerHeight;
  11256. const videoAspectRatio = this.player_.videoWidth() / this.player_.videoHeight();
  11257. let insetInlineMatch = 0;
  11258. let insetBlockMatch = 0;
  11259. if (Math.abs(playerAspectRatio - videoAspectRatio) > 0.1) {
  11260. if (playerAspectRatio > videoAspectRatio) {
  11261. insetInlineMatch = Math.round((playerWidth - playerHeight * videoAspectRatio) / 2);
  11262. } else {
  11263. insetBlockMatch = Math.round((playerHeight - playerWidth / videoAspectRatio) / 2);
  11264. }
  11265. }
  11266. tryUpdateStyle(this.el_, 'insetInline', getCSSPositionValue(insetInlineMatch));
  11267. tryUpdateStyle(this.el_, 'insetBlock', getCSSPositionValue(insetBlockMatch));
  11268. }
  11269. /**
  11270. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  11271. *
  11272. * @param {TextTrack} track
  11273. * Text track object containing active cues to style.
  11274. */
  11275. updateDisplayState(track) {
  11276. const overrides = this.player_.textTrackSettings.getValues();
  11277. const cues = track.activeCues;
  11278. let i = cues.length;
  11279. while (i--) {
  11280. const cue = cues[i];
  11281. if (!cue) {
  11282. continue;
  11283. }
  11284. const cueDiv = cue.displayState;
  11285. if (overrides.color) {
  11286. cueDiv.firstChild.style.color = overrides.color;
  11287. }
  11288. if (overrides.textOpacity) {
  11289. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  11290. }
  11291. if (overrides.backgroundColor) {
  11292. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  11293. }
  11294. if (overrides.backgroundOpacity) {
  11295. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  11296. }
  11297. if (overrides.windowColor) {
  11298. if (overrides.windowOpacity) {
  11299. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  11300. } else {
  11301. cueDiv.style.backgroundColor = overrides.windowColor;
  11302. }
  11303. }
  11304. if (overrides.edgeStyle) {
  11305. if (overrides.edgeStyle === 'dropshadow') {
  11306. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  11307. } else if (overrides.edgeStyle === 'raised') {
  11308. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  11309. } else if (overrides.edgeStyle === 'depressed') {
  11310. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  11311. } else if (overrides.edgeStyle === 'uniform') {
  11312. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  11313. }
  11314. }
  11315. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  11316. const fontSize = window.parseFloat(cueDiv.style.fontSize);
  11317. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  11318. cueDiv.style.height = 'auto';
  11319. cueDiv.style.top = 'auto';
  11320. }
  11321. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  11322. if (overrides.fontFamily === 'small-caps') {
  11323. cueDiv.firstChild.style.fontVariant = 'small-caps';
  11324. } else {
  11325. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  11326. }
  11327. }
  11328. }
  11329. }
  11330. /**
  11331. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  11332. *
  11333. * @param {TextTrack|TextTrack[]} tracks
  11334. * Text track object or text track array to be added to the list.
  11335. */
  11336. updateForTrack(tracks) {
  11337. if (!Array.isArray(tracks)) {
  11338. tracks = [tracks];
  11339. }
  11340. if (typeof window.WebVTT !== 'function' || tracks.every(track => {
  11341. return !track.activeCues;
  11342. })) {
  11343. return;
  11344. }
  11345. const cues = [];
  11346. // push all active track cues
  11347. for (let i = 0; i < tracks.length; ++i) {
  11348. const track = tracks[i];
  11349. for (let j = 0; j < track.activeCues.length; ++j) {
  11350. cues.push(track.activeCues[j]);
  11351. }
  11352. }
  11353. // removes all cues before it processes new ones
  11354. window.WebVTT.processCues(window, cues, this.el_);
  11355. // add unique class to each language text track & add settings styling if necessary
  11356. for (let i = 0; i < tracks.length; ++i) {
  11357. const track = tracks[i];
  11358. for (let j = 0; j < track.activeCues.length; ++j) {
  11359. const cueEl = track.activeCues[j].displayState;
  11360. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  11361. if (track.language) {
  11362. setAttribute(cueEl, 'lang', track.language);
  11363. }
  11364. }
  11365. if (this.player_.textTrackSettings) {
  11366. this.updateDisplayState(track);
  11367. }
  11368. }
  11369. }
  11370. }
  11371. Component.registerComponent('TextTrackDisplay', TextTrackDisplay);
  11372. /**
  11373. * @file loading-spinner.js
  11374. */
  11375. /**
  11376. * A loading spinner for use during waiting/loading events.
  11377. *
  11378. * @extends Component
  11379. */
  11380. class LoadingSpinner extends Component {
  11381. /**
  11382. * Create the `LoadingSpinner`s DOM element.
  11383. *
  11384. * @return {Element}
  11385. * The dom element that gets created.
  11386. */
  11387. createEl() {
  11388. const isAudio = this.player_.isAudio();
  11389. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  11390. const controlText = createEl('span', {
  11391. className: 'vjs-control-text',
  11392. textContent: this.localize('{1} is loading.', [playerType])
  11393. });
  11394. const el = super.createEl('div', {
  11395. className: 'vjs-loading-spinner',
  11396. dir: 'ltr'
  11397. });
  11398. el.appendChild(controlText);
  11399. return el;
  11400. }
  11401. /**
  11402. * Update control text on languagechange
  11403. */
  11404. handleLanguagechange() {
  11405. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  11406. }
  11407. }
  11408. Component.registerComponent('LoadingSpinner', LoadingSpinner);
  11409. /**
  11410. * @file button.js
  11411. */
  11412. /**
  11413. * Base class for all buttons.
  11414. *
  11415. * @extends ClickableComponent
  11416. */
  11417. class Button extends ClickableComponent {
  11418. /**
  11419. * Create the `Button`s DOM element.
  11420. *
  11421. * @param {string} [tag="button"]
  11422. * The element's node type. This argument is IGNORED: no matter what
  11423. * is passed, it will always create a `button` element.
  11424. *
  11425. * @param {Object} [props={}]
  11426. * An object of properties that should be set on the element.
  11427. *
  11428. * @param {Object} [attributes={}]
  11429. * An object of attributes that should be set on the element.
  11430. *
  11431. * @return {Element}
  11432. * The element that gets created.
  11433. */
  11434. createEl(tag, props = {}, attributes = {}) {
  11435. tag = 'button';
  11436. props = Object.assign({
  11437. className: this.buildCSSClass()
  11438. }, props);
  11439. // Add attributes for button element
  11440. attributes = Object.assign({
  11441. // Necessary since the default button type is "submit"
  11442. type: 'button'
  11443. }, attributes);
  11444. const el = createEl(tag, props, attributes);
  11445. if (!this.player_.options_.experimentalSvgIcons) {
  11446. el.appendChild(createEl('span', {
  11447. className: 'vjs-icon-placeholder'
  11448. }, {
  11449. 'aria-hidden': true
  11450. }));
  11451. }
  11452. this.createControlTextEl(el);
  11453. return el;
  11454. }
  11455. /**
  11456. * Add a child `Component` inside of this `Button`.
  11457. *
  11458. * @param {string|Component} child
  11459. * The name or instance of a child to add.
  11460. *
  11461. * @param {Object} [options={}]
  11462. * The key/value store of options that will get passed to children of
  11463. * the child.
  11464. *
  11465. * @return {Component}
  11466. * The `Component` that gets added as a child. When using a string the
  11467. * `Component` will get created by this process.
  11468. *
  11469. * @deprecated since version 5
  11470. */
  11471. addChild(child, options = {}) {
  11472. const className = this.constructor.name;
  11473. log.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  11474. // Avoid the error message generated by ClickableComponent's addChild method
  11475. return Component.prototype.addChild.call(this, child, options);
  11476. }
  11477. /**
  11478. * Enable the `Button` element so that it can be activated or clicked. Use this with
  11479. * {@link Button#disable}.
  11480. */
  11481. enable() {
  11482. super.enable();
  11483. this.el_.removeAttribute('disabled');
  11484. }
  11485. /**
  11486. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  11487. * {@link Button#enable}.
  11488. */
  11489. disable() {
  11490. super.disable();
  11491. this.el_.setAttribute('disabled', 'disabled');
  11492. }
  11493. /**
  11494. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  11495. * press.
  11496. *
  11497. * @param {KeyboardEvent} event
  11498. * The event that caused this function to get called.
  11499. *
  11500. * @listens keydown
  11501. */
  11502. handleKeyDown(event) {
  11503. // Ignore Space or Enter key operation, which is handled by the browser for
  11504. // a button - though not for its super class, ClickableComponent. Also,
  11505. // prevent the event from propagating through the DOM and triggering Player
  11506. // hotkeys. We do not preventDefault here because we _want_ the browser to
  11507. // handle it.
  11508. if (event.key === ' ' || event.key === 'Enter') {
  11509. event.stopPropagation();
  11510. return;
  11511. }
  11512. // Pass keypress handling up for unsupported keys
  11513. super.handleKeyDown(event);
  11514. }
  11515. }
  11516. Component.registerComponent('Button', Button);
  11517. /**
  11518. * @file big-play-button.js
  11519. */
  11520. /**
  11521. * The initial play button that shows before the video has played. The hiding of the
  11522. * `BigPlayButton` get done via CSS and `Player` states.
  11523. *
  11524. * @extends Button
  11525. */
  11526. class BigPlayButton extends Button {
  11527. constructor(player, options) {
  11528. super(player, options);
  11529. this.mouseused_ = false;
  11530. this.setIcon('play');
  11531. this.on('mousedown', e => this.handleMouseDown(e));
  11532. }
  11533. /**
  11534. * Builds the default DOM `className`.
  11535. *
  11536. * @return {string}
  11537. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  11538. */
  11539. buildCSSClass() {
  11540. return 'vjs-big-play-button';
  11541. }
  11542. /**
  11543. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  11544. * for more detailed information on what a click can be.
  11545. *
  11546. * @param {KeyboardEvent|MouseEvent|TouchEvent} event
  11547. * The `keydown`, `tap`, or `click` event that caused this function to be
  11548. * called.
  11549. *
  11550. * @listens tap
  11551. * @listens click
  11552. */
  11553. handleClick(event) {
  11554. const playPromise = this.player_.play();
  11555. // exit early if clicked via the mouse
  11556. if (this.mouseused_ && 'clientX' in event && 'clientY' in event) {
  11557. silencePromise(playPromise);
  11558. if (this.player_.tech(true)) {
  11559. this.player_.tech(true).focus();
  11560. }
  11561. return;
  11562. }
  11563. const cb = this.player_.getChild('controlBar');
  11564. const playToggle = cb && cb.getChild('playToggle');
  11565. if (!playToggle) {
  11566. this.player_.tech(true).focus();
  11567. return;
  11568. }
  11569. const playFocus = () => playToggle.focus();
  11570. if (isPromise(playPromise)) {
  11571. playPromise.then(playFocus, () => {});
  11572. } else {
  11573. this.setTimeout(playFocus, 1);
  11574. }
  11575. }
  11576. /**
  11577. * Event handler that is called when a `BigPlayButton` receives a
  11578. * `keydown` event.
  11579. *
  11580. * @param {KeyboardEvent} event
  11581. * The `keydown` event that caused this function to be called.
  11582. *
  11583. * @listens keydown
  11584. */
  11585. handleKeyDown(event) {
  11586. this.mouseused_ = false;
  11587. super.handleKeyDown(event);
  11588. }
  11589. /**
  11590. * Handle `mousedown` events on the `BigPlayButton`.
  11591. *
  11592. * @param {MouseEvent} event
  11593. * `mousedown` or `touchstart` event that triggered this function
  11594. *
  11595. * @listens mousedown
  11596. */
  11597. handleMouseDown(event) {
  11598. this.mouseused_ = true;
  11599. }
  11600. }
  11601. /**
  11602. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  11603. *
  11604. * @type {string}
  11605. * @protected
  11606. */
  11607. BigPlayButton.prototype.controlText_ = 'Play Video';
  11608. Component.registerComponent('BigPlayButton', BigPlayButton);
  11609. /**
  11610. * @file close-button.js
  11611. */
  11612. /** @import Player from './player' */
  11613. /**
  11614. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  11615. * it gets clicked.
  11616. *
  11617. * @extends Button
  11618. */
  11619. class CloseButton extends Button {
  11620. /**
  11621. * Creates an instance of the this class.
  11622. *
  11623. * @param {Player} player
  11624. * The `Player` that this class should be attached to.
  11625. *
  11626. * @param {Object} [options]
  11627. * The key/value store of player options.
  11628. */
  11629. constructor(player, options) {
  11630. super(player, options);
  11631. this.setIcon('cancel');
  11632. this.controlText(options && options.controlText || this.localize('Close'));
  11633. }
  11634. /**
  11635. * Builds the default DOM `className`.
  11636. *
  11637. * @return {string}
  11638. * The DOM `className` for this object.
  11639. */
  11640. buildCSSClass() {
  11641. return `vjs-close-button ${super.buildCSSClass()}`;
  11642. }
  11643. /**
  11644. * This gets called when a `CloseButton` gets clicked. See
  11645. * {@link ClickableComponent#handleClick} for more information on when
  11646. * this will be triggered
  11647. *
  11648. * @param {Event} event
  11649. * The `keydown`, `tap`, or `click` event that caused this function to be
  11650. * called.
  11651. *
  11652. * @listens tap
  11653. * @listens click
  11654. * @fires CloseButton#close
  11655. */
  11656. handleClick(event) {
  11657. /**
  11658. * Triggered when the a `CloseButton` is clicked.
  11659. *
  11660. * @event CloseButton#close
  11661. * @type {Event}
  11662. *
  11663. * @property {boolean} [bubbles=false]
  11664. * set to false so that the close event does not
  11665. * bubble up to parents if there is no listener
  11666. */
  11667. this.trigger({
  11668. type: 'close',
  11669. bubbles: false
  11670. });
  11671. }
  11672. /**
  11673. * Event handler that is called when a `CloseButton` receives a
  11674. * `keydown` event.
  11675. *
  11676. * By default, if the key is Esc, it will trigger a `click` event.
  11677. *
  11678. * @param {KeyboardEvent} event
  11679. * The `keydown` event that caused this function to be called.
  11680. *
  11681. * @listens keydown
  11682. */
  11683. handleKeyDown(event) {
  11684. // Esc button will trigger `click` event
  11685. if (event.key === 'Escape') {
  11686. event.preventDefault();
  11687. event.stopPropagation();
  11688. this.trigger('click');
  11689. } else {
  11690. // Pass keypress handling up for unsupported keys
  11691. super.handleKeyDown(event);
  11692. }
  11693. }
  11694. }
  11695. Component.registerComponent('CloseButton', CloseButton);
  11696. /**
  11697. * @file play-toggle.js
  11698. */
  11699. /** @import Player from './player' */
  11700. /**
  11701. * Button to toggle between play and pause.
  11702. *
  11703. * @extends Button
  11704. */
  11705. class PlayToggle extends Button {
  11706. /**
  11707. * Creates an instance of this class.
  11708. *
  11709. * @param {Player} player
  11710. * The `Player` that this class should be attached to.
  11711. *
  11712. * @param {Object} [options={}]
  11713. * The key/value store of player options.
  11714. */
  11715. constructor(player, options = {}) {
  11716. super(player, options);
  11717. // show or hide replay icon
  11718. options.replay = options.replay === undefined || options.replay;
  11719. this.setIcon('play');
  11720. this.on(player, 'play', e => this.handlePlay(e));
  11721. this.on(player, 'pause', e => this.handlePause(e));
  11722. if (options.replay) {
  11723. this.on(player, 'ended', e => this.handleEnded(e));
  11724. }
  11725. }
  11726. /**
  11727. * Builds the default DOM `className`.
  11728. *
  11729. * @return {string}
  11730. * The DOM `className` for this object.
  11731. */
  11732. buildCSSClass() {
  11733. return `vjs-play-control ${super.buildCSSClass()}`;
  11734. }
  11735. /**
  11736. * This gets called when an `PlayToggle` is "clicked". See
  11737. * {@link ClickableComponent} for more detailed information on what a click can be.
  11738. *
  11739. * @param {Event} [event]
  11740. * The `keydown`, `tap`, or `click` event that caused this function to be
  11741. * called.
  11742. *
  11743. * @listens tap
  11744. * @listens click
  11745. */
  11746. handleClick(event) {
  11747. if (this.player_.paused()) {
  11748. silencePromise(this.player_.play());
  11749. } else {
  11750. this.player_.pause();
  11751. }
  11752. }
  11753. /**
  11754. * This gets called once after the video has ended and the user seeks so that
  11755. * we can change the replay button back to a play button.
  11756. *
  11757. * @param {Event} [event]
  11758. * The event that caused this function to run.
  11759. *
  11760. * @listens Player#seeked
  11761. */
  11762. handleSeeked(event) {
  11763. this.removeClass('vjs-ended');
  11764. if (this.player_.paused()) {
  11765. this.handlePause(event);
  11766. } else {
  11767. this.handlePlay(event);
  11768. }
  11769. }
  11770. /**
  11771. * Add the vjs-playing class to the element so it can change appearance.
  11772. *
  11773. * @param {Event} [event]
  11774. * The event that caused this function to run.
  11775. *
  11776. * @listens Player#play
  11777. */
  11778. handlePlay(event) {
  11779. this.removeClass('vjs-ended', 'vjs-paused');
  11780. this.addClass('vjs-playing');
  11781. // change the button text to "Pause"
  11782. this.setIcon('pause');
  11783. this.controlText('Pause');
  11784. }
  11785. /**
  11786. * Add the vjs-paused class to the element so it can change appearance.
  11787. *
  11788. * @param {Event} [event]
  11789. * The event that caused this function to run.
  11790. *
  11791. * @listens Player#pause
  11792. */
  11793. handlePause(event) {
  11794. this.removeClass('vjs-playing');
  11795. this.addClass('vjs-paused');
  11796. // change the button text to "Play"
  11797. this.setIcon('play');
  11798. this.controlText('Play');
  11799. }
  11800. /**
  11801. * Add the vjs-ended class to the element so it can change appearance
  11802. *
  11803. * @param {Event} [event]
  11804. * The event that caused this function to run.
  11805. *
  11806. * @listens Player#ended
  11807. */
  11808. handleEnded(event) {
  11809. this.removeClass('vjs-playing');
  11810. this.addClass('vjs-ended');
  11811. // change the button text to "Replay"
  11812. this.setIcon('replay');
  11813. this.controlText('Replay');
  11814. // on the next seek remove the replay button
  11815. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  11816. }
  11817. }
  11818. /**
  11819. * The text that should display over the `PlayToggle`s controls. Added for localization.
  11820. *
  11821. * @type {string}
  11822. * @protected
  11823. */
  11824. PlayToggle.prototype.controlText_ = 'Play';
  11825. Component.registerComponent('PlayToggle', PlayToggle);
  11826. /**
  11827. * @file time-display.js
  11828. */
  11829. /** @import Player from '../../player' */
  11830. /**
  11831. * Displays time information about the video
  11832. *
  11833. * @extends Component
  11834. */
  11835. class TimeDisplay extends Component {
  11836. /**
  11837. * Creates an instance of this class.
  11838. *
  11839. * @param {Player} player
  11840. * The `Player` that this class should be attached to.
  11841. *
  11842. * @param {Object} [options]
  11843. * The key/value store of player options.
  11844. */
  11845. constructor(player, options) {
  11846. super(player, options);
  11847. this.on(player, ['timeupdate', 'ended', 'seeking'], e => this.update(e));
  11848. this.updateTextNode_();
  11849. }
  11850. /**
  11851. * Create the `Component`'s DOM element
  11852. *
  11853. * @return {Element}
  11854. * The element that was created.
  11855. */
  11856. createEl() {
  11857. const className = this.buildCSSClass();
  11858. const el = super.createEl('div', {
  11859. className: `${className} vjs-time-control vjs-control`
  11860. });
  11861. const span = createEl('span', {
  11862. className: 'vjs-control-text',
  11863. textContent: `${this.localize(this.labelText_)}\u00a0`
  11864. }, {
  11865. role: 'presentation'
  11866. });
  11867. el.appendChild(span);
  11868. this.contentEl_ = createEl('span', {
  11869. className: `${className}-display`
  11870. }, {
  11871. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  11872. // treat them as a break between items in the DOM when using arrow keys
  11873. // (or left-to-right swipes on iOS) to read contents of a page. Using
  11874. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  11875. role: 'presentation'
  11876. });
  11877. el.appendChild(this.contentEl_);
  11878. return el;
  11879. }
  11880. dispose() {
  11881. this.contentEl_ = null;
  11882. this.textNode_ = null;
  11883. super.dispose();
  11884. }
  11885. /**
  11886. * Updates the displayed time according to the `updateContent` function which is defined in the child class.
  11887. *
  11888. * @param {Event} [event]
  11889. * The `timeupdate`, `ended` or `seeking` (if enableSmoothSeeking is true) event that caused this function to be called.
  11890. */
  11891. update(event) {
  11892. if (!this.player_.options_.enableSmoothSeeking && event.type === 'seeking') {
  11893. return;
  11894. }
  11895. this.updateContent(event);
  11896. }
  11897. /**
  11898. * Updates the time display text node with a new time
  11899. *
  11900. * @param {number} [time=0] the time to update to
  11901. *
  11902. * @private
  11903. */
  11904. updateTextNode_(time = 0) {
  11905. time = formatTime(time);
  11906. if (this.formattedTime_ === time) {
  11907. return;
  11908. }
  11909. this.formattedTime_ = time;
  11910. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  11911. if (!this.contentEl_) {
  11912. return;
  11913. }
  11914. let oldNode = this.textNode_;
  11915. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  11916. oldNode = null;
  11917. 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.');
  11918. }
  11919. this.textNode_ = document.createTextNode(this.formattedTime_);
  11920. if (!this.textNode_) {
  11921. return;
  11922. }
  11923. if (oldNode) {
  11924. this.contentEl_.replaceChild(this.textNode_, oldNode);
  11925. } else {
  11926. this.contentEl_.appendChild(this.textNode_);
  11927. }
  11928. });
  11929. }
  11930. /**
  11931. * To be filled out in the child class, should update the displayed time
  11932. * in accordance with the fact that the current time has changed.
  11933. *
  11934. * @param {Event} [event]
  11935. * The `timeupdate` event that caused this to run.
  11936. *
  11937. * @listens Player#timeupdate
  11938. */
  11939. updateContent(event) {}
  11940. }
  11941. /**
  11942. * The text that is added to the `TimeDisplay` for screen reader users.
  11943. *
  11944. * @type {string}
  11945. * @private
  11946. */
  11947. TimeDisplay.prototype.labelText_ = 'Time';
  11948. /**
  11949. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  11950. *
  11951. * @type {string}
  11952. * @protected
  11953. *
  11954. * @deprecated in v7; controlText_ is not used in non-active display Components
  11955. */
  11956. TimeDisplay.prototype.controlText_ = 'Time';
  11957. Component.registerComponent('TimeDisplay', TimeDisplay);
  11958. /**
  11959. * @file current-time-display.js
  11960. */
  11961. /**
  11962. * Displays the current time
  11963. *
  11964. * @extends Component
  11965. */
  11966. class CurrentTimeDisplay extends TimeDisplay {
  11967. /**
  11968. * Builds the default DOM `className`.
  11969. *
  11970. * @return {string}
  11971. * The DOM `className` for this object.
  11972. */
  11973. buildCSSClass() {
  11974. return 'vjs-current-time';
  11975. }
  11976. /**
  11977. * Update current time display
  11978. *
  11979. * @param {Event} [event]
  11980. * The `timeupdate` event that caused this function to run.
  11981. *
  11982. * @listens Player#timeupdate
  11983. */
  11984. updateContent(event) {
  11985. // Allows for smooth scrubbing, when player can't keep up.
  11986. let time;
  11987. if (this.player_.ended()) {
  11988. time = this.player_.duration();
  11989. } else {
  11990. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11991. }
  11992. this.updateTextNode_(time);
  11993. }
  11994. }
  11995. /**
  11996. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  11997. *
  11998. * @type {string}
  11999. * @private
  12000. */
  12001. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  12002. /**
  12003. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  12004. *
  12005. * @type {string}
  12006. * @protected
  12007. *
  12008. * @deprecated in v7; controlText_ is not used in non-active display Components
  12009. */
  12010. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  12011. Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  12012. /**
  12013. * @file duration-display.js
  12014. */
  12015. /** @import Player from '../../player' */
  12016. /**
  12017. * Displays the duration
  12018. *
  12019. * @extends Component
  12020. */
  12021. class DurationDisplay extends TimeDisplay {
  12022. /**
  12023. * Creates an instance of this class.
  12024. *
  12025. * @param {Player} player
  12026. * The `Player` that this class should be attached to.
  12027. *
  12028. * @param {Object} [options]
  12029. * The key/value store of player options.
  12030. */
  12031. constructor(player, options) {
  12032. super(player, options);
  12033. const updateContent = e => this.updateContent(e);
  12034. // we do not want to/need to throttle duration changes,
  12035. // as they should always display the changed duration as
  12036. // it has changed
  12037. this.on(player, 'durationchange', updateContent);
  12038. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  12039. // but the durationchange on the user agent will not fire.
  12040. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  12041. this.on(player, 'loadstart', updateContent);
  12042. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  12043. // listeners could have broken dependent applications/libraries. These
  12044. // can likely be removed for 7.0.
  12045. this.on(player, 'loadedmetadata', updateContent);
  12046. }
  12047. /**
  12048. * Builds the default DOM `className`.
  12049. *
  12050. * @return {string}
  12051. * The DOM `className` for this object.
  12052. */
  12053. buildCSSClass() {
  12054. return 'vjs-duration';
  12055. }
  12056. /**
  12057. * Update duration time display.
  12058. *
  12059. * @param {Event} [event]
  12060. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  12061. * this function to be called.
  12062. *
  12063. * @listens Player#durationchange
  12064. * @listens Player#timeupdate
  12065. * @listens Player#loadedmetadata
  12066. */
  12067. updateContent(event) {
  12068. const duration = this.player_.duration();
  12069. this.updateTextNode_(duration);
  12070. }
  12071. }
  12072. /**
  12073. * The text that is added to the `DurationDisplay` for screen reader users.
  12074. *
  12075. * @type {string}
  12076. * @private
  12077. */
  12078. DurationDisplay.prototype.labelText_ = 'Duration';
  12079. /**
  12080. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  12081. *
  12082. * @type {string}
  12083. * @protected
  12084. *
  12085. * @deprecated in v7; controlText_ is not used in non-active display Components
  12086. */
  12087. DurationDisplay.prototype.controlText_ = 'Duration';
  12088. Component.registerComponent('DurationDisplay', DurationDisplay);
  12089. /**
  12090. * @file time-divider.js
  12091. */
  12092. /**
  12093. * The separator between the current time and duration.
  12094. * Can be hidden if it's not needed in the design.
  12095. *
  12096. * @extends Component
  12097. */
  12098. class TimeDivider extends Component {
  12099. /**
  12100. * Create the component's DOM element
  12101. *
  12102. * @return {Element}
  12103. * The element that was created.
  12104. */
  12105. createEl() {
  12106. const el = super.createEl('div', {
  12107. className: 'vjs-time-control vjs-time-divider'
  12108. }, {
  12109. // this element and its contents can be hidden from assistive techs since
  12110. // it is made extraneous by the announcement of the control text
  12111. // for the current time and duration displays
  12112. 'aria-hidden': true
  12113. });
  12114. const div = super.createEl('div');
  12115. const span = super.createEl('span', {
  12116. textContent: '/'
  12117. });
  12118. div.appendChild(span);
  12119. el.appendChild(div);
  12120. return el;
  12121. }
  12122. }
  12123. Component.registerComponent('TimeDivider', TimeDivider);
  12124. /**
  12125. * @file remaining-time-display.js
  12126. */
  12127. /** @import Player from '../../player' */
  12128. /**
  12129. * Displays the time left in the video
  12130. *
  12131. * @extends Component
  12132. */
  12133. class RemainingTimeDisplay extends TimeDisplay {
  12134. /**
  12135. * Creates an instance of this class.
  12136. *
  12137. * @param {Player} player
  12138. * The `Player` that this class should be attached to.
  12139. *
  12140. * @param {Object} [options]
  12141. * The key/value store of player options.
  12142. */
  12143. constructor(player, options) {
  12144. super(player, options);
  12145. this.on(player, 'durationchange', e => this.updateContent(e));
  12146. }
  12147. /**
  12148. * Builds the default DOM `className`.
  12149. *
  12150. * @return {string}
  12151. * The DOM `className` for this object.
  12152. */
  12153. buildCSSClass() {
  12154. return 'vjs-remaining-time';
  12155. }
  12156. /**
  12157. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  12158. *
  12159. * @return {Element}
  12160. * The element that was created.
  12161. */
  12162. createEl() {
  12163. const el = super.createEl();
  12164. if (this.options_.displayNegative !== false) {
  12165. el.insertBefore(createEl('span', {}, {
  12166. 'aria-hidden': true
  12167. }, '-'), this.contentEl_);
  12168. }
  12169. return el;
  12170. }
  12171. /**
  12172. * Update remaining time display.
  12173. *
  12174. * @param {Event} [event]
  12175. * The `timeupdate` or `durationchange` event that caused this to run.
  12176. *
  12177. * @listens Player#timeupdate
  12178. * @listens Player#durationchange
  12179. */
  12180. updateContent(event) {
  12181. if (typeof this.player_.duration() !== 'number') {
  12182. return;
  12183. }
  12184. let time;
  12185. // @deprecated We should only use remainingTimeDisplay
  12186. // as of video.js 7
  12187. if (this.player_.ended()) {
  12188. time = 0;
  12189. } else if (this.player_.remainingTimeDisplay) {
  12190. time = this.player_.remainingTimeDisplay();
  12191. } else {
  12192. time = this.player_.remainingTime();
  12193. }
  12194. this.updateTextNode_(time);
  12195. }
  12196. }
  12197. /**
  12198. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  12199. *
  12200. * @type {string}
  12201. * @private
  12202. */
  12203. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  12204. /**
  12205. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  12206. *
  12207. * @type {string}
  12208. * @protected
  12209. *
  12210. * @deprecated in v7; controlText_ is not used in non-active display Components
  12211. */
  12212. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  12213. Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  12214. /**
  12215. * @file live-display.js
  12216. */
  12217. /** @import Player from './player' */
  12218. // TODO - Future make it click to snap to live
  12219. /**
  12220. * Displays the live indicator when duration is Infinity.
  12221. *
  12222. * @extends Component
  12223. */
  12224. class LiveDisplay extends Component {
  12225. /**
  12226. * Creates an instance of this class.
  12227. *
  12228. * @param {Player} player
  12229. * The `Player` that this class should be attached to.
  12230. *
  12231. * @param {Object} [options]
  12232. * The key/value store of player options.
  12233. */
  12234. constructor(player, options) {
  12235. super(player, options);
  12236. this.updateShowing();
  12237. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  12238. }
  12239. /**
  12240. * Create the `Component`'s DOM element
  12241. *
  12242. * @return {Element}
  12243. * The element that was created.
  12244. */
  12245. createEl() {
  12246. const el = super.createEl('div', {
  12247. className: 'vjs-live-control vjs-control'
  12248. });
  12249. this.contentEl_ = createEl('div', {
  12250. className: 'vjs-live-display'
  12251. }, {
  12252. 'aria-live': 'off'
  12253. });
  12254. this.contentEl_.appendChild(createEl('span', {
  12255. className: 'vjs-control-text',
  12256. textContent: `${this.localize('Stream Type')}\u00a0`
  12257. }));
  12258. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  12259. el.appendChild(this.contentEl_);
  12260. return el;
  12261. }
  12262. dispose() {
  12263. this.contentEl_ = null;
  12264. super.dispose();
  12265. }
  12266. /**
  12267. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  12268. * it accordingly
  12269. *
  12270. * @param {Event} [event]
  12271. * The {@link Player#durationchange} event that caused this function to run.
  12272. *
  12273. * @listens Player#durationchange
  12274. */
  12275. updateShowing(event) {
  12276. if (this.player().duration() === Infinity) {
  12277. this.show();
  12278. } else {
  12279. this.hide();
  12280. }
  12281. }
  12282. }
  12283. Component.registerComponent('LiveDisplay', LiveDisplay);
  12284. /**
  12285. * @file seek-to-live.js
  12286. */
  12287. /** @import Player from './player' */
  12288. /**
  12289. * Displays the live indicator when duration is Infinity.
  12290. *
  12291. * @extends Component
  12292. */
  12293. class SeekToLive extends Button {
  12294. /**
  12295. * Creates an instance of this class.
  12296. *
  12297. * @param {Player} player
  12298. * The `Player` that this class should be attached to.
  12299. *
  12300. * @param {Object} [options]
  12301. * The key/value store of player options.
  12302. */
  12303. constructor(player, options) {
  12304. super(player, options);
  12305. this.updateLiveEdgeStatus();
  12306. if (this.player_.liveTracker) {
  12307. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  12308. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12309. }
  12310. }
  12311. /**
  12312. * Create the `Component`'s DOM element
  12313. *
  12314. * @return {Element}
  12315. * The element that was created.
  12316. */
  12317. createEl() {
  12318. const el = super.createEl('button', {
  12319. className: 'vjs-seek-to-live-control vjs-control'
  12320. });
  12321. this.setIcon('circle', el);
  12322. this.textEl_ = createEl('span', {
  12323. className: 'vjs-seek-to-live-text',
  12324. textContent: this.localize('LIVE')
  12325. }, {
  12326. 'aria-hidden': 'true'
  12327. });
  12328. el.appendChild(this.textEl_);
  12329. return el;
  12330. }
  12331. /**
  12332. * Update the state of this button if we are at the live edge
  12333. * or not
  12334. */
  12335. updateLiveEdgeStatus() {
  12336. // default to live edge
  12337. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  12338. this.setAttribute('aria-disabled', true);
  12339. this.addClass('vjs-at-live-edge');
  12340. this.controlText('Seek to live, currently playing live');
  12341. } else {
  12342. this.setAttribute('aria-disabled', false);
  12343. this.removeClass('vjs-at-live-edge');
  12344. this.controlText('Seek to live, currently behind live');
  12345. }
  12346. }
  12347. /**
  12348. * On click bring us as near to the live point as possible.
  12349. * This requires that we wait for the next `live-seekable-change`
  12350. * event which will happen every segment length seconds.
  12351. */
  12352. handleClick() {
  12353. this.player_.liveTracker.seekToLiveEdge();
  12354. }
  12355. /**
  12356. * Dispose of the element and stop tracking
  12357. */
  12358. dispose() {
  12359. if (this.player_.liveTracker) {
  12360. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12361. }
  12362. this.textEl_ = null;
  12363. super.dispose();
  12364. }
  12365. }
  12366. /**
  12367. * The text that should display over the `SeekToLive`s control. Added for localization.
  12368. *
  12369. * @type {string}
  12370. * @protected
  12371. */
  12372. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  12373. Component.registerComponent('SeekToLive', SeekToLive);
  12374. /**
  12375. * @file num.js
  12376. * @module num
  12377. */
  12378. /**
  12379. * Keep a number between a min and a max value
  12380. *
  12381. * @param {number} number
  12382. * The number to clamp
  12383. *
  12384. * @param {number} min
  12385. * The minimum value
  12386. * @param {number} max
  12387. * The maximum value
  12388. *
  12389. * @return {number}
  12390. * the clamped number
  12391. */
  12392. function clamp(number, min, max) {
  12393. number = Number(number);
  12394. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  12395. }
  12396. var Num = /*#__PURE__*/Object.freeze({
  12397. __proto__: null,
  12398. clamp: clamp
  12399. });
  12400. /**
  12401. * @file slider.js
  12402. */
  12403. /** @import Player from '../player' */
  12404. /**
  12405. * The base functionality for a slider. Can be vertical or horizontal.
  12406. * For instance the volume bar or the seek bar on a video is a slider.
  12407. *
  12408. * @extends Component
  12409. */
  12410. class Slider extends Component {
  12411. /**
  12412. * Create an instance of this class
  12413. *
  12414. * @param {Player} player
  12415. * The `Player` that this class should be attached to.
  12416. *
  12417. * @param {Object} [options]
  12418. * The key/value store of player options.
  12419. */
  12420. constructor(player, options) {
  12421. super(player, options);
  12422. this.handleMouseDown_ = e => this.handleMouseDown(e);
  12423. this.handleMouseUp_ = e => this.handleMouseUp(e);
  12424. this.handleKeyDown_ = e => this.handleKeyDown(e);
  12425. this.handleClick_ = e => this.handleClick(e);
  12426. this.handleMouseMove_ = e => this.handleMouseMove(e);
  12427. this.update_ = e => this.update(e);
  12428. // Set property names to bar to match with the child Slider class is looking for
  12429. this.bar = this.getChild(this.options_.barName);
  12430. // Set a horizontal or vertical class on the slider depending on the slider type
  12431. this.vertical(!!this.options_.vertical);
  12432. this.enable();
  12433. }
  12434. /**
  12435. * Are controls are currently enabled for this slider or not.
  12436. *
  12437. * @return {boolean}
  12438. * true if controls are enabled, false otherwise
  12439. */
  12440. enabled() {
  12441. return this.enabled_;
  12442. }
  12443. /**
  12444. * Enable controls for this slider if they are disabled
  12445. */
  12446. enable() {
  12447. if (this.enabled()) {
  12448. return;
  12449. }
  12450. this.on('mousedown', this.handleMouseDown_);
  12451. this.on('touchstart', this.handleMouseDown_);
  12452. this.on('keydown', this.handleKeyDown_);
  12453. this.on('click', this.handleClick_);
  12454. // TODO: deprecated, controlsvisible does not seem to be fired
  12455. this.on(this.player_, 'controlsvisible', this.update);
  12456. if (this.playerEvent) {
  12457. this.on(this.player_, this.playerEvent, this.update);
  12458. }
  12459. this.removeClass('disabled');
  12460. this.setAttribute('tabindex', 0);
  12461. this.enabled_ = true;
  12462. }
  12463. /**
  12464. * Disable controls for this slider if they are enabled
  12465. */
  12466. disable() {
  12467. if (!this.enabled()) {
  12468. return;
  12469. }
  12470. const doc = this.bar.el_.ownerDocument;
  12471. this.off('mousedown', this.handleMouseDown_);
  12472. this.off('touchstart', this.handleMouseDown_);
  12473. this.off('keydown', this.handleKeyDown_);
  12474. this.off('click', this.handleClick_);
  12475. this.off(this.player_, 'controlsvisible', this.update_);
  12476. this.off(doc, 'mousemove', this.handleMouseMove_);
  12477. this.off(doc, 'mouseup', this.handleMouseUp_);
  12478. this.off(doc, 'touchmove', this.handleMouseMove_);
  12479. this.off(doc, 'touchend', this.handleMouseUp_);
  12480. this.removeAttribute('tabindex');
  12481. this.addClass('disabled');
  12482. if (this.playerEvent) {
  12483. this.off(this.player_, this.playerEvent, this.update);
  12484. }
  12485. this.enabled_ = false;
  12486. }
  12487. /**
  12488. * Create the `Slider`s DOM element.
  12489. *
  12490. * @param {string} type
  12491. * Type of element to create.
  12492. *
  12493. * @param {Object} [props={}]
  12494. * List of properties in Object form.
  12495. *
  12496. * @param {Object} [attributes={}]
  12497. * list of attributes in Object form.
  12498. *
  12499. * @return {Element}
  12500. * The element that gets created.
  12501. */
  12502. createEl(type, props = {}, attributes = {}) {
  12503. // Add the slider element class to all sub classes
  12504. props.className = props.className + ' vjs-slider';
  12505. props = Object.assign({
  12506. tabIndex: 0
  12507. }, props);
  12508. attributes = Object.assign({
  12509. 'role': 'slider',
  12510. 'aria-valuenow': 0,
  12511. 'aria-valuemin': 0,
  12512. 'aria-valuemax': 100
  12513. }, attributes);
  12514. return super.createEl(type, props, attributes);
  12515. }
  12516. /**
  12517. * Handle `mousedown` or `touchstart` events on the `Slider`.
  12518. *
  12519. * @param {MouseEvent} event
  12520. * `mousedown` or `touchstart` event that triggered this function
  12521. *
  12522. * @listens mousedown
  12523. * @listens touchstart
  12524. * @fires Slider#slideractive
  12525. */
  12526. handleMouseDown(event) {
  12527. const doc = this.bar.el_.ownerDocument;
  12528. if (event.type === 'mousedown') {
  12529. event.preventDefault();
  12530. }
  12531. // Do not call preventDefault() on touchstart in Chrome
  12532. // to avoid console warnings. Use a 'touch-action: none' style
  12533. // instead to prevent unintended scrolling.
  12534. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  12535. if (event.type === 'touchstart' && !IS_CHROME) {
  12536. event.preventDefault();
  12537. }
  12538. blockTextSelection();
  12539. this.addClass('vjs-sliding');
  12540. /**
  12541. * Triggered when the slider is in an active state
  12542. *
  12543. * @event Slider#slideractive
  12544. * @type {MouseEvent}
  12545. */
  12546. this.trigger('slideractive');
  12547. this.on(doc, 'mousemove', this.handleMouseMove_);
  12548. this.on(doc, 'mouseup', this.handleMouseUp_);
  12549. this.on(doc, 'touchmove', this.handleMouseMove_);
  12550. this.on(doc, 'touchend', this.handleMouseUp_);
  12551. this.handleMouseMove(event, true);
  12552. }
  12553. /**
  12554. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  12555. * The `mousemove` and `touchmove` events will only only trigger this function during
  12556. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  12557. * {@link Slider#handleMouseUp}.
  12558. *
  12559. * @param {MouseEvent} event
  12560. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  12561. * this function
  12562. * @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.
  12563. *
  12564. * @listens mousemove
  12565. * @listens touchmove
  12566. */
  12567. handleMouseMove(event) {}
  12568. /**
  12569. * Handle `mouseup` or `touchend` events on the `Slider`.
  12570. *
  12571. * @param {MouseEvent} event
  12572. * `mouseup` or `touchend` event that triggered this function.
  12573. *
  12574. * @listens touchend
  12575. * @listens mouseup
  12576. * @fires Slider#sliderinactive
  12577. */
  12578. handleMouseUp(event) {
  12579. const doc = this.bar.el_.ownerDocument;
  12580. unblockTextSelection();
  12581. this.removeClass('vjs-sliding');
  12582. /**
  12583. * Triggered when the slider is no longer in an active state.
  12584. *
  12585. * @event Slider#sliderinactive
  12586. * @type {Event}
  12587. */
  12588. this.trigger('sliderinactive');
  12589. this.off(doc, 'mousemove', this.handleMouseMove_);
  12590. this.off(doc, 'mouseup', this.handleMouseUp_);
  12591. this.off(doc, 'touchmove', this.handleMouseMove_);
  12592. this.off(doc, 'touchend', this.handleMouseUp_);
  12593. this.update();
  12594. }
  12595. /**
  12596. * Update the progress bar of the `Slider`.
  12597. *
  12598. * @return {number}
  12599. * The percentage of progress the progress bar represents as a
  12600. * number from 0 to 1.
  12601. */
  12602. update() {
  12603. // In VolumeBar init we have a setTimeout for update that pops and update
  12604. // to the end of the execution stack. The player is destroyed before then
  12605. // update will cause an error
  12606. // If there's no bar...
  12607. if (!this.el_ || !this.bar) {
  12608. return;
  12609. }
  12610. // clamp progress between 0 and 1
  12611. // and only round to four decimal places, as we round to two below
  12612. const progress = this.getProgress();
  12613. if (progress === this.progress_) {
  12614. return progress;
  12615. }
  12616. this.progress_ = progress;
  12617. this.requestNamedAnimationFrame('Slider#update', () => {
  12618. // Set the new bar width or height
  12619. const sizeKey = this.vertical() ? 'height' : 'width';
  12620. // Convert to a percentage for css value
  12621. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  12622. });
  12623. return progress;
  12624. }
  12625. /**
  12626. * Get the percentage of the bar that should be filled
  12627. * but clamped and rounded.
  12628. *
  12629. * @return {number}
  12630. * percentage filled that the slider is
  12631. */
  12632. getProgress() {
  12633. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  12634. }
  12635. /**
  12636. * Calculate distance for slider
  12637. *
  12638. * @param {Event} event
  12639. * The event that caused this function to run.
  12640. *
  12641. * @return {number}
  12642. * The current position of the Slider.
  12643. * - position.x for vertical `Slider`s
  12644. * - position.y for horizontal `Slider`s
  12645. */
  12646. calculateDistance(event) {
  12647. const position = getPointerPosition(this.el_, event);
  12648. if (this.vertical()) {
  12649. return position.y;
  12650. }
  12651. return position.x;
  12652. }
  12653. /**
  12654. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  12655. * arrow keys. This function will only be called when the slider has focus. See
  12656. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  12657. *
  12658. * @param {KeyboardEvent} event
  12659. * the `keydown` event that caused this function to run.
  12660. *
  12661. * @listens keydown
  12662. */
  12663. handleKeyDown(event) {
  12664. const spatialNavOptions = this.options_.playerOptions.spatialNavigation;
  12665. const spatialNavEnabled = spatialNavOptions && spatialNavOptions.enabled;
  12666. const horizontalSeek = spatialNavOptions && spatialNavOptions.horizontalSeek;
  12667. if (spatialNavEnabled) {
  12668. if (horizontalSeek && event.key === 'ArrowLeft' || !horizontalSeek && event.key === 'ArrowDown') {
  12669. event.preventDefault();
  12670. event.stopPropagation();
  12671. this.stepBack();
  12672. } else if (horizontalSeek && event.key === 'ArrowRight' || !horizontalSeek && event.key === 'ArrowUp') {
  12673. event.preventDefault();
  12674. event.stopPropagation();
  12675. this.stepForward();
  12676. } else {
  12677. super.handleKeyDown(event);
  12678. }
  12679. // Left and Down Arrows
  12680. } else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {
  12681. event.preventDefault();
  12682. event.stopPropagation();
  12683. this.stepBack();
  12684. // Up and Right Arrows
  12685. } else if (event.key === 'ArrowUp' || event.key === 'ArrowRight') {
  12686. event.preventDefault();
  12687. event.stopPropagation();
  12688. this.stepForward();
  12689. } else {
  12690. // Pass keydown handling up for unsupported keys
  12691. super.handleKeyDown(event);
  12692. }
  12693. }
  12694. /**
  12695. * Listener for click events on slider, used to prevent clicks
  12696. * from bubbling up to parent elements like button menus.
  12697. *
  12698. * @param {Object} event
  12699. * Event that caused this object to run
  12700. */
  12701. handleClick(event) {
  12702. event.stopPropagation();
  12703. event.preventDefault();
  12704. }
  12705. /**
  12706. * Get/set if slider is horizontal for vertical
  12707. *
  12708. * @param {boolean} [bool]
  12709. * - true if slider is vertical,
  12710. * - false is horizontal
  12711. *
  12712. * @return {boolean}
  12713. * - true if slider is vertical, and getting
  12714. * - false if the slider is horizontal, and getting
  12715. */
  12716. vertical(bool) {
  12717. if (bool === undefined) {
  12718. return this.vertical_ || false;
  12719. }
  12720. this.vertical_ = !!bool;
  12721. if (this.vertical_) {
  12722. this.addClass('vjs-slider-vertical');
  12723. } else {
  12724. this.addClass('vjs-slider-horizontal');
  12725. }
  12726. }
  12727. }
  12728. Component.registerComponent('Slider', Slider);
  12729. /**
  12730. * @file load-progress-bar.js
  12731. */
  12732. /** @import Player from '../../player' */
  12733. // get the percent width of a time compared to the total end
  12734. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  12735. /**
  12736. * Shows loading progress
  12737. *
  12738. * @extends Component
  12739. */
  12740. class LoadProgressBar extends Component {
  12741. /**
  12742. * Creates an instance of this class.
  12743. *
  12744. * @param {Player} player
  12745. * The `Player` that this class should be attached to.
  12746. *
  12747. * @param {Object} [options]
  12748. * The key/value store of player options.
  12749. */
  12750. constructor(player, options) {
  12751. super(player, options);
  12752. this.partEls_ = [];
  12753. this.on(player, 'progress', e => this.update(e));
  12754. }
  12755. /**
  12756. * Create the `Component`'s DOM element
  12757. *
  12758. * @return {Element}
  12759. * The element that was created.
  12760. */
  12761. createEl() {
  12762. const el = super.createEl('div', {
  12763. className: 'vjs-load-progress'
  12764. });
  12765. const wrapper = createEl('span', {
  12766. className: 'vjs-control-text'
  12767. });
  12768. const loadedText = createEl('span', {
  12769. textContent: this.localize('Loaded')
  12770. });
  12771. const separator = document.createTextNode(': ');
  12772. this.percentageEl_ = createEl('span', {
  12773. className: 'vjs-control-text-loaded-percentage',
  12774. textContent: '0%'
  12775. });
  12776. el.appendChild(wrapper);
  12777. wrapper.appendChild(loadedText);
  12778. wrapper.appendChild(separator);
  12779. wrapper.appendChild(this.percentageEl_);
  12780. return el;
  12781. }
  12782. dispose() {
  12783. this.partEls_ = null;
  12784. this.percentageEl_ = null;
  12785. super.dispose();
  12786. }
  12787. /**
  12788. * Update progress bar
  12789. *
  12790. * @param {Event} [event]
  12791. * The `progress` event that caused this function to run.
  12792. *
  12793. * @listens Player#progress
  12794. */
  12795. update(event) {
  12796. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  12797. const liveTracker = this.player_.liveTracker;
  12798. const buffered = this.player_.buffered();
  12799. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  12800. const bufferedEnd = this.player_.bufferedEnd();
  12801. const children = this.partEls_;
  12802. const percent = percentify(bufferedEnd, duration);
  12803. if (this.percent_ !== percent) {
  12804. // update the width of the progress bar
  12805. this.el_.style.width = percent;
  12806. // update the control-text
  12807. textContent(this.percentageEl_, percent);
  12808. this.percent_ = percent;
  12809. }
  12810. // add child elements to represent the individual buffered time ranges
  12811. for (let i = 0; i < buffered.length; i++) {
  12812. const start = buffered.start(i);
  12813. const end = buffered.end(i);
  12814. let part = children[i];
  12815. if (!part) {
  12816. part = this.el_.appendChild(createEl());
  12817. children[i] = part;
  12818. }
  12819. // only update if changed
  12820. if (part.dataset.start === start && part.dataset.end === end) {
  12821. continue;
  12822. }
  12823. part.dataset.start = start;
  12824. part.dataset.end = end;
  12825. // set the percent based on the width of the progress bar (bufferedEnd)
  12826. part.style.left = percentify(start, bufferedEnd);
  12827. part.style.width = percentify(end - start, bufferedEnd);
  12828. }
  12829. // remove unused buffered range elements
  12830. for (let i = children.length; i > buffered.length; i--) {
  12831. this.el_.removeChild(children[i - 1]);
  12832. }
  12833. children.length = buffered.length;
  12834. });
  12835. }
  12836. }
  12837. Component.registerComponent('LoadProgressBar', LoadProgressBar);
  12838. /**
  12839. * @file time-tooltip.js
  12840. */
  12841. /** @import Player from '../../player' */
  12842. /**
  12843. * Time tooltips display a time above the progress bar.
  12844. *
  12845. * @extends Component
  12846. */
  12847. class TimeTooltip extends Component {
  12848. /**
  12849. * Creates an instance of this class.
  12850. *
  12851. * @param {Player} player
  12852. * The {@link Player} that this class should be attached to.
  12853. *
  12854. * @param {Object} [options]
  12855. * The key/value store of player options.
  12856. */
  12857. constructor(player, options) {
  12858. super(player, options);
  12859. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12860. }
  12861. /**
  12862. * Create the time tooltip DOM element
  12863. *
  12864. * @return {Element}
  12865. * The element that was created.
  12866. */
  12867. createEl() {
  12868. return super.createEl('div', {
  12869. className: 'vjs-time-tooltip'
  12870. }, {
  12871. 'aria-hidden': 'true'
  12872. });
  12873. }
  12874. /**
  12875. * Updates the position of the time tooltip relative to the `SeekBar`.
  12876. *
  12877. * @param {Object} seekBarRect
  12878. * The `ClientRect` for the {@link SeekBar} element.
  12879. *
  12880. * @param {number} seekBarPoint
  12881. * A number from 0 to 1, representing a horizontal reference point
  12882. * from the left edge of the {@link SeekBar}
  12883. */
  12884. update(seekBarRect, seekBarPoint, content) {
  12885. const tooltipRect = findPosition(this.el_);
  12886. const playerRect = getBoundingClientRect(this.player_.el());
  12887. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  12888. // do nothing if either rect isn't available
  12889. // for example, if the player isn't in the DOM for testing
  12890. if (!playerRect || !tooltipRect) {
  12891. return;
  12892. }
  12893. // This is the space left of the `seekBarPoint` available within the bounds
  12894. // of the player. We calculate any gap between the left edge of the player
  12895. // and the left edge of the `SeekBar` and add the number of pixels in the
  12896. // `SeekBar` before hitting the `seekBarPoint`
  12897. let spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  12898. // This is the space right of the `seekBarPoint` available within the bounds
  12899. // of the player. We calculate the number of pixels from the `seekBarPoint`
  12900. // to the right edge of the `SeekBar` and add to that any gap between the
  12901. // right edge of the `SeekBar` and the player.
  12902. let spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  12903. // spaceRightOfPoint is always NaN for mouse time display
  12904. // because the seekbarRect does not have a right property. This causes
  12905. // the mouse tool tip to be truncated when it's close to the right edge of the player.
  12906. // In such cases, we ignore the `playerRect.right - seekBarRect.right` value when calculating.
  12907. // For the sake of consistency, we ignore seekBarRect.left - playerRect.left for the left edge.
  12908. if (!spaceRightOfPoint) {
  12909. spaceRightOfPoint = seekBarRect.width - seekBarPointPx;
  12910. spaceLeftOfPoint = seekBarPointPx;
  12911. }
  12912. // This is the number of pixels by which the tooltip will need to be pulled
  12913. // further to the right to center it over the `seekBarPoint`.
  12914. let pullTooltipBy = tooltipRect.width / 2;
  12915. // Adjust the `pullTooltipBy` distance to the left or right depending on
  12916. // the results of the space calculations above.
  12917. if (spaceLeftOfPoint < pullTooltipBy) {
  12918. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  12919. } else if (spaceRightOfPoint < pullTooltipBy) {
  12920. pullTooltipBy = spaceRightOfPoint;
  12921. }
  12922. // Due to the imprecision of decimal/ratio based calculations and varying
  12923. // rounding behaviors, there are cases where the spacing adjustment is off
  12924. // by a pixel or two. This adds insurance to these calculations.
  12925. if (pullTooltipBy < 0) {
  12926. pullTooltipBy = 0;
  12927. } else if (pullTooltipBy > tooltipRect.width) {
  12928. pullTooltipBy = tooltipRect.width;
  12929. }
  12930. // prevent small width fluctuations within 0.4px from
  12931. // changing the value below.
  12932. // This really helps for live to prevent the play
  12933. // progress time tooltip from jittering
  12934. pullTooltipBy = Math.round(pullTooltipBy);
  12935. this.el_.style.right = `-${pullTooltipBy}px`;
  12936. this.write(content);
  12937. }
  12938. /**
  12939. * Write the time to the tooltip DOM element.
  12940. *
  12941. * @param {string} content
  12942. * The formatted time for the tooltip.
  12943. */
  12944. write(content) {
  12945. textContent(this.el_, content);
  12946. }
  12947. /**
  12948. * Updates the position of the time tooltip relative to the `SeekBar`.
  12949. *
  12950. * @param {Object} seekBarRect
  12951. * The `ClientRect` for the {@link SeekBar} element.
  12952. *
  12953. * @param {number} seekBarPoint
  12954. * A number from 0 to 1, representing a horizontal reference point
  12955. * from the left edge of the {@link SeekBar}
  12956. *
  12957. * @param {number} time
  12958. * The time to update the tooltip to, not used during live playback
  12959. *
  12960. * @param {Function} cb
  12961. * A function that will be called during the request animation frame
  12962. * for tooltips that need to do additional animations from the default
  12963. */
  12964. updateTime(seekBarRect, seekBarPoint, time, cb) {
  12965. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  12966. let content;
  12967. const duration = this.player_.duration();
  12968. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  12969. const liveWindow = this.player_.liveTracker.liveWindow();
  12970. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  12971. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  12972. } else {
  12973. content = formatTime(time, duration);
  12974. }
  12975. this.update(seekBarRect, seekBarPoint, content);
  12976. if (cb) {
  12977. cb();
  12978. }
  12979. });
  12980. }
  12981. }
  12982. Component.registerComponent('TimeTooltip', TimeTooltip);
  12983. /**
  12984. * @file play-progress-bar.js
  12985. */
  12986. /**
  12987. * Used by {@link SeekBar} to display media playback progress as part of the
  12988. * {@link ProgressControl}.
  12989. *
  12990. * @extends Component
  12991. */
  12992. class PlayProgressBar extends Component {
  12993. /**
  12994. * Creates an instance of this class.
  12995. *
  12996. * @param {Player} player
  12997. * The {@link Player} that this class should be attached to.
  12998. *
  12999. * @param {Object} [options]
  13000. * The key/value store of player options.
  13001. */
  13002. constructor(player, options) {
  13003. super(player, options);
  13004. this.setIcon('circle');
  13005. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13006. }
  13007. /**
  13008. * Create the the DOM element for this class.
  13009. *
  13010. * @return {Element}
  13011. * The element that was created.
  13012. */
  13013. createEl() {
  13014. return super.createEl('div', {
  13015. className: 'vjs-play-progress vjs-slider-bar'
  13016. }, {
  13017. 'aria-hidden': 'true'
  13018. });
  13019. }
  13020. /**
  13021. * Enqueues updates to its own DOM as well as the DOM of its
  13022. * {@link TimeTooltip} child.
  13023. *
  13024. * @param {Object} seekBarRect
  13025. * The `ClientRect` for the {@link SeekBar} element.
  13026. *
  13027. * @param {number} seekBarPoint
  13028. * A number from 0 to 1, representing a horizontal reference point
  13029. * from the left edge of the {@link SeekBar}
  13030. */
  13031. update(seekBarRect, seekBarPoint) {
  13032. const timeTooltip = this.getChild('timeTooltip');
  13033. if (!timeTooltip) {
  13034. return;
  13035. }
  13036. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13037. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  13038. }
  13039. }
  13040. /**
  13041. * Default options for {@link PlayProgressBar}.
  13042. *
  13043. * @type {Object}
  13044. * @private
  13045. */
  13046. PlayProgressBar.prototype.options_ = {
  13047. children: []
  13048. };
  13049. // Time tooltips should not be added to a player on mobile devices
  13050. if (!IS_IOS && !IS_ANDROID) {
  13051. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  13052. }
  13053. Component.registerComponent('PlayProgressBar', PlayProgressBar);
  13054. /**
  13055. * @file mouse-time-display.js
  13056. */
  13057. /**
  13058. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  13059. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  13060. * indicating the time which is represented by a given point in the
  13061. * {@link ProgressControl}.
  13062. *
  13063. * @extends Component
  13064. */
  13065. class MouseTimeDisplay extends Component {
  13066. /**
  13067. * Creates an instance of this class.
  13068. *
  13069. * @param {Player} player
  13070. * The {@link Player} that this class should be attached to.
  13071. *
  13072. * @param {Object} [options]
  13073. * The key/value store of player options.
  13074. */
  13075. constructor(player, options) {
  13076. super(player, options);
  13077. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13078. }
  13079. /**
  13080. * Create the DOM element for this class.
  13081. *
  13082. * @return {Element}
  13083. * The element that was created.
  13084. */
  13085. createEl() {
  13086. return super.createEl('div', {
  13087. className: 'vjs-mouse-display'
  13088. });
  13089. }
  13090. /**
  13091. * Enqueues updates to its own DOM as well as the DOM of its
  13092. * {@link TimeTooltip} child.
  13093. *
  13094. * @param {Object} seekBarRect
  13095. * The `ClientRect` for the {@link SeekBar} element.
  13096. *
  13097. * @param {number} seekBarPoint
  13098. * A number from 0 to 1, representing a horizontal reference point
  13099. * from the left edge of the {@link SeekBar}
  13100. */
  13101. update(seekBarRect, seekBarPoint) {
  13102. const time = seekBarPoint * this.player_.duration();
  13103. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  13104. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  13105. });
  13106. }
  13107. }
  13108. /**
  13109. * Default options for `MouseTimeDisplay`
  13110. *
  13111. * @type {Object}
  13112. * @private
  13113. */
  13114. MouseTimeDisplay.prototype.options_ = {
  13115. children: ['timeTooltip']
  13116. };
  13117. Component.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  13118. /**
  13119. * @file seek-bar.js
  13120. */
  13121. // The number of seconds the `step*` functions move the timeline.
  13122. const STEP_SECONDS = 5;
  13123. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  13124. const PAGE_KEY_MULTIPLIER = 12;
  13125. /**
  13126. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  13127. * as its `bar`.
  13128. *
  13129. * @extends Slider
  13130. */
  13131. class SeekBar extends Slider {
  13132. /**
  13133. * Creates an instance of this class.
  13134. *
  13135. * @param {Player} player
  13136. * The `Player` that this class should be attached to.
  13137. *
  13138. * @param {Object} [options]
  13139. * The key/value store of player options.
  13140. */
  13141. constructor(player, options) {
  13142. options = merge(SeekBar.prototype.options_, options);
  13143. // Avoid mutating the prototype's `children` array by creating a copy
  13144. options.children = [...options.children];
  13145. const shouldDisableSeekWhileScrubbingOnMobile = player.options_.disableSeekWhileScrubbingOnMobile && (IS_IOS || IS_ANDROID);
  13146. // Add the TimeTooltip as a child if we are on desktop, or on mobile with `disableSeekWhileScrubbingOnMobile: true`
  13147. if (!IS_IOS && !IS_ANDROID || shouldDisableSeekWhileScrubbingOnMobile) {
  13148. options.children.splice(1, 0, 'mouseTimeDisplay');
  13149. }
  13150. super(player, options);
  13151. this.shouldDisableSeekWhileScrubbingOnMobile_ = shouldDisableSeekWhileScrubbingOnMobile;
  13152. this.pendingSeekTime_ = null;
  13153. this.setEventHandlers_();
  13154. }
  13155. /**
  13156. * Sets the event handlers
  13157. *
  13158. * @private
  13159. */
  13160. setEventHandlers_() {
  13161. this.update_ = bind_(this, this.update);
  13162. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  13163. this.on(this.player_, ['durationchange', 'timeupdate'], this.update);
  13164. this.on(this.player_, ['ended'], this.update_);
  13165. if (this.player_.liveTracker) {
  13166. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  13167. }
  13168. // when playing, let's ensure we smoothly update the play progress bar
  13169. // via an interval
  13170. this.updateInterval = null;
  13171. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  13172. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  13173. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  13174. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  13175. // we don't need to update the play progress if the document is hidden,
  13176. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13177. if ('hidden' in document && 'visibilityState' in document) {
  13178. this.on(document, 'visibilitychange', this.toggleVisibility_);
  13179. }
  13180. }
  13181. toggleVisibility_(e) {
  13182. if (document.visibilityState === 'hidden') {
  13183. this.cancelNamedAnimationFrame('SeekBar#update');
  13184. this.cancelNamedAnimationFrame('Slider#update');
  13185. this.disableInterval_(e);
  13186. } else {
  13187. if (!this.player_.ended() && !this.player_.paused()) {
  13188. this.enableInterval_();
  13189. }
  13190. // we just switched back to the page and someone may be looking, so, update ASAP
  13191. this.update();
  13192. }
  13193. }
  13194. enableInterval_() {
  13195. if (this.updateInterval) {
  13196. return;
  13197. }
  13198. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  13199. }
  13200. disableInterval_(e) {
  13201. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  13202. return;
  13203. }
  13204. if (!this.updateInterval) {
  13205. return;
  13206. }
  13207. this.clearInterval(this.updateInterval);
  13208. this.updateInterval = null;
  13209. }
  13210. /**
  13211. * Create the `Component`'s DOM element
  13212. *
  13213. * @return {Element}
  13214. * The element that was created.
  13215. */
  13216. createEl() {
  13217. return super.createEl('div', {
  13218. className: 'vjs-progress-holder'
  13219. }, {
  13220. 'aria-label': this.localize('Progress Bar')
  13221. });
  13222. }
  13223. /**
  13224. * This function updates the play progress bar and accessibility
  13225. * attributes to whatever is passed in.
  13226. *
  13227. * @param {Event} [event]
  13228. * The `timeupdate` or `ended` event that caused this to run.
  13229. *
  13230. * @listens Player#timeupdate
  13231. *
  13232. * @return {number}
  13233. * The current percent at a number from 0-1
  13234. */
  13235. update(event) {
  13236. // ignore updates while the tab is hidden
  13237. if (document.visibilityState === 'hidden') {
  13238. return;
  13239. }
  13240. const percent = super.update();
  13241. this.requestNamedAnimationFrame('SeekBar#update', () => {
  13242. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  13243. const liveTracker = this.player_.liveTracker;
  13244. let duration = this.player_.duration();
  13245. if (liveTracker && liveTracker.isLive()) {
  13246. duration = this.player_.liveTracker.liveCurrentTime();
  13247. }
  13248. if (this.percent_ !== percent) {
  13249. // machine readable value of progress bar (percentage complete)
  13250. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  13251. this.percent_ = percent;
  13252. }
  13253. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  13254. // human readable value of progress bar (time complete)
  13255. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  13256. this.currentTime_ = currentTime;
  13257. this.duration_ = duration;
  13258. }
  13259. // update the progress bar time tooltip with the current time
  13260. if (this.bar) {
  13261. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  13262. }
  13263. });
  13264. return percent;
  13265. }
  13266. /**
  13267. * Prevent liveThreshold from causing seeks to seem like they
  13268. * are not happening from a user perspective.
  13269. *
  13270. * @param {number} ct
  13271. * current time to seek to
  13272. */
  13273. userSeek_(ct) {
  13274. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  13275. this.player_.liveTracker.nextSeekedFromUser();
  13276. }
  13277. this.player_.currentTime(ct);
  13278. }
  13279. /**
  13280. * Get the value of current time but allows for smooth scrubbing,
  13281. * when player can't keep up.
  13282. *
  13283. * @return {number}
  13284. * The current time value to display
  13285. *
  13286. * @private
  13287. */
  13288. getCurrentTime_() {
  13289. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13290. }
  13291. /**
  13292. * Get the percentage of media played so far.
  13293. *
  13294. * @return {number}
  13295. * The percentage of media played so far (0 to 1).
  13296. */
  13297. getPercent() {
  13298. // If we have a pending seek time, we are scrubbing on mobile and should set the slider percent
  13299. // to reflect the current scrub location.
  13300. if (this.pendingSeekTime_) {
  13301. return this.pendingSeekTime_ / this.player_.duration();
  13302. }
  13303. const currentTime = this.getCurrentTime_();
  13304. let percent;
  13305. const liveTracker = this.player_.liveTracker;
  13306. if (liveTracker && liveTracker.isLive()) {
  13307. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  13308. // prevent the percent from changing at the live edge
  13309. if (liveTracker.atLiveEdge()) {
  13310. percent = 1;
  13311. }
  13312. } else {
  13313. percent = currentTime / this.player_.duration();
  13314. }
  13315. return percent;
  13316. }
  13317. /**
  13318. * Handle mouse down on seek bar
  13319. *
  13320. * @param {MouseEvent} event
  13321. * The `mousedown` event that caused this to run.
  13322. *
  13323. * @listens mousedown
  13324. */
  13325. handleMouseDown(event) {
  13326. if (!isSingleLeftClick(event)) {
  13327. return;
  13328. }
  13329. // Stop event propagation to prevent double fire in progress-control.js
  13330. event.stopPropagation();
  13331. this.videoWasPlaying = !this.player_.paused();
  13332. // Don't pause if we are on mobile and `disableSeekWhileScrubbingOnMobile: true`.
  13333. // In that case, playback should continue while the player scrubs to a new location.
  13334. if (!this.shouldDisableSeekWhileScrubbingOnMobile_) {
  13335. this.player_.pause();
  13336. }
  13337. super.handleMouseDown(event);
  13338. }
  13339. /**
  13340. * Handle mouse move on seek bar
  13341. *
  13342. * @param {MouseEvent} event
  13343. * The `mousemove` event that caused this to run.
  13344. * @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
  13345. *
  13346. * @listens mousemove
  13347. */
  13348. handleMouseMove(event, mouseDown = false) {
  13349. if (!isSingleLeftClick(event) || isNaN(this.player_.duration())) {
  13350. return;
  13351. }
  13352. if (!mouseDown && !this.player_.scrubbing()) {
  13353. this.player_.scrubbing(true);
  13354. }
  13355. let newTime;
  13356. const distance = this.calculateDistance(event);
  13357. const liveTracker = this.player_.liveTracker;
  13358. if (!liveTracker || !liveTracker.isLive()) {
  13359. newTime = distance * this.player_.duration();
  13360. // Don't let video end while scrubbing.
  13361. if (newTime === this.player_.duration()) {
  13362. newTime = newTime - 0.1;
  13363. }
  13364. } else {
  13365. if (distance >= 0.99) {
  13366. liveTracker.seekToLiveEdge();
  13367. return;
  13368. }
  13369. const seekableStart = liveTracker.seekableStart();
  13370. const seekableEnd = liveTracker.liveCurrentTime();
  13371. newTime = seekableStart + distance * liveTracker.liveWindow();
  13372. // Don't let video end while scrubbing.
  13373. if (newTime >= seekableEnd) {
  13374. newTime = seekableEnd;
  13375. }
  13376. // Compensate for precision differences so that currentTime is not less
  13377. // than seekable start
  13378. if (newTime <= seekableStart) {
  13379. newTime = seekableStart + 0.1;
  13380. }
  13381. // On android seekableEnd can be Infinity sometimes,
  13382. // this will cause newTime to be Infinity, which is
  13383. // not a valid currentTime.
  13384. if (newTime === Infinity) {
  13385. return;
  13386. }
  13387. }
  13388. // if on mobile and `disableSeekWhileScrubbingOnMobile: true`, keep track of the desired seek point but we won't initiate the seek until 'touchend'
  13389. if (this.shouldDisableSeekWhileScrubbingOnMobile_) {
  13390. this.pendingSeekTime_ = newTime;
  13391. } else {
  13392. this.userSeek_(newTime);
  13393. }
  13394. if (this.player_.options_.enableSmoothSeeking) {
  13395. this.update();
  13396. }
  13397. }
  13398. enable() {
  13399. super.enable();
  13400. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13401. if (!mouseTimeDisplay) {
  13402. return;
  13403. }
  13404. mouseTimeDisplay.show();
  13405. }
  13406. disable() {
  13407. super.disable();
  13408. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13409. if (!mouseTimeDisplay) {
  13410. return;
  13411. }
  13412. mouseTimeDisplay.hide();
  13413. }
  13414. /**
  13415. * Handle mouse up on seek bar
  13416. *
  13417. * @param {MouseEvent} event
  13418. * The `mouseup` event that caused this to run.
  13419. *
  13420. * @listens mouseup
  13421. */
  13422. handleMouseUp(event) {
  13423. super.handleMouseUp(event);
  13424. // Stop event propagation to prevent double fire in progress-control.js
  13425. if (event) {
  13426. event.stopPropagation();
  13427. }
  13428. this.player_.scrubbing(false);
  13429. // If we have a pending seek time, then we have finished scrubbing on mobile and should initiate a seek.
  13430. if (this.pendingSeekTime_) {
  13431. this.userSeek_(this.pendingSeekTime_);
  13432. this.pendingSeekTime_ = null;
  13433. }
  13434. /**
  13435. * Trigger timeupdate because we're done seeking and the time has changed.
  13436. * This is particularly useful for if the player is paused to time the time displays.
  13437. *
  13438. * @event Tech#timeupdate
  13439. * @type {Event}
  13440. */
  13441. this.player_.trigger({
  13442. type: 'timeupdate',
  13443. target: this,
  13444. manuallyTriggered: true
  13445. });
  13446. if (this.videoWasPlaying) {
  13447. silencePromise(this.player_.play());
  13448. } else {
  13449. // We're done seeking and the time has changed.
  13450. // If the player is paused, make sure we display the correct time on the seek bar.
  13451. this.update_();
  13452. }
  13453. }
  13454. /**
  13455. * Move more quickly fast forward for keyboard-only users
  13456. */
  13457. stepForward() {
  13458. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  13459. }
  13460. /**
  13461. * Move more quickly rewind for keyboard-only users
  13462. */
  13463. stepBack() {
  13464. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  13465. }
  13466. /**
  13467. * Toggles the playback state of the player
  13468. * This gets called when enter or space is used on the seekbar
  13469. *
  13470. * @param {KeyboardEvent} event
  13471. * The `keydown` event that caused this function to be called
  13472. *
  13473. */
  13474. handleAction(event) {
  13475. if (this.player_.paused()) {
  13476. this.player_.play();
  13477. } else {
  13478. this.player_.pause();
  13479. }
  13480. }
  13481. /**
  13482. * Called when this SeekBar has focus and a key gets pressed down.
  13483. * Supports the following keys:
  13484. *
  13485. * Space or Enter key fire a click event
  13486. * Home key moves to start of the timeline
  13487. * End key moves to end of the timeline
  13488. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  13489. * PageDown key moves back a larger step than ArrowDown
  13490. * PageUp key moves forward a large step
  13491. *
  13492. * @param {KeyboardEvent} event
  13493. * The `keydown` event that caused this function to be called.
  13494. *
  13495. * @listens keydown
  13496. */
  13497. handleKeyDown(event) {
  13498. const liveTracker = this.player_.liveTracker;
  13499. if (event.key === ' ' || event.key === 'Enter') {
  13500. event.preventDefault();
  13501. event.stopPropagation();
  13502. this.handleAction(event);
  13503. } else if (event.key === 'Home') {
  13504. event.preventDefault();
  13505. event.stopPropagation();
  13506. this.userSeek_(0);
  13507. } else if (event.key === 'End') {
  13508. event.preventDefault();
  13509. event.stopPropagation();
  13510. if (liveTracker && liveTracker.isLive()) {
  13511. this.userSeek_(liveTracker.liveCurrentTime());
  13512. } else {
  13513. this.userSeek_(this.player_.duration());
  13514. }
  13515. } else if (/^[0-9]$/.test(event.key)) {
  13516. event.preventDefault();
  13517. event.stopPropagation();
  13518. const gotoFraction = parseInt(event.key, 10) * 0.1;
  13519. if (liveTracker && liveTracker.isLive()) {
  13520. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  13521. } else {
  13522. this.userSeek_(this.player_.duration() * gotoFraction);
  13523. }
  13524. } else if (event.key === 'PageDown') {
  13525. event.preventDefault();
  13526. event.stopPropagation();
  13527. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  13528. } else if (event.key === 'PageUp') {
  13529. event.preventDefault();
  13530. event.stopPropagation();
  13531. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  13532. } else {
  13533. // Pass keydown handling up for unsupported keys
  13534. super.handleKeyDown(event);
  13535. }
  13536. }
  13537. dispose() {
  13538. this.disableInterval_();
  13539. this.off(this.player_, ['durationchange', 'timeupdate'], this.update);
  13540. this.off(this.player_, ['ended'], this.update_);
  13541. if (this.player_.liveTracker) {
  13542. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  13543. }
  13544. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  13545. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  13546. // we don't need to update the play progress if the document is hidden,
  13547. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13548. if ('hidden' in document && 'visibilityState' in document) {
  13549. this.off(document, 'visibilitychange', this.toggleVisibility_);
  13550. }
  13551. super.dispose();
  13552. }
  13553. }
  13554. /**
  13555. * Default options for the `SeekBar`
  13556. *
  13557. * @type {Object}
  13558. * @private
  13559. */
  13560. SeekBar.prototype.options_ = {
  13561. children: ['loadProgressBar', 'playProgressBar'],
  13562. barName: 'playProgressBar'
  13563. };
  13564. Component.registerComponent('SeekBar', SeekBar);
  13565. /**
  13566. * @file progress-control.js
  13567. */
  13568. /**
  13569. * The Progress Control component contains the seek bar, load progress,
  13570. * and play progress.
  13571. *
  13572. * @extends Component
  13573. */
  13574. class ProgressControl extends Component {
  13575. /**
  13576. * Creates an instance of this class.
  13577. *
  13578. * @param {Player} player
  13579. * The `Player` that this class should be attached to.
  13580. *
  13581. * @param {Object} [options]
  13582. * The key/value store of player options.
  13583. */
  13584. constructor(player, options) {
  13585. super(player, options);
  13586. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  13587. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  13588. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  13589. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  13590. this.enable();
  13591. }
  13592. /**
  13593. * Create the `Component`'s DOM element
  13594. *
  13595. * @return {Element}
  13596. * The element that was created.
  13597. */
  13598. createEl() {
  13599. return super.createEl('div', {
  13600. className: 'vjs-progress-control vjs-control'
  13601. });
  13602. }
  13603. /**
  13604. * When the mouse moves over the `ProgressControl`, the pointer position
  13605. * gets passed down to the `MouseTimeDisplay` component.
  13606. *
  13607. * @param {Event} event
  13608. * The `mousemove` event that caused this function to run.
  13609. *
  13610. * @listen mousemove
  13611. */
  13612. handleMouseMove(event) {
  13613. const seekBar = this.getChild('seekBar');
  13614. if (!seekBar) {
  13615. return;
  13616. }
  13617. const playProgressBar = seekBar.getChild('playProgressBar');
  13618. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  13619. if (!playProgressBar && !mouseTimeDisplay) {
  13620. return;
  13621. }
  13622. const seekBarEl = seekBar.el();
  13623. const seekBarRect = findPosition(seekBarEl);
  13624. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  13625. // The default skin has a gap on either side of the `SeekBar`. This means
  13626. // that it's possible to trigger this behavior outside the boundaries of
  13627. // the `SeekBar`. This ensures we stay within it at all times.
  13628. seekBarPoint = clamp(seekBarPoint, 0, 1);
  13629. if (mouseTimeDisplay) {
  13630. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  13631. }
  13632. if (playProgressBar) {
  13633. playProgressBar.update(seekBarRect, seekBar.getProgress());
  13634. }
  13635. }
  13636. /**
  13637. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  13638. *
  13639. * @method ProgressControl#throttledHandleMouseSeek
  13640. * @param {Event} event
  13641. * The `mousemove` event that caused this function to run.
  13642. *
  13643. * @listen mousemove
  13644. * @listen touchmove
  13645. */
  13646. /**
  13647. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  13648. *
  13649. * @param {Event} event
  13650. * `mousedown` or `touchstart` event that triggered this function
  13651. *
  13652. * @listens mousemove
  13653. * @listens touchmove
  13654. */
  13655. handleMouseSeek(event) {
  13656. const seekBar = this.getChild('seekBar');
  13657. if (seekBar) {
  13658. seekBar.handleMouseMove(event);
  13659. }
  13660. }
  13661. /**
  13662. * Are controls are currently enabled for this progress control.
  13663. *
  13664. * @return {boolean}
  13665. * true if controls are enabled, false otherwise
  13666. */
  13667. enabled() {
  13668. return this.enabled_;
  13669. }
  13670. /**
  13671. * Disable all controls on the progress control and its children
  13672. */
  13673. disable() {
  13674. this.children().forEach(child => child.disable && child.disable());
  13675. if (!this.enabled()) {
  13676. return;
  13677. }
  13678. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  13679. this.off(this.el_, ['mousemove', 'touchmove'], this.handleMouseMove);
  13680. this.removeListenersAddedOnMousedownAndTouchstart();
  13681. this.addClass('disabled');
  13682. this.enabled_ = false;
  13683. // Restore normal playback state if controls are disabled while scrubbing
  13684. if (this.player_.scrubbing()) {
  13685. const seekBar = this.getChild('seekBar');
  13686. this.player_.scrubbing(false);
  13687. if (seekBar.videoWasPlaying) {
  13688. silencePromise(this.player_.play());
  13689. }
  13690. }
  13691. }
  13692. /**
  13693. * Enable all controls on the progress control and its children
  13694. */
  13695. enable() {
  13696. this.children().forEach(child => child.enable && child.enable());
  13697. if (this.enabled()) {
  13698. return;
  13699. }
  13700. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  13701. this.on(this.el_, ['mousemove', 'touchmove'], this.handleMouseMove);
  13702. this.removeClass('disabled');
  13703. this.enabled_ = true;
  13704. }
  13705. /**
  13706. * Cleanup listeners after the user finishes interacting with the progress controls
  13707. */
  13708. removeListenersAddedOnMousedownAndTouchstart() {
  13709. const doc = this.el_.ownerDocument;
  13710. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  13711. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  13712. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  13713. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  13714. }
  13715. /**
  13716. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  13717. *
  13718. * @param {Event} event
  13719. * `mousedown` or `touchstart` event that triggered this function
  13720. *
  13721. * @listens mousedown
  13722. * @listens touchstart
  13723. */
  13724. handleMouseDown(event) {
  13725. const doc = this.el_.ownerDocument;
  13726. const seekBar = this.getChild('seekBar');
  13727. if (seekBar) {
  13728. seekBar.handleMouseDown(event);
  13729. }
  13730. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  13731. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  13732. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  13733. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  13734. }
  13735. /**
  13736. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  13737. *
  13738. * @param {Event} event
  13739. * `mouseup` or `touchend` event that triggered this function.
  13740. *
  13741. * @listens touchend
  13742. * @listens mouseup
  13743. */
  13744. handleMouseUp(event) {
  13745. const seekBar = this.getChild('seekBar');
  13746. if (seekBar) {
  13747. seekBar.handleMouseUp(event);
  13748. }
  13749. this.removeListenersAddedOnMousedownAndTouchstart();
  13750. }
  13751. }
  13752. /**
  13753. * Default options for `ProgressControl`
  13754. *
  13755. * @type {Object}
  13756. * @private
  13757. */
  13758. ProgressControl.prototype.options_ = {
  13759. children: ['seekBar']
  13760. };
  13761. Component.registerComponent('ProgressControl', ProgressControl);
  13762. /**
  13763. * @file picture-in-picture-toggle.js
  13764. */
  13765. /** @import Player from './player' */
  13766. /**
  13767. * Toggle Picture-in-Picture mode
  13768. *
  13769. * @extends Button
  13770. */
  13771. class PictureInPictureToggle extends Button {
  13772. /**
  13773. * Creates an instance of this class.
  13774. *
  13775. * @param {Player} player
  13776. * The `Player` that this class should be attached to.
  13777. *
  13778. * @param {Object} [options]
  13779. * The key/value store of player options.
  13780. *
  13781. * @listens Player#enterpictureinpicture
  13782. * @listens Player#leavepictureinpicture
  13783. */
  13784. constructor(player, options) {
  13785. super(player, options);
  13786. this.setIcon('picture-in-picture-enter');
  13787. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  13788. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  13789. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => this.handlePictureInPictureAudioModeChange());
  13790. // TODO: Deactivate button on player emptied event.
  13791. this.disable();
  13792. }
  13793. /**
  13794. * Builds the default DOM `className`.
  13795. *
  13796. * @return {string}
  13797. * The DOM `className` for this object.
  13798. */
  13799. buildCSSClass() {
  13800. return `vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`;
  13801. }
  13802. /**
  13803. * Displays or hides the button depending on the audio mode detection.
  13804. * Exits picture-in-picture if it is enabled when switching to audio mode.
  13805. */
  13806. handlePictureInPictureAudioModeChange() {
  13807. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  13808. const isSourceAudio = this.player_.currentType().substring(0, 5) === 'audio';
  13809. const isAudioMode = isSourceAudio || this.player_.audioPosterMode() || this.player_.audioOnlyMode();
  13810. if (!isAudioMode) {
  13811. this.show();
  13812. return;
  13813. }
  13814. if (this.player_.isInPictureInPicture()) {
  13815. this.player_.exitPictureInPicture();
  13816. }
  13817. this.hide();
  13818. }
  13819. /**
  13820. * Enables or disables button based on availability of a Picture-In-Picture mode.
  13821. *
  13822. * Enabled if
  13823. * - `player.options().enableDocumentPictureInPicture` is true and
  13824. * window.documentPictureInPicture is available; or
  13825. * - `player.disablePictureInPicture()` is false and
  13826. * element.requestPictureInPicture is available
  13827. */
  13828. handlePictureInPictureEnabledChange() {
  13829. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window) {
  13830. this.enable();
  13831. } else {
  13832. this.disable();
  13833. }
  13834. }
  13835. /**
  13836. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  13837. *
  13838. * @param {Event} [event]
  13839. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  13840. * called.
  13841. *
  13842. * @listens Player#enterpictureinpicture
  13843. * @listens Player#leavepictureinpicture
  13844. */
  13845. handlePictureInPictureChange(event) {
  13846. if (this.player_.isInPictureInPicture()) {
  13847. this.setIcon('picture-in-picture-exit');
  13848. this.controlText('Exit Picture-in-Picture');
  13849. } else {
  13850. this.setIcon('picture-in-picture-enter');
  13851. this.controlText('Picture-in-Picture');
  13852. }
  13853. this.handlePictureInPictureEnabledChange();
  13854. }
  13855. /**
  13856. * This gets called when an `PictureInPictureToggle` is "clicked". See
  13857. * {@link ClickableComponent} for more detailed information on what a click can be.
  13858. *
  13859. * @param {Event} [event]
  13860. * The `keydown`, `tap`, or `click` event that caused this function to be
  13861. * called.
  13862. *
  13863. * @listens tap
  13864. * @listens click
  13865. */
  13866. handleClick(event) {
  13867. if (!this.player_.isInPictureInPicture()) {
  13868. this.player_.requestPictureInPicture();
  13869. } else {
  13870. this.player_.exitPictureInPicture();
  13871. }
  13872. }
  13873. /**
  13874. * Show the `Component`s element if it is hidden by removing the
  13875. * 'vjs-hidden' class name from it only in browsers that support the Picture-in-Picture API.
  13876. */
  13877. show() {
  13878. // Does not allow to display the pictureInPictureToggle in browsers that do not support the Picture-in-Picture API, e.g. Firefox.
  13879. if (typeof document.exitPictureInPicture !== 'function') {
  13880. return;
  13881. }
  13882. super.show();
  13883. }
  13884. }
  13885. /**
  13886. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  13887. *
  13888. * @type {string}
  13889. * @protected
  13890. */
  13891. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  13892. Component.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  13893. /**
  13894. * @file fullscreen-toggle.js
  13895. */
  13896. /** @import Player from './player' */
  13897. /**
  13898. * Toggle fullscreen video
  13899. *
  13900. * @extends Button
  13901. */
  13902. class FullscreenToggle extends Button {
  13903. /**
  13904. * Creates an instance of this class.
  13905. *
  13906. * @param {Player} player
  13907. * The `Player` that this class should be attached to.
  13908. *
  13909. * @param {Object} [options]
  13910. * The key/value store of player options.
  13911. */
  13912. constructor(player, options) {
  13913. super(player, options);
  13914. this.setIcon('fullscreen-enter');
  13915. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  13916. if (document[player.fsApi_.fullscreenEnabled] === false) {
  13917. this.disable();
  13918. }
  13919. }
  13920. /**
  13921. * Builds the default DOM `className`.
  13922. *
  13923. * @return {string}
  13924. * The DOM `className` for this object.
  13925. */
  13926. buildCSSClass() {
  13927. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  13928. }
  13929. /**
  13930. * Handles fullscreenchange on the player and change control text accordingly.
  13931. *
  13932. * @param {Event} [event]
  13933. * The {@link Player#fullscreenchange} event that caused this function to be
  13934. * called.
  13935. *
  13936. * @listens Player#fullscreenchange
  13937. */
  13938. handleFullscreenChange(event) {
  13939. if (this.player_.isFullscreen()) {
  13940. this.controlText('Exit Fullscreen');
  13941. this.setIcon('fullscreen-exit');
  13942. } else {
  13943. this.controlText('Fullscreen');
  13944. this.setIcon('fullscreen-enter');
  13945. }
  13946. }
  13947. /**
  13948. * This gets called when an `FullscreenToggle` is "clicked". See
  13949. * {@link ClickableComponent} for more detailed information on what a click can be.
  13950. *
  13951. * @param {Event} [event]
  13952. * The `keydown`, `tap`, or `click` event that caused this function to be
  13953. * called.
  13954. *
  13955. * @listens tap
  13956. * @listens click
  13957. */
  13958. handleClick(event) {
  13959. if (!this.player_.isFullscreen()) {
  13960. this.player_.requestFullscreen();
  13961. } else {
  13962. this.player_.exitFullscreen();
  13963. }
  13964. }
  13965. }
  13966. /**
  13967. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  13968. *
  13969. * @type {string}
  13970. * @protected
  13971. */
  13972. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  13973. Component.registerComponent('FullscreenToggle', FullscreenToggle);
  13974. /** @import Component from '../../component' */
  13975. /** @import Player from '../../player' */
  13976. /**
  13977. * Check if volume control is supported and if it isn't hide the
  13978. * `Component` that was passed using the `vjs-hidden` class.
  13979. *
  13980. * @param {Component} self
  13981. * The component that should be hidden if volume is unsupported
  13982. *
  13983. * @param {Player} player
  13984. * A reference to the player
  13985. *
  13986. * @private
  13987. */
  13988. const checkVolumeSupport = function (self, player) {
  13989. // hide volume controls when they're not supported by the current tech
  13990. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  13991. self.addClass('vjs-hidden');
  13992. }
  13993. self.on(player, 'loadstart', function () {
  13994. if (!player.tech_.featuresVolumeControl) {
  13995. self.addClass('vjs-hidden');
  13996. } else {
  13997. self.removeClass('vjs-hidden');
  13998. }
  13999. });
  14000. };
  14001. /**
  14002. * @file volume-level.js
  14003. */
  14004. /**
  14005. * Shows volume level
  14006. *
  14007. * @extends Component
  14008. */
  14009. class VolumeLevel extends Component {
  14010. /**
  14011. * Create the `Component`'s DOM element
  14012. *
  14013. * @return {Element}
  14014. * The element that was created.
  14015. */
  14016. createEl() {
  14017. const el = super.createEl('div', {
  14018. className: 'vjs-volume-level'
  14019. });
  14020. this.setIcon('circle', el);
  14021. el.appendChild(super.createEl('span', {
  14022. className: 'vjs-control-text'
  14023. }));
  14024. return el;
  14025. }
  14026. }
  14027. Component.registerComponent('VolumeLevel', VolumeLevel);
  14028. /**
  14029. * @file volume-level-tooltip.js
  14030. */
  14031. /** @import Player from '../../player' */
  14032. /**
  14033. * Volume level tooltips display a volume above or side by side the volume bar.
  14034. *
  14035. * @extends Component
  14036. */
  14037. class VolumeLevelTooltip extends Component {
  14038. /**
  14039. * Creates an instance of this class.
  14040. *
  14041. * @param {Player} player
  14042. * The {@link Player} that this class should be attached to.
  14043. *
  14044. * @param {Object} [options]
  14045. * The key/value store of player options.
  14046. */
  14047. constructor(player, options) {
  14048. super(player, options);
  14049. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14050. }
  14051. /**
  14052. * Create the volume tooltip DOM element
  14053. *
  14054. * @return {Element}
  14055. * The element that was created.
  14056. */
  14057. createEl() {
  14058. return super.createEl('div', {
  14059. className: 'vjs-volume-tooltip'
  14060. }, {
  14061. 'aria-hidden': 'true'
  14062. });
  14063. }
  14064. /**
  14065. * Updates the position of the tooltip relative to the `VolumeBar` and
  14066. * its content text.
  14067. *
  14068. * @param {Object} rangeBarRect
  14069. * The `ClientRect` for the {@link VolumeBar} element.
  14070. *
  14071. * @param {number} rangeBarPoint
  14072. * A number from 0 to 1, representing a horizontal/vertical reference point
  14073. * from the left edge of the {@link VolumeBar}
  14074. *
  14075. * @param {boolean} vertical
  14076. * Referees to the Volume control position
  14077. * in the control bar{@link VolumeControl}
  14078. *
  14079. */
  14080. update(rangeBarRect, rangeBarPoint, vertical, content) {
  14081. if (!vertical) {
  14082. const tooltipRect = getBoundingClientRect(this.el_);
  14083. const playerRect = getBoundingClientRect(this.player_.el());
  14084. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  14085. if (!playerRect || !tooltipRect) {
  14086. return;
  14087. }
  14088. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  14089. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  14090. let pullTooltipBy = tooltipRect.width / 2;
  14091. if (spaceLeftOfPoint < pullTooltipBy) {
  14092. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  14093. } else if (spaceRightOfPoint < pullTooltipBy) {
  14094. pullTooltipBy = spaceRightOfPoint;
  14095. }
  14096. if (pullTooltipBy < 0) {
  14097. pullTooltipBy = 0;
  14098. } else if (pullTooltipBy > tooltipRect.width) {
  14099. pullTooltipBy = tooltipRect.width;
  14100. }
  14101. this.el_.style.right = `-${pullTooltipBy}px`;
  14102. }
  14103. this.write(`${content}%`);
  14104. }
  14105. /**
  14106. * Write the volume to the tooltip DOM element.
  14107. *
  14108. * @param {string} content
  14109. * The formatted volume for the tooltip.
  14110. */
  14111. write(content) {
  14112. textContent(this.el_, content);
  14113. }
  14114. /**
  14115. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  14116. *
  14117. * @param {Object} rangeBarRect
  14118. * The `ClientRect` for the {@link VolumeBar} element.
  14119. *
  14120. * @param {number} rangeBarPoint
  14121. * A number from 0 to 1, representing a horizontal/vertical reference point
  14122. * from the left edge of the {@link VolumeBar}
  14123. *
  14124. * @param {boolean} vertical
  14125. * Referees to the Volume control position
  14126. * in the control bar{@link VolumeControl}
  14127. *
  14128. * @param {number} volume
  14129. * The volume level to update the tooltip to
  14130. *
  14131. * @param {Function} cb
  14132. * A function that will be called during the request animation frame
  14133. * for tooltips that need to do additional animations from the default
  14134. */
  14135. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  14136. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  14137. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  14138. if (cb) {
  14139. cb();
  14140. }
  14141. });
  14142. }
  14143. }
  14144. Component.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  14145. /**
  14146. * @file mouse-volume-level-display.js
  14147. */
  14148. /**
  14149. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  14150. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  14151. * indicating the volume level which is represented by a given point in the
  14152. * {@link VolumeBar}.
  14153. *
  14154. * @extends Component
  14155. */
  14156. class MouseVolumeLevelDisplay extends Component {
  14157. /**
  14158. * Creates an instance of this class.
  14159. *
  14160. * @param {Player} player
  14161. * The {@link Player} that this class should be attached to.
  14162. *
  14163. * @param {Object} [options]
  14164. * The key/value store of player options.
  14165. */
  14166. constructor(player, options) {
  14167. super(player, options);
  14168. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14169. }
  14170. /**
  14171. * Create the DOM element for this class.
  14172. *
  14173. * @return {Element}
  14174. * The element that was created.
  14175. */
  14176. createEl() {
  14177. return super.createEl('div', {
  14178. className: 'vjs-mouse-display'
  14179. });
  14180. }
  14181. /**
  14182. * Enquires updates to its own DOM as well as the DOM of its
  14183. * {@link VolumeLevelTooltip} child.
  14184. *
  14185. * @param {Object} rangeBarRect
  14186. * The `ClientRect` for the {@link VolumeBar} element.
  14187. *
  14188. * @param {number} rangeBarPoint
  14189. * A number from 0 to 1, representing a horizontal/vertical reference point
  14190. * from the left edge of the {@link VolumeBar}
  14191. *
  14192. * @param {boolean} vertical
  14193. * Referees to the Volume control position
  14194. * in the control bar{@link VolumeControl}
  14195. *
  14196. */
  14197. update(rangeBarRect, rangeBarPoint, vertical) {
  14198. const volume = 100 * rangeBarPoint;
  14199. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  14200. if (vertical) {
  14201. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  14202. } else {
  14203. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  14204. }
  14205. });
  14206. }
  14207. }
  14208. /**
  14209. * Default options for `MouseVolumeLevelDisplay`
  14210. *
  14211. * @type {Object}
  14212. * @private
  14213. */
  14214. MouseVolumeLevelDisplay.prototype.options_ = {
  14215. children: ['volumeLevelTooltip']
  14216. };
  14217. Component.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  14218. /**
  14219. * @file volume-bar.js
  14220. */
  14221. /**
  14222. * The bar that contains the volume level and can be clicked on to adjust the level
  14223. *
  14224. * @extends Slider
  14225. */
  14226. class VolumeBar extends Slider {
  14227. /**
  14228. * Creates an instance of this class.
  14229. *
  14230. * @param {Player} player
  14231. * The `Player` that this class should be attached to.
  14232. *
  14233. * @param {Object} [options]
  14234. * The key/value store of player options.
  14235. */
  14236. constructor(player, options) {
  14237. super(player, options);
  14238. this.on('slideractive', e => this.updateLastVolume_(e));
  14239. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  14240. player.ready(() => this.updateARIAAttributes());
  14241. }
  14242. /**
  14243. * Create the `Component`'s DOM element
  14244. *
  14245. * @return {Element}
  14246. * The element that was created.
  14247. */
  14248. createEl() {
  14249. return super.createEl('div', {
  14250. className: 'vjs-volume-bar vjs-slider-bar'
  14251. }, {
  14252. 'aria-label': this.localize('Volume Level'),
  14253. 'aria-live': 'polite'
  14254. });
  14255. }
  14256. /**
  14257. * Handle mouse down on volume bar
  14258. *
  14259. * @param {Event} event
  14260. * The `mousedown` event that caused this to run.
  14261. *
  14262. * @listens mousedown
  14263. */
  14264. handleMouseDown(event) {
  14265. if (!isSingleLeftClick(event)) {
  14266. return;
  14267. }
  14268. super.handleMouseDown(event);
  14269. }
  14270. /**
  14271. * Handle movement events on the {@link VolumeMenuButton}.
  14272. *
  14273. * @param {Event} event
  14274. * The event that caused this function to run.
  14275. *
  14276. * @listens mousemove
  14277. */
  14278. handleMouseMove(event) {
  14279. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  14280. if (mouseVolumeLevelDisplay) {
  14281. const volumeBarEl = this.el();
  14282. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  14283. const vertical = this.vertical();
  14284. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  14285. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  14286. // The default skin has a gap on either side of the `VolumeBar`. This means
  14287. // that it's possible to trigger this behavior outside the boundaries of
  14288. // the `VolumeBar`. This ensures we stay within it at all times.
  14289. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  14290. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  14291. }
  14292. if (!isSingleLeftClick(event)) {
  14293. return;
  14294. }
  14295. this.checkMuted();
  14296. this.player_.volume(this.calculateDistance(event));
  14297. }
  14298. /**
  14299. * If the player is muted unmute it.
  14300. */
  14301. checkMuted() {
  14302. if (this.player_.muted()) {
  14303. this.player_.muted(false);
  14304. }
  14305. }
  14306. /**
  14307. * Get percent of volume level
  14308. *
  14309. * @return {number}
  14310. * Volume level percent as a decimal number.
  14311. */
  14312. getPercent() {
  14313. if (this.player_.muted()) {
  14314. return 0;
  14315. }
  14316. return this.player_.volume();
  14317. }
  14318. /**
  14319. * Increase volume level for keyboard users
  14320. */
  14321. stepForward() {
  14322. this.checkMuted();
  14323. this.player_.volume(this.player_.volume() + 0.1);
  14324. }
  14325. /**
  14326. * Decrease volume level for keyboard users
  14327. */
  14328. stepBack() {
  14329. this.checkMuted();
  14330. this.player_.volume(this.player_.volume() - 0.1);
  14331. }
  14332. /**
  14333. * Update ARIA accessibility attributes
  14334. *
  14335. * @param {Event} [event]
  14336. * The `volumechange` event that caused this function to run.
  14337. *
  14338. * @listens Player#volumechange
  14339. */
  14340. updateARIAAttributes(event) {
  14341. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  14342. this.el_.setAttribute('aria-valuenow', ariaValue);
  14343. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  14344. }
  14345. /**
  14346. * Returns the current value of the player volume as a percentage
  14347. *
  14348. * @private
  14349. */
  14350. volumeAsPercentage_() {
  14351. return Math.round(this.player_.volume() * 100);
  14352. }
  14353. /**
  14354. * When user starts dragging the VolumeBar, store the volume and listen for
  14355. * the end of the drag. When the drag ends, if the volume was set to zero,
  14356. * set lastVolume to the stored volume.
  14357. *
  14358. * @listens slideractive
  14359. * @private
  14360. */
  14361. updateLastVolume_() {
  14362. const volumeBeforeDrag = this.player_.volume();
  14363. this.one('sliderinactive', () => {
  14364. if (this.player_.volume() === 0) {
  14365. this.player_.lastVolume_(volumeBeforeDrag);
  14366. }
  14367. });
  14368. }
  14369. }
  14370. /**
  14371. * Default options for the `VolumeBar`
  14372. *
  14373. * @type {Object}
  14374. * @private
  14375. */
  14376. VolumeBar.prototype.options_ = {
  14377. children: ['volumeLevel'],
  14378. barName: 'volumeLevel'
  14379. };
  14380. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  14381. if (!IS_IOS && !IS_ANDROID) {
  14382. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  14383. }
  14384. /**
  14385. * Call the update event for this Slider when this event happens on the player.
  14386. *
  14387. * @type {string}
  14388. */
  14389. VolumeBar.prototype.playerEvent = 'volumechange';
  14390. Component.registerComponent('VolumeBar', VolumeBar);
  14391. /**
  14392. * @file volume-control.js
  14393. */
  14394. /**
  14395. * The component for controlling the volume level
  14396. *
  14397. * @extends Component
  14398. */
  14399. class VolumeControl extends Component {
  14400. /**
  14401. * Creates an instance of this class.
  14402. *
  14403. * @param {Player} player
  14404. * The `Player` that this class should be attached to.
  14405. *
  14406. * @param {Object} [options={}]
  14407. * The key/value store of player options.
  14408. */
  14409. constructor(player, options = {}) {
  14410. options.vertical = options.vertical || false;
  14411. // Pass the vertical option down to the VolumeBar if
  14412. // the VolumeBar is turned on.
  14413. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  14414. options.volumeBar = options.volumeBar || {};
  14415. options.volumeBar.vertical = options.vertical;
  14416. }
  14417. super(player, options);
  14418. // hide this control if volume support is missing
  14419. checkVolumeSupport(this, player);
  14420. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  14421. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  14422. this.on('mousedown', e => this.handleMouseDown(e));
  14423. this.on('touchstart', e => this.handleMouseDown(e));
  14424. this.on('mousemove', e => this.handleMouseMove(e));
  14425. // while the slider is active (the mouse has been pressed down and
  14426. // is dragging) or in focus we do not want to hide the VolumeBar
  14427. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  14428. this.volumeBar.addClass('vjs-slider-active');
  14429. this.addClass('vjs-slider-active');
  14430. this.trigger('slideractive');
  14431. });
  14432. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  14433. this.volumeBar.removeClass('vjs-slider-active');
  14434. this.removeClass('vjs-slider-active');
  14435. this.trigger('sliderinactive');
  14436. });
  14437. }
  14438. /**
  14439. * Create the `Component`'s DOM element
  14440. *
  14441. * @return {Element}
  14442. * The element that was created.
  14443. */
  14444. createEl() {
  14445. let orientationClass = 'vjs-volume-horizontal';
  14446. if (this.options_.vertical) {
  14447. orientationClass = 'vjs-volume-vertical';
  14448. }
  14449. return super.createEl('div', {
  14450. className: `vjs-volume-control vjs-control ${orientationClass}`
  14451. });
  14452. }
  14453. /**
  14454. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  14455. *
  14456. * @param {Event} event
  14457. * `mousedown` or `touchstart` event that triggered this function
  14458. *
  14459. * @listens mousedown
  14460. * @listens touchstart
  14461. */
  14462. handleMouseDown(event) {
  14463. const doc = this.el_.ownerDocument;
  14464. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  14465. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  14466. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  14467. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  14468. }
  14469. /**
  14470. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  14471. *
  14472. * @param {Event} event
  14473. * `mouseup` or `touchend` event that triggered this function.
  14474. *
  14475. * @listens touchend
  14476. * @listens mouseup
  14477. */
  14478. handleMouseUp(event) {
  14479. const doc = this.el_.ownerDocument;
  14480. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  14481. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  14482. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  14483. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  14484. }
  14485. /**
  14486. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  14487. *
  14488. * @param {Event} event
  14489. * `mousedown` or `touchstart` event that triggered this function
  14490. *
  14491. * @listens mousedown
  14492. * @listens touchstart
  14493. */
  14494. handleMouseMove(event) {
  14495. this.volumeBar.handleMouseMove(event);
  14496. }
  14497. }
  14498. /**
  14499. * Default options for the `VolumeControl`
  14500. *
  14501. * @type {Object}
  14502. * @private
  14503. */
  14504. VolumeControl.prototype.options_ = {
  14505. children: ['volumeBar']
  14506. };
  14507. Component.registerComponent('VolumeControl', VolumeControl);
  14508. /** @import Component from '../../component' */
  14509. /** @import Player from '../../player' */
  14510. /**
  14511. * Check if muting volume is supported and if it isn't hide the mute toggle
  14512. * button.
  14513. *
  14514. * @param {Component} self
  14515. * A reference to the mute toggle button
  14516. *
  14517. * @param {Player} player
  14518. * A reference to the player
  14519. *
  14520. * @private
  14521. */
  14522. const checkMuteSupport = function (self, player) {
  14523. // hide mute toggle button if it's not supported by the current tech
  14524. if (player.tech_ && !player.tech_.featuresMuteControl) {
  14525. self.addClass('vjs-hidden');
  14526. }
  14527. self.on(player, 'loadstart', function () {
  14528. if (!player.tech_.featuresMuteControl) {
  14529. self.addClass('vjs-hidden');
  14530. } else {
  14531. self.removeClass('vjs-hidden');
  14532. }
  14533. });
  14534. };
  14535. /**
  14536. * @file mute-toggle.js
  14537. */
  14538. /** @import Player from './player' */
  14539. /**
  14540. * A button component for muting the audio.
  14541. *
  14542. * @extends Button
  14543. */
  14544. class MuteToggle extends Button {
  14545. /**
  14546. * Creates an instance of this class.
  14547. *
  14548. * @param {Player} player
  14549. * The `Player` that this class should be attached to.
  14550. *
  14551. * @param {Object} [options]
  14552. * The key/value store of player options.
  14553. */
  14554. constructor(player, options) {
  14555. super(player, options);
  14556. // hide this control if volume support is missing
  14557. checkMuteSupport(this, player);
  14558. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  14559. }
  14560. /**
  14561. * Builds the default DOM `className`.
  14562. *
  14563. * @return {string}
  14564. * The DOM `className` for this object.
  14565. */
  14566. buildCSSClass() {
  14567. return `vjs-mute-control ${super.buildCSSClass()}`;
  14568. }
  14569. /**
  14570. * This gets called when an `MuteToggle` is "clicked". See
  14571. * {@link ClickableComponent} for more detailed information on what a click can be.
  14572. *
  14573. * @param {Event} [event]
  14574. * The `keydown`, `tap`, or `click` event that caused this function to be
  14575. * called.
  14576. *
  14577. * @listens tap
  14578. * @listens click
  14579. */
  14580. handleClick(event) {
  14581. const vol = this.player_.volume();
  14582. const lastVolume = this.player_.lastVolume_();
  14583. if (vol === 0) {
  14584. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  14585. this.player_.volume(volumeToSet);
  14586. this.player_.muted(false);
  14587. } else {
  14588. this.player_.muted(this.player_.muted() ? false : true);
  14589. }
  14590. }
  14591. /**
  14592. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  14593. * on the player.
  14594. *
  14595. * @param {Event} [event]
  14596. * The {@link Player#loadstart} event if this function was called
  14597. * through an event.
  14598. *
  14599. * @listens Player#loadstart
  14600. * @listens Player#volumechange
  14601. */
  14602. update(event) {
  14603. this.updateIcon_();
  14604. this.updateControlText_();
  14605. }
  14606. /**
  14607. * Update the appearance of the `MuteToggle` icon.
  14608. *
  14609. * Possible states (given `level` variable below):
  14610. * - 0: crossed out
  14611. * - 1: zero bars of volume
  14612. * - 2: one bar of volume
  14613. * - 3: two bars of volume
  14614. *
  14615. * @private
  14616. */
  14617. updateIcon_() {
  14618. const vol = this.player_.volume();
  14619. let level = 3;
  14620. this.setIcon('volume-high');
  14621. // in iOS when a player is loaded with muted attribute
  14622. // and volume is changed with a native mute button
  14623. // we want to make sure muted state is updated
  14624. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  14625. this.player_.muted(this.player_.tech_.el_.muted);
  14626. }
  14627. if (vol === 0 || this.player_.muted()) {
  14628. this.setIcon('volume-mute');
  14629. level = 0;
  14630. } else if (vol < 0.33) {
  14631. this.setIcon('volume-low');
  14632. level = 1;
  14633. } else if (vol < 0.67) {
  14634. this.setIcon('volume-medium');
  14635. level = 2;
  14636. }
  14637. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  14638. addClass(this.el_, `vjs-vol-${level}`);
  14639. }
  14640. /**
  14641. * If `muted` has changed on the player, update the control text
  14642. * (`title` attribute on `vjs-mute-control` element and content of
  14643. * `vjs-control-text` element).
  14644. *
  14645. * @private
  14646. */
  14647. updateControlText_() {
  14648. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  14649. const text = soundOff ? 'Unmute' : 'Mute';
  14650. if (this.controlText() !== text) {
  14651. this.controlText(text);
  14652. }
  14653. }
  14654. }
  14655. /**
  14656. * The text that should display over the `MuteToggle`s controls. Added for localization.
  14657. *
  14658. * @type {string}
  14659. * @protected
  14660. */
  14661. MuteToggle.prototype.controlText_ = 'Mute';
  14662. Component.registerComponent('MuteToggle', MuteToggle);
  14663. /**
  14664. * @file volume-control.js
  14665. */
  14666. /**
  14667. * A Component to contain the MuteToggle and VolumeControl so that
  14668. * they can work together.
  14669. *
  14670. * @extends Component
  14671. */
  14672. class VolumePanel extends Component {
  14673. /**
  14674. * Creates an instance of this class.
  14675. *
  14676. * @param {Player} player
  14677. * The `Player` that this class should be attached to.
  14678. *
  14679. * @param {Object} [options={}]
  14680. * The key/value store of player options.
  14681. */
  14682. constructor(player, options = {}) {
  14683. if (typeof options.inline !== 'undefined') {
  14684. options.inline = options.inline;
  14685. } else {
  14686. options.inline = true;
  14687. }
  14688. // pass the inline option down to the VolumeControl as vertical if
  14689. // the VolumeControl is on.
  14690. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  14691. options.volumeControl = options.volumeControl || {};
  14692. options.volumeControl.vertical = !options.inline;
  14693. }
  14694. super(player, options);
  14695. // this handler is used by mouse handler methods below
  14696. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  14697. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  14698. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  14699. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  14700. this.on('keydown', e => this.handleKeyPress(e));
  14701. this.on('mouseover', e => this.handleMouseOver(e));
  14702. this.on('mouseout', e => this.handleMouseOut(e));
  14703. // while the slider is active (the mouse has been pressed down and
  14704. // is dragging) we do not want to hide the VolumeBar
  14705. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  14706. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  14707. }
  14708. /**
  14709. * Add vjs-slider-active class to the VolumePanel
  14710. *
  14711. * @listens VolumeControl#slideractive
  14712. * @private
  14713. */
  14714. sliderActive_() {
  14715. this.addClass('vjs-slider-active');
  14716. }
  14717. /**
  14718. * Removes vjs-slider-active class to the VolumePanel
  14719. *
  14720. * @listens VolumeControl#sliderinactive
  14721. * @private
  14722. */
  14723. sliderInactive_() {
  14724. this.removeClass('vjs-slider-active');
  14725. }
  14726. /**
  14727. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  14728. * depending on MuteToggle and VolumeControl state
  14729. *
  14730. * @listens Player#loadstart
  14731. * @private
  14732. */
  14733. volumePanelState_() {
  14734. // hide volume panel if neither volume control or mute toggle
  14735. // are displayed
  14736. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  14737. this.addClass('vjs-hidden');
  14738. }
  14739. // if only mute toggle is visible we don't want
  14740. // volume panel expanding when hovered or active
  14741. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  14742. this.addClass('vjs-mute-toggle-only');
  14743. }
  14744. }
  14745. /**
  14746. * Create the `Component`'s DOM element
  14747. *
  14748. * @return {Element}
  14749. * The element that was created.
  14750. */
  14751. createEl() {
  14752. let orientationClass = 'vjs-volume-panel-horizontal';
  14753. if (!this.options_.inline) {
  14754. orientationClass = 'vjs-volume-panel-vertical';
  14755. }
  14756. return super.createEl('div', {
  14757. className: `vjs-volume-panel vjs-control ${orientationClass}`
  14758. });
  14759. }
  14760. /**
  14761. * Dispose of the `volume-panel` and all child components.
  14762. */
  14763. dispose() {
  14764. this.handleMouseOut();
  14765. super.dispose();
  14766. }
  14767. /**
  14768. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  14769. * the volume panel and sets focus on `MuteToggle`.
  14770. *
  14771. * @param {Event} event
  14772. * The `keyup` event that caused this function to be called.
  14773. *
  14774. * @listens keyup
  14775. */
  14776. handleVolumeControlKeyUp(event) {
  14777. if (event.key === 'Escape') {
  14778. this.muteToggle.focus();
  14779. }
  14780. }
  14781. /**
  14782. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  14783. * Turns on listening for `mouseover` event. When they happen it
  14784. * calls `this.handleMouseOver`.
  14785. *
  14786. * @param {Event} event
  14787. * The `mouseover` event that caused this function to be called.
  14788. *
  14789. * @listens mouseover
  14790. */
  14791. handleMouseOver(event) {
  14792. this.addClass('vjs-hover');
  14793. on(document, 'keyup', this.handleKeyPressHandler_);
  14794. }
  14795. /**
  14796. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  14797. * Turns on listening for `mouseout` event. When they happen it
  14798. * calls `this.handleMouseOut`.
  14799. *
  14800. * @param {Event} event
  14801. * The `mouseout` event that caused this function to be called.
  14802. *
  14803. * @listens mouseout
  14804. */
  14805. handleMouseOut(event) {
  14806. this.removeClass('vjs-hover');
  14807. off(document, 'keyup', this.handleKeyPressHandler_);
  14808. }
  14809. /**
  14810. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  14811. * looking for ESC, which hides the `VolumeControl`.
  14812. *
  14813. * @param {Event} event
  14814. * The keypress that triggered this event.
  14815. *
  14816. * @listens keydown | keyup
  14817. */
  14818. handleKeyPress(event) {
  14819. if (event.key === 'Escape') {
  14820. this.handleMouseOut();
  14821. }
  14822. }
  14823. }
  14824. /**
  14825. * Default options for the `VolumeControl`
  14826. *
  14827. * @type {Object}
  14828. * @private
  14829. */
  14830. VolumePanel.prototype.options_ = {
  14831. children: ['muteToggle', 'volumeControl']
  14832. };
  14833. Component.registerComponent('VolumePanel', VolumePanel);
  14834. /**
  14835. * Button to skip forward a configurable amount of time
  14836. * through a video. Renders in the control bar.
  14837. *
  14838. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  14839. *
  14840. * @extends Button
  14841. */
  14842. class SkipForward extends Button {
  14843. constructor(player, options) {
  14844. super(player, options);
  14845. this.validOptions = [5, 10, 30];
  14846. this.skipTime = this.getSkipForwardTime();
  14847. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  14848. this.setIcon(`forward-${this.skipTime}`);
  14849. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime.toLocaleString(player.language())]));
  14850. this.show();
  14851. } else {
  14852. this.hide();
  14853. }
  14854. }
  14855. getSkipForwardTime() {
  14856. const playerOptions = this.options_.playerOptions;
  14857. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  14858. }
  14859. buildCSSClass() {
  14860. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  14861. }
  14862. /**
  14863. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  14864. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  14865. * skips to end of duration/seekable range.
  14866. *
  14867. * Handle a click on a `SkipForward` button
  14868. *
  14869. * @param {EventTarget~Event} event
  14870. * The `click` event that caused this function
  14871. * to be called
  14872. */
  14873. handleClick(event) {
  14874. if (isNaN(this.player_.duration())) {
  14875. return;
  14876. }
  14877. const currentVideoTime = this.player_.currentTime();
  14878. const liveTracker = this.player_.liveTracker;
  14879. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  14880. let newTime;
  14881. if (currentVideoTime + this.skipTime <= duration) {
  14882. newTime = currentVideoTime + this.skipTime;
  14883. } else {
  14884. newTime = duration;
  14885. }
  14886. this.player_.currentTime(newTime);
  14887. }
  14888. /**
  14889. * Update control text on languagechange
  14890. */
  14891. handleLanguagechange() {
  14892. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  14893. }
  14894. }
  14895. SkipForward.prototype.controlText_ = 'Skip Forward';
  14896. Component.registerComponent('SkipForward', SkipForward);
  14897. /**
  14898. * Button to skip backward a configurable amount of time
  14899. * through a video. Renders in the control bar.
  14900. *
  14901. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  14902. *
  14903. * @extends Button
  14904. */
  14905. class SkipBackward extends Button {
  14906. constructor(player, options) {
  14907. super(player, options);
  14908. this.validOptions = [5, 10, 30];
  14909. this.skipTime = this.getSkipBackwardTime();
  14910. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  14911. this.setIcon(`replay-${this.skipTime}`);
  14912. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime.toLocaleString(player.language())]));
  14913. this.show();
  14914. } else {
  14915. this.hide();
  14916. }
  14917. }
  14918. getSkipBackwardTime() {
  14919. const playerOptions = this.options_.playerOptions;
  14920. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  14921. }
  14922. buildCSSClass() {
  14923. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  14924. }
  14925. /**
  14926. * On click, skips backward in the video by a configurable amount of seconds.
  14927. * If the current time in the video is less than the configured 'skip backward' time,
  14928. * skips to beginning of video or seekable range.
  14929. *
  14930. * Handle a click on a `SkipBackward` button
  14931. *
  14932. * @param {EventTarget~Event} event
  14933. * The `click` event that caused this function
  14934. * to be called
  14935. */
  14936. handleClick(event) {
  14937. const currentVideoTime = this.player_.currentTime();
  14938. const liveTracker = this.player_.liveTracker;
  14939. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  14940. let newTime;
  14941. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  14942. newTime = seekableStart;
  14943. } else if (currentVideoTime >= this.skipTime) {
  14944. newTime = currentVideoTime - this.skipTime;
  14945. } else {
  14946. newTime = 0;
  14947. }
  14948. this.player_.currentTime(newTime);
  14949. }
  14950. /**
  14951. * Update control text on languagechange
  14952. */
  14953. handleLanguagechange() {
  14954. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  14955. }
  14956. }
  14957. SkipBackward.prototype.controlText_ = 'Skip Backward';
  14958. Component.registerComponent('SkipBackward', SkipBackward);
  14959. /**
  14960. * @file menu.js
  14961. */
  14962. /** @import Player from '../player' */
  14963. /**
  14964. * The Menu component is used to build popup menus, including subtitle and
  14965. * captions selection menus.
  14966. *
  14967. * @extends Component
  14968. */
  14969. class Menu extends Component {
  14970. /**
  14971. * Create an instance of this class.
  14972. *
  14973. * @param {Player} player
  14974. * the player that this component should attach to
  14975. *
  14976. * @param {Object} [options]
  14977. * Object of option names and values
  14978. *
  14979. */
  14980. constructor(player, options) {
  14981. super(player, options);
  14982. if (options) {
  14983. this.menuButton_ = options.menuButton;
  14984. }
  14985. this.focusedChild_ = -1;
  14986. this.on('keydown', e => this.handleKeyDown(e));
  14987. // All the menu item instances share the same blur handler provided by the menu container.
  14988. this.boundHandleBlur_ = e => this.handleBlur(e);
  14989. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  14990. }
  14991. /**
  14992. * Add event listeners to the {@link MenuItem}.
  14993. *
  14994. * @param {Object} component
  14995. * The instance of the `MenuItem` to add listeners to.
  14996. *
  14997. */
  14998. addEventListenerForItem(component) {
  14999. if (!(component instanceof Component)) {
  15000. return;
  15001. }
  15002. this.on(component, 'blur', this.boundHandleBlur_);
  15003. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  15004. }
  15005. /**
  15006. * Remove event listeners from the {@link MenuItem}.
  15007. *
  15008. * @param {Object} component
  15009. * The instance of the `MenuItem` to remove listeners.
  15010. *
  15011. */
  15012. removeEventListenerForItem(component) {
  15013. if (!(component instanceof Component)) {
  15014. return;
  15015. }
  15016. this.off(component, 'blur', this.boundHandleBlur_);
  15017. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  15018. }
  15019. /**
  15020. * This method will be called indirectly when the component has been added
  15021. * before the component adds to the new menu instance by `addItem`.
  15022. * In this case, the original menu instance will remove the component
  15023. * by calling `removeChild`.
  15024. *
  15025. * @param {Object} component
  15026. * The instance of the `MenuItem`
  15027. */
  15028. removeChild(component) {
  15029. if (typeof component === 'string') {
  15030. component = this.getChild(component);
  15031. }
  15032. this.removeEventListenerForItem(component);
  15033. super.removeChild(component);
  15034. }
  15035. /**
  15036. * Add a {@link MenuItem} to the menu.
  15037. *
  15038. * @param {Object|string} component
  15039. * The name or instance of the `MenuItem` to add.
  15040. *
  15041. */
  15042. addItem(component) {
  15043. const childComponent = this.addChild(component);
  15044. if (childComponent) {
  15045. this.addEventListenerForItem(childComponent);
  15046. }
  15047. }
  15048. /**
  15049. * Create the `Menu`s DOM element.
  15050. *
  15051. * @return {Element}
  15052. * the element that was created
  15053. */
  15054. createEl() {
  15055. const contentElType = this.options_.contentElType || 'ul';
  15056. this.contentEl_ = createEl(contentElType, {
  15057. className: 'vjs-menu-content'
  15058. });
  15059. this.contentEl_.setAttribute('role', 'menu');
  15060. const el = super.createEl('div', {
  15061. append: this.contentEl_,
  15062. className: 'vjs-menu'
  15063. });
  15064. el.appendChild(this.contentEl_);
  15065. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  15066. // where a click on the parent is significant
  15067. on(el, 'click', function (event) {
  15068. event.preventDefault();
  15069. event.stopImmediatePropagation();
  15070. });
  15071. return el;
  15072. }
  15073. dispose() {
  15074. this.contentEl_ = null;
  15075. this.boundHandleBlur_ = null;
  15076. this.boundHandleTapClick_ = null;
  15077. super.dispose();
  15078. }
  15079. /**
  15080. * Called when a `MenuItem` loses focus.
  15081. *
  15082. * @param {Event} event
  15083. * The `blur` event that caused this function to be called.
  15084. *
  15085. * @listens blur
  15086. */
  15087. handleBlur(event) {
  15088. const relatedTarget = event.relatedTarget || document.activeElement;
  15089. // Close menu popup when a user clicks outside the menu
  15090. if (!this.children().some(element => {
  15091. return element.el() === relatedTarget;
  15092. })) {
  15093. const btn = this.menuButton_;
  15094. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  15095. btn.unpressButton();
  15096. }
  15097. }
  15098. }
  15099. /**
  15100. * Called when a `MenuItem` gets clicked or tapped.
  15101. *
  15102. * @param {Event} event
  15103. * The `click` or `tap` event that caused this function to be called.
  15104. *
  15105. * @listens click,tap
  15106. */
  15107. handleTapClick(event) {
  15108. // Unpress the associated MenuButton, and move focus back to it
  15109. if (this.menuButton_) {
  15110. this.menuButton_.unpressButton();
  15111. const childComponents = this.children();
  15112. if (!Array.isArray(childComponents)) {
  15113. return;
  15114. }
  15115. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  15116. if (!foundComponent) {
  15117. return;
  15118. }
  15119. // don't focus menu button if item is a caption settings item
  15120. // because focus will move elsewhere
  15121. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  15122. this.menuButton_.focus();
  15123. }
  15124. }
  15125. }
  15126. /**
  15127. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  15128. *
  15129. * @param {KeyboardEvent} event
  15130. * A `keydown` event that happened on the menu.
  15131. *
  15132. * @listens keydown
  15133. */
  15134. handleKeyDown(event) {
  15135. // Left and Down Arrows
  15136. if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {
  15137. event.preventDefault();
  15138. event.stopPropagation();
  15139. this.stepForward();
  15140. // Up and Right Arrows
  15141. } else if (event.key === 'ArrowRight' || event.key === 'ArrowUp') {
  15142. event.preventDefault();
  15143. event.stopPropagation();
  15144. this.stepBack();
  15145. }
  15146. }
  15147. /**
  15148. * Move to next (lower) menu item for keyboard users.
  15149. */
  15150. stepForward() {
  15151. let stepChild = 0;
  15152. if (this.focusedChild_ !== undefined) {
  15153. stepChild = this.focusedChild_ + 1;
  15154. }
  15155. this.focus(stepChild);
  15156. }
  15157. /**
  15158. * Move to previous (higher) menu item for keyboard users.
  15159. */
  15160. stepBack() {
  15161. let stepChild = 0;
  15162. if (this.focusedChild_ !== undefined) {
  15163. stepChild = this.focusedChild_ - 1;
  15164. }
  15165. this.focus(stepChild);
  15166. }
  15167. /**
  15168. * Set focus on a {@link MenuItem} in the `Menu`.
  15169. *
  15170. * @param {Object|string} [item=0]
  15171. * Index of child item set focus on.
  15172. */
  15173. focus(item = 0) {
  15174. const children = this.children().slice();
  15175. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  15176. if (haveTitle) {
  15177. children.shift();
  15178. }
  15179. if (children.length > 0) {
  15180. if (item < 0) {
  15181. item = 0;
  15182. } else if (item >= children.length) {
  15183. item = children.length - 1;
  15184. }
  15185. this.focusedChild_ = item;
  15186. children[item].el_.focus();
  15187. }
  15188. }
  15189. }
  15190. Component.registerComponent('Menu', Menu);
  15191. /**
  15192. * @file menu-button.js
  15193. */
  15194. /** @import Player from '../player' */
  15195. /**
  15196. * A `MenuButton` class for any popup {@link Menu}.
  15197. *
  15198. * @extends Component
  15199. */
  15200. class MenuButton extends Component {
  15201. /**
  15202. * Creates an instance of this class.
  15203. *
  15204. * @param {Player} player
  15205. * The `Player` that this class should be attached to.
  15206. *
  15207. * @param {Object} [options={}]
  15208. * The key/value store of player options.
  15209. */
  15210. constructor(player, options = {}) {
  15211. super(player, options);
  15212. this.menuButton_ = new Button(player, options);
  15213. this.menuButton_.controlText(this.controlText_);
  15214. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  15215. // Add buildCSSClass values to the button, not the wrapper
  15216. const buttonClass = Button.prototype.buildCSSClass();
  15217. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  15218. this.menuButton_.removeClass('vjs-control');
  15219. this.addChild(this.menuButton_);
  15220. this.update();
  15221. this.enabled_ = true;
  15222. const handleClick = e => this.handleClick(e);
  15223. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  15224. this.on(this.menuButton_, 'tap', handleClick);
  15225. this.on(this.menuButton_, 'click', handleClick);
  15226. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  15227. this.on(this.menuButton_, 'mouseenter', () => {
  15228. this.addClass('vjs-hover');
  15229. this.menu.show();
  15230. on(document, 'keyup', this.handleMenuKeyUp_);
  15231. });
  15232. this.on('mouseleave', e => this.handleMouseLeave(e));
  15233. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  15234. }
  15235. /**
  15236. * Update the menu based on the current state of its items.
  15237. */
  15238. update() {
  15239. const menu = this.createMenu();
  15240. if (this.menu) {
  15241. this.menu.dispose();
  15242. this.removeChild(this.menu);
  15243. }
  15244. this.menu = menu;
  15245. this.addChild(menu);
  15246. /**
  15247. * Track the state of the menu button
  15248. *
  15249. * @type {Boolean}
  15250. * @private
  15251. */
  15252. this.buttonPressed_ = false;
  15253. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15254. if (this.items && this.items.length <= this.hideThreshold_) {
  15255. this.hide();
  15256. this.menu.contentEl_.removeAttribute('role');
  15257. } else {
  15258. this.show();
  15259. this.menu.contentEl_.setAttribute('role', 'menu');
  15260. }
  15261. }
  15262. /**
  15263. * Create the menu and add all items to it.
  15264. *
  15265. * @return {Menu}
  15266. * The constructed menu
  15267. */
  15268. createMenu() {
  15269. const menu = new Menu(this.player_, {
  15270. menuButton: this
  15271. });
  15272. /**
  15273. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  15274. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  15275. * it here because every time we run `createMenu` we need to reset the value.
  15276. *
  15277. * @protected
  15278. * @type {Number}
  15279. */
  15280. this.hideThreshold_ = 0;
  15281. // Add a title list item to the top
  15282. if (this.options_.title) {
  15283. const titleEl = createEl('li', {
  15284. className: 'vjs-menu-title',
  15285. textContent: toTitleCase(this.options_.title),
  15286. tabIndex: -1
  15287. });
  15288. const titleComponent = new Component(this.player_, {
  15289. el: titleEl
  15290. });
  15291. menu.addItem(titleComponent);
  15292. }
  15293. this.items = this.createItems();
  15294. if (this.items) {
  15295. // Add menu items to the menu
  15296. for (let i = 0; i < this.items.length; i++) {
  15297. menu.addItem(this.items[i]);
  15298. }
  15299. }
  15300. return menu;
  15301. }
  15302. /**
  15303. * Create the list of menu items. Specific to each subclass.
  15304. *
  15305. * @abstract
  15306. */
  15307. createItems() {}
  15308. /**
  15309. * Create the `MenuButtons`s DOM element.
  15310. *
  15311. * @return {Element}
  15312. * The element that gets created.
  15313. */
  15314. createEl() {
  15315. return super.createEl('div', {
  15316. className: this.buildWrapperCSSClass()
  15317. }, {});
  15318. }
  15319. /**
  15320. * Overwrites the `setIcon` method from `Component`.
  15321. * In this case, we want the icon to be appended to the menuButton.
  15322. *
  15323. * @param {string} name
  15324. * The icon name to be added.
  15325. */
  15326. setIcon(name) {
  15327. super.setIcon(name, this.menuButton_.el_);
  15328. }
  15329. /**
  15330. * Allow sub components to stack CSS class names for the wrapper element
  15331. *
  15332. * @return {string}
  15333. * The constructed wrapper DOM `className`
  15334. */
  15335. buildWrapperCSSClass() {
  15336. let menuButtonClass = 'vjs-menu-button';
  15337. // If the inline option is passed, we want to use different styles altogether.
  15338. if (this.options_.inline === true) {
  15339. menuButtonClass += '-inline';
  15340. } else {
  15341. menuButtonClass += '-popup';
  15342. }
  15343. // TODO: Fix the CSS so that this isn't necessary
  15344. const buttonClass = Button.prototype.buildCSSClass();
  15345. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  15346. }
  15347. /**
  15348. * Builds the default DOM `className`.
  15349. *
  15350. * @return {string}
  15351. * The DOM `className` for this object.
  15352. */
  15353. buildCSSClass() {
  15354. let menuButtonClass = 'vjs-menu-button';
  15355. // If the inline option is passed, we want to use different styles altogether.
  15356. if (this.options_.inline === true) {
  15357. menuButtonClass += '-inline';
  15358. } else {
  15359. menuButtonClass += '-popup';
  15360. }
  15361. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  15362. }
  15363. /**
  15364. * Get or set the localized control text that will be used for accessibility.
  15365. *
  15366. * > NOTE: This will come from the internal `menuButton_` element.
  15367. *
  15368. * @param {string} [text]
  15369. * Control text for element.
  15370. *
  15371. * @param {Element} [el=this.menuButton_.el()]
  15372. * Element to set the title on.
  15373. *
  15374. * @return {string}
  15375. * - The control text when getting
  15376. */
  15377. controlText(text, el = this.menuButton_.el()) {
  15378. return this.menuButton_.controlText(text, el);
  15379. }
  15380. /**
  15381. * Dispose of the `menu-button` and all child components.
  15382. */
  15383. dispose() {
  15384. this.handleMouseLeave();
  15385. super.dispose();
  15386. }
  15387. /**
  15388. * Handle a click on a `MenuButton`.
  15389. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15390. *
  15391. * @param {Event} event
  15392. * The `keydown`, `tap`, or `click` event that caused this function to be
  15393. * called.
  15394. *
  15395. * @listens tap
  15396. * @listens click
  15397. */
  15398. handleClick(event) {
  15399. if (this.buttonPressed_) {
  15400. this.unpressButton();
  15401. } else {
  15402. this.pressButton();
  15403. }
  15404. }
  15405. /**
  15406. * Handle `mouseleave` for `MenuButton`.
  15407. *
  15408. * @param {Event} event
  15409. * The `mouseleave` event that caused this function to be called.
  15410. *
  15411. * @listens mouseleave
  15412. */
  15413. handleMouseLeave(event) {
  15414. this.removeClass('vjs-hover');
  15415. off(document, 'keyup', this.handleMenuKeyUp_);
  15416. }
  15417. /**
  15418. * Set the focus to the actual button, not to this element
  15419. */
  15420. focus() {
  15421. this.menuButton_.focus();
  15422. }
  15423. /**
  15424. * Remove the focus from the actual button, not this element
  15425. */
  15426. blur() {
  15427. this.menuButton_.blur();
  15428. }
  15429. /**
  15430. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  15431. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15432. *
  15433. * @param {Event} event
  15434. * The `keydown` event that caused this function to be called.
  15435. *
  15436. * @listens keydown
  15437. */
  15438. handleKeyDown(event) {
  15439. // Escape or Tab unpress the 'button'
  15440. if (event.key === 'Escape' || event.key === 'Tab') {
  15441. if (this.buttonPressed_) {
  15442. this.unpressButton();
  15443. }
  15444. // Don't preventDefault for Tab key - we still want to lose focus
  15445. if (!event.key === 'Tab') {
  15446. event.preventDefault();
  15447. // Set focus back to the menu button's button
  15448. this.menuButton_.focus();
  15449. }
  15450. // Up Arrow or Down Arrow also 'press' the button to open the menu
  15451. } else if (event.key === 'Up' || event.key === 'Down' && !(this.player_.options_.playerOptions.spatialNavigation && this.player_.options_.playerOptions.spatialNavigation.enabled)) {
  15452. if (!this.buttonPressed_) {
  15453. event.preventDefault();
  15454. this.pressButton();
  15455. }
  15456. }
  15457. }
  15458. /**
  15459. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  15460. * the constructor.
  15461. *
  15462. * @param {Event} event
  15463. * Key press event
  15464. *
  15465. * @listens keyup
  15466. */
  15467. handleMenuKeyUp(event) {
  15468. // Escape hides popup menu
  15469. if (event.key === 'Escape' || event.key === 'Tab') {
  15470. this.removeClass('vjs-hover');
  15471. }
  15472. }
  15473. /**
  15474. * This method name now delegates to `handleSubmenuKeyDown`. This means
  15475. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  15476. * stop working.
  15477. *
  15478. * @param {Event} event
  15479. * The event that caused this function to be called.
  15480. */
  15481. handleSubmenuKeyPress(event) {
  15482. this.handleSubmenuKeyDown(event);
  15483. }
  15484. /**
  15485. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  15486. * the constructor.
  15487. *
  15488. * @param {Event} event
  15489. * Key press event
  15490. *
  15491. * @listens keydown
  15492. */
  15493. handleSubmenuKeyDown(event) {
  15494. // Escape or Tab unpress the 'button'
  15495. if (event.key === 'Escape' || event.key === 'Tab') {
  15496. if (this.buttonPressed_) {
  15497. this.unpressButton();
  15498. }
  15499. // Don't preventDefault for Tab key - we still want to lose focus
  15500. if (!event.key === 'Tab') {
  15501. event.preventDefault();
  15502. // Set focus back to the menu button's button
  15503. this.menuButton_.focus();
  15504. }
  15505. }
  15506. }
  15507. /**
  15508. * Put the current `MenuButton` into a pressed state.
  15509. */
  15510. pressButton() {
  15511. if (this.enabled_) {
  15512. this.buttonPressed_ = true;
  15513. this.menu.show();
  15514. this.menu.lockShowing();
  15515. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  15516. // set the focus into the submenu, except on iOS where it is resulting in
  15517. // undesired scrolling behavior when the player is in an iframe
  15518. if (IS_IOS && isInFrame()) {
  15519. // Return early so that the menu isn't focused
  15520. return;
  15521. }
  15522. this.menu.focus();
  15523. }
  15524. }
  15525. /**
  15526. * Take the current `MenuButton` out of a pressed state.
  15527. */
  15528. unpressButton() {
  15529. if (this.enabled_) {
  15530. this.buttonPressed_ = false;
  15531. this.menu.unlockShowing();
  15532. this.menu.hide();
  15533. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15534. }
  15535. }
  15536. /**
  15537. * Disable the `MenuButton`. Don't allow it to be clicked.
  15538. */
  15539. disable() {
  15540. this.unpressButton();
  15541. this.enabled_ = false;
  15542. this.addClass('vjs-disabled');
  15543. this.menuButton_.disable();
  15544. }
  15545. /**
  15546. * Enable the `MenuButton`. Allow it to be clicked.
  15547. */
  15548. enable() {
  15549. this.enabled_ = true;
  15550. this.removeClass('vjs-disabled');
  15551. this.menuButton_.enable();
  15552. }
  15553. }
  15554. Component.registerComponent('MenuButton', MenuButton);
  15555. /**
  15556. * @file track-button.js
  15557. */
  15558. /** @import Player from './player' */
  15559. /**
  15560. * The base class for buttons that toggle specific track types (e.g. subtitles).
  15561. *
  15562. * @extends MenuButton
  15563. */
  15564. class TrackButton extends MenuButton {
  15565. /**
  15566. * Creates an instance of this class.
  15567. *
  15568. * @param {Player} player
  15569. * The `Player` that this class should be attached to.
  15570. *
  15571. * @param {Object} [options]
  15572. * The key/value store of player options.
  15573. */
  15574. constructor(player, options) {
  15575. const tracks = options.tracks;
  15576. super(player, options);
  15577. if (this.items.length <= 1) {
  15578. this.hide();
  15579. }
  15580. if (!tracks) {
  15581. return;
  15582. }
  15583. const updateHandler = bind_(this, this.update);
  15584. tracks.addEventListener('removetrack', updateHandler);
  15585. tracks.addEventListener('addtrack', updateHandler);
  15586. tracks.addEventListener('labelchange', updateHandler);
  15587. this.player_.on('ready', updateHandler);
  15588. this.player_.on('dispose', function () {
  15589. tracks.removeEventListener('removetrack', updateHandler);
  15590. tracks.removeEventListener('addtrack', updateHandler);
  15591. tracks.removeEventListener('labelchange', updateHandler);
  15592. });
  15593. }
  15594. }
  15595. Component.registerComponent('TrackButton', TrackButton);
  15596. /**
  15597. * @file menu-item.js
  15598. */
  15599. /** @import Player from '../player' */
  15600. /**
  15601. * The component for a menu item. `<li>`
  15602. *
  15603. * @extends ClickableComponent
  15604. */
  15605. class MenuItem extends ClickableComponent {
  15606. /**
  15607. * Creates an instance of the this class.
  15608. *
  15609. * @param {Player} player
  15610. * The `Player` that this class should be attached to.
  15611. *
  15612. * @param {Object} [options={}]
  15613. * The key/value store of player options.
  15614. *
  15615. */
  15616. constructor(player, options) {
  15617. super(player, options);
  15618. this.selectable = options.selectable;
  15619. this.isSelected_ = options.selected || false;
  15620. this.multiSelectable = options.multiSelectable;
  15621. this.selected(this.isSelected_);
  15622. if (this.selectable) {
  15623. if (this.multiSelectable) {
  15624. this.el_.setAttribute('role', 'menuitemcheckbox');
  15625. } else {
  15626. this.el_.setAttribute('role', 'menuitemradio');
  15627. }
  15628. } else {
  15629. this.el_.setAttribute('role', 'menuitem');
  15630. }
  15631. }
  15632. /**
  15633. * Create the `MenuItem's DOM element
  15634. *
  15635. * @param {string} [type=li]
  15636. * Element's node type, not actually used, always set to `li`.
  15637. *
  15638. * @param {Object} [props={}]
  15639. * An object of properties that should be set on the element
  15640. *
  15641. * @param {Object} [attrs={}]
  15642. * An object of attributes that should be set on the element
  15643. *
  15644. * @return {Element}
  15645. * The element that gets created.
  15646. */
  15647. createEl(type, props, attrs) {
  15648. // The control is textual, not just an icon
  15649. this.nonIconControl = true;
  15650. const el = super.createEl('li', Object.assign({
  15651. className: 'vjs-menu-item',
  15652. tabIndex: -1
  15653. }, props), attrs);
  15654. // swap icon with menu item text.
  15655. const menuItemEl = createEl('span', {
  15656. className: 'vjs-menu-item-text',
  15657. textContent: this.localize(this.options_.label)
  15658. });
  15659. // If using SVG icons, the element with vjs-icon-placeholder will be added separately.
  15660. if (this.player_.options_.experimentalSvgIcons) {
  15661. el.appendChild(menuItemEl);
  15662. } else {
  15663. el.replaceChild(menuItemEl, el.querySelector('.vjs-icon-placeholder'));
  15664. }
  15665. return el;
  15666. }
  15667. /**
  15668. * Ignore keys which are used by the menu, but pass any other ones up. See
  15669. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15670. *
  15671. * @param {KeyboardEvent} event
  15672. * The `keydown` event that caused this function to be called.
  15673. *
  15674. * @listens keydown
  15675. */
  15676. handleKeyDown(event) {
  15677. if (!['Tab', 'Escape', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'].includes(event.key)) {
  15678. // Pass keydown handling up for unused keys
  15679. super.handleKeyDown(event);
  15680. }
  15681. }
  15682. /**
  15683. * Any click on a `MenuItem` puts it into the selected state.
  15684. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15685. *
  15686. * @param {Event} event
  15687. * The `keydown`, `tap`, or `click` event that caused this function to be
  15688. * called.
  15689. *
  15690. * @listens tap
  15691. * @listens click
  15692. */
  15693. handleClick(event) {
  15694. this.selected(true);
  15695. }
  15696. /**
  15697. * Set the state for this menu item as selected or not.
  15698. *
  15699. * @param {boolean} selected
  15700. * if the menu item is selected or not
  15701. */
  15702. selected(selected) {
  15703. if (this.selectable) {
  15704. if (selected) {
  15705. this.addClass('vjs-selected');
  15706. this.el_.setAttribute('aria-checked', 'true');
  15707. // aria-checked isn't fully supported by browsers/screen readers,
  15708. // so indicate selected state to screen reader in the control text.
  15709. this.controlText(', selected');
  15710. this.isSelected_ = true;
  15711. } else {
  15712. this.removeClass('vjs-selected');
  15713. this.el_.setAttribute('aria-checked', 'false');
  15714. // Indicate un-selected state to screen reader
  15715. this.controlText('');
  15716. this.isSelected_ = false;
  15717. }
  15718. }
  15719. }
  15720. }
  15721. Component.registerComponent('MenuItem', MenuItem);
  15722. /**
  15723. * @file text-track-menu-item.js
  15724. */
  15725. /** @import Player from '../../player' */
  15726. /**
  15727. * The specific menu item type for selecting a language within a text track kind
  15728. *
  15729. * @extends MenuItem
  15730. */
  15731. class TextTrackMenuItem extends MenuItem {
  15732. /**
  15733. * Creates an instance of this class.
  15734. *
  15735. * @param {Player} player
  15736. * The `Player` that this class should be attached to.
  15737. *
  15738. * @param {Object} [options]
  15739. * The key/value store of player options.
  15740. */
  15741. constructor(player, options) {
  15742. const track = options.track;
  15743. const tracks = player.textTracks();
  15744. // Modify options for parent MenuItem class's init.
  15745. options.label = track.label || track.language || 'Unknown';
  15746. options.selected = track.mode === 'showing';
  15747. super(player, options);
  15748. this.track = track;
  15749. // Determine the relevant kind(s) of tracks for this component and filter
  15750. // out empty kinds.
  15751. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  15752. const changeHandler = (...args) => {
  15753. this.handleTracksChange.apply(this, args);
  15754. };
  15755. const selectedLanguageChangeHandler = (...args) => {
  15756. this.handleSelectedLanguageChange.apply(this, args);
  15757. };
  15758. player.on(['loadstart', 'texttrackchange'], changeHandler);
  15759. tracks.addEventListener('change', changeHandler);
  15760. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  15761. this.on('dispose', function () {
  15762. player.off(['loadstart', 'texttrackchange'], changeHandler);
  15763. tracks.removeEventListener('change', changeHandler);
  15764. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  15765. });
  15766. // iOS7 doesn't dispatch change events to TextTrackLists when an
  15767. // associated track's mode changes. Without something like
  15768. // Object.observe() (also not present on iOS7), it's not
  15769. // possible to detect changes to the mode attribute and polyfill
  15770. // the change event. As a poor substitute, we manually dispatch
  15771. // change events whenever the controls modify the mode.
  15772. if (tracks.onchange === undefined) {
  15773. let event;
  15774. this.on(['tap', 'click'], function () {
  15775. if (typeof window.Event !== 'object') {
  15776. // Android 2.3 throws an Illegal Constructor error for window.Event
  15777. try {
  15778. event = new window.Event('change');
  15779. } catch (err) {
  15780. // continue regardless of error
  15781. }
  15782. }
  15783. if (!event) {
  15784. event = document.createEvent('Event');
  15785. event.initEvent('change', true, true);
  15786. }
  15787. tracks.dispatchEvent(event);
  15788. });
  15789. }
  15790. // set the default state based on current tracks
  15791. this.handleTracksChange();
  15792. }
  15793. /**
  15794. * This gets called when an `TextTrackMenuItem` is "clicked". See
  15795. * {@link ClickableComponent} for more detailed information on what a click can be.
  15796. *
  15797. * @param {Event} event
  15798. * The `keydown`, `tap`, or `click` event that caused this function to be
  15799. * called.
  15800. *
  15801. * @listens tap
  15802. * @listens click
  15803. */
  15804. handleClick(event) {
  15805. const referenceTrack = this.track;
  15806. const tracks = this.player_.textTracks();
  15807. super.handleClick(event);
  15808. if (!tracks) {
  15809. return;
  15810. }
  15811. for (let i = 0; i < tracks.length; i++) {
  15812. const track = tracks[i];
  15813. // If the track from the text tracks list is not of the right kind,
  15814. // skip it. We do not want to affect tracks of incompatible kind(s).
  15815. if (this.kinds.indexOf(track.kind) === -1) {
  15816. continue;
  15817. }
  15818. // If this text track is the component's track and it is not showing,
  15819. // set it to showing.
  15820. if (track === referenceTrack) {
  15821. if (track.mode !== 'showing') {
  15822. track.mode = 'showing';
  15823. }
  15824. // If this text track is not the component's track and it is not
  15825. // disabled, set it to disabled.
  15826. } else if (track.mode !== 'disabled') {
  15827. track.mode = 'disabled';
  15828. }
  15829. }
  15830. }
  15831. /**
  15832. * Handle text track list change
  15833. *
  15834. * @param {Event} event
  15835. * The `change` event that caused this function to be called.
  15836. *
  15837. * @listens TextTrackList#change
  15838. */
  15839. handleTracksChange(event) {
  15840. const shouldBeSelected = this.track.mode === 'showing';
  15841. // Prevent redundant selected() calls because they may cause
  15842. // screen readers to read the appended control text unnecessarily
  15843. if (shouldBeSelected !== this.isSelected_) {
  15844. this.selected(shouldBeSelected);
  15845. }
  15846. }
  15847. handleSelectedLanguageChange(event) {
  15848. if (this.track.mode === 'showing') {
  15849. const selectedLanguage = this.player_.cache_.selectedLanguage;
  15850. // Don't replace the kind of track across the same language
  15851. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  15852. return;
  15853. }
  15854. this.player_.cache_.selectedLanguage = {
  15855. enabled: true,
  15856. language: this.track.language,
  15857. kind: this.track.kind
  15858. };
  15859. }
  15860. }
  15861. dispose() {
  15862. // remove reference to track object on dispose
  15863. this.track = null;
  15864. super.dispose();
  15865. }
  15866. }
  15867. Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  15868. /**
  15869. * @file off-text-track-menu-item.js
  15870. */
  15871. /** @import Player from '../../player' */
  15872. /**
  15873. * A special menu item for turning off a specific type of text track
  15874. *
  15875. * @extends TextTrackMenuItem
  15876. */
  15877. class OffTextTrackMenuItem extends TextTrackMenuItem {
  15878. /**
  15879. * Creates an instance of this class.
  15880. *
  15881. * @param {Player} player
  15882. * The `Player` that this class should be attached to.
  15883. *
  15884. * @param {Object} [options]
  15885. * The key/value store of player options.
  15886. */
  15887. constructor(player, options) {
  15888. // Create pseudo track info
  15889. // Requires options['kind']
  15890. options.track = {
  15891. player,
  15892. // it is no longer necessary to store `kind` or `kinds` on the track itself
  15893. // since they are now stored in the `kinds` property of all instances of
  15894. // TextTrackMenuItem, but this will remain for backwards compatibility
  15895. kind: options.kind,
  15896. kinds: options.kinds,
  15897. default: false,
  15898. mode: 'disabled'
  15899. };
  15900. if (!options.kinds) {
  15901. options.kinds = [options.kind];
  15902. }
  15903. if (options.label) {
  15904. options.track.label = options.label;
  15905. } else {
  15906. options.track.label = options.kinds.join(' and ') + ' off';
  15907. }
  15908. // MenuItem is selectable
  15909. options.selectable = true;
  15910. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  15911. options.multiSelectable = false;
  15912. super(player, options);
  15913. }
  15914. /**
  15915. * Handle text track change
  15916. *
  15917. * @param {Event} event
  15918. * The event that caused this function to run
  15919. */
  15920. handleTracksChange(event) {
  15921. const tracks = this.player().textTracks();
  15922. let shouldBeSelected = true;
  15923. for (let i = 0, l = tracks.length; i < l; i++) {
  15924. const track = tracks[i];
  15925. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  15926. shouldBeSelected = false;
  15927. break;
  15928. }
  15929. }
  15930. // Prevent redundant selected() calls because they may cause
  15931. // screen readers to read the appended control text unnecessarily
  15932. if (shouldBeSelected !== this.isSelected_) {
  15933. this.selected(shouldBeSelected);
  15934. }
  15935. }
  15936. handleSelectedLanguageChange(event) {
  15937. const tracks = this.player().textTracks();
  15938. let allHidden = true;
  15939. for (let i = 0, l = tracks.length; i < l; i++) {
  15940. const track = tracks[i];
  15941. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  15942. allHidden = false;
  15943. break;
  15944. }
  15945. }
  15946. if (allHidden) {
  15947. this.player_.cache_.selectedLanguage = {
  15948. enabled: false
  15949. };
  15950. }
  15951. }
  15952. /**
  15953. * Update control text and label on languagechange
  15954. */
  15955. handleLanguagechange() {
  15956. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  15957. super.handleLanguagechange();
  15958. }
  15959. }
  15960. Component.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  15961. /**
  15962. * @file text-track-button.js
  15963. */
  15964. /** @import Player from '../../player' */
  15965. /**
  15966. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  15967. *
  15968. * @extends MenuButton
  15969. */
  15970. class TextTrackButton extends TrackButton {
  15971. /**
  15972. * Creates an instance of this class.
  15973. *
  15974. * @param {Player} player
  15975. * The `Player` that this class should be attached to.
  15976. *
  15977. * @param {Object} [options={}]
  15978. * The key/value store of player options.
  15979. */
  15980. constructor(player, options = {}) {
  15981. options.tracks = player.textTracks();
  15982. super(player, options);
  15983. }
  15984. /**
  15985. * Create a menu item for each text track
  15986. *
  15987. * @param {TextTrackMenuItem[]} [items=[]]
  15988. * Existing array of items to use during creation
  15989. *
  15990. * @return {TextTrackMenuItem[]}
  15991. * Array of menu items that were created
  15992. */
  15993. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  15994. // Label is an override for the [track] off label
  15995. // USed to localise captions/subtitles
  15996. let label;
  15997. if (this.label_) {
  15998. label = `${this.label_} off`;
  15999. }
  16000. // Add an OFF menu item to turn all tracks off
  16001. items.push(new OffTextTrackMenuItem(this.player_, {
  16002. kinds: this.kinds_,
  16003. kind: this.kind_,
  16004. label
  16005. }));
  16006. this.hideThreshold_ += 1;
  16007. const tracks = this.player_.textTracks();
  16008. if (!Array.isArray(this.kinds_)) {
  16009. this.kinds_ = [this.kind_];
  16010. }
  16011. for (let i = 0; i < tracks.length; i++) {
  16012. const track = tracks[i];
  16013. // only add tracks that are of an appropriate kind and have a label
  16014. if (this.kinds_.indexOf(track.kind) > -1) {
  16015. const item = new TrackMenuItem(this.player_, {
  16016. track,
  16017. kinds: this.kinds_,
  16018. kind: this.kind_,
  16019. // MenuItem is selectable
  16020. selectable: true,
  16021. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16022. multiSelectable: false
  16023. });
  16024. item.addClass(`vjs-${track.kind}-menu-item`);
  16025. items.push(item);
  16026. }
  16027. }
  16028. return items;
  16029. }
  16030. }
  16031. Component.registerComponent('TextTrackButton', TextTrackButton);
  16032. /**
  16033. * @file chapters-track-menu-item.js
  16034. */
  16035. /** @import Player from '../../player' */
  16036. /**
  16037. * The chapter track menu item
  16038. *
  16039. * @extends MenuItem
  16040. */
  16041. class ChaptersTrackMenuItem extends MenuItem {
  16042. /**
  16043. * Creates an instance of this class.
  16044. *
  16045. * @param {Player} player
  16046. * The `Player` that this class should be attached to.
  16047. *
  16048. * @param {Object} [options]
  16049. * The key/value store of player options.
  16050. */
  16051. constructor(player, options) {
  16052. const track = options.track;
  16053. const cue = options.cue;
  16054. const currentTime = player.currentTime();
  16055. // Modify options for parent MenuItem class's init.
  16056. options.selectable = true;
  16057. options.multiSelectable = false;
  16058. options.label = cue.text;
  16059. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  16060. super(player, options);
  16061. this.track = track;
  16062. this.cue = cue;
  16063. }
  16064. /**
  16065. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  16066. * {@link ClickableComponent} for more detailed information on what a click can be.
  16067. *
  16068. * @param {Event} [event]
  16069. * The `keydown`, `tap`, or `click` event that caused this function to be
  16070. * called.
  16071. *
  16072. * @listens tap
  16073. * @listens click
  16074. */
  16075. handleClick(event) {
  16076. super.handleClick();
  16077. this.player_.currentTime(this.cue.startTime);
  16078. }
  16079. }
  16080. Component.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  16081. /**
  16082. * @file chapters-button.js
  16083. */
  16084. /** @import Player from '../../player' */
  16085. /** @import Menu from '../../menu/menu' */
  16086. /** @import TextTrack from '../../tracks/text-track' */
  16087. /** @import TextTrackMenuItem from '../text-track-controls/text-track-menu-item' */
  16088. /**
  16089. * The button component for toggling and selecting chapters
  16090. * Chapters act much differently than other text tracks
  16091. * Cues are navigation vs. other tracks of alternative languages
  16092. *
  16093. * @extends TextTrackButton
  16094. */
  16095. class ChaptersButton extends TextTrackButton {
  16096. /**
  16097. * Creates an instance of this class.
  16098. *
  16099. * @param {Player} player
  16100. * The `Player` that this class should be attached to.
  16101. *
  16102. * @param {Object} [options]
  16103. * The key/value store of player options.
  16104. *
  16105. * @param {Function} [ready]
  16106. * The function to call when this function is ready.
  16107. */
  16108. constructor(player, options, ready) {
  16109. super(player, options, ready);
  16110. this.setIcon('chapters');
  16111. this.selectCurrentItem_ = () => {
  16112. this.items.forEach(item => {
  16113. item.selected(this.track_.activeCues[0] === item.cue);
  16114. });
  16115. };
  16116. }
  16117. /**
  16118. * Builds the default DOM `className`.
  16119. *
  16120. * @return {string}
  16121. * The DOM `className` for this object.
  16122. */
  16123. buildCSSClass() {
  16124. return `vjs-chapters-button ${super.buildCSSClass()}`;
  16125. }
  16126. buildWrapperCSSClass() {
  16127. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  16128. }
  16129. /**
  16130. * Update the menu based on the current state of its items.
  16131. *
  16132. * @param {Event} [event]
  16133. * An event that triggered this function to run.
  16134. *
  16135. * @listens TextTrackList#addtrack
  16136. * @listens TextTrackList#removetrack
  16137. * @listens TextTrackList#change
  16138. */
  16139. update(event) {
  16140. if (event && event.track && event.track.kind !== 'chapters') {
  16141. return;
  16142. }
  16143. const track = this.findChaptersTrack();
  16144. if (track !== this.track_) {
  16145. this.setTrack(track);
  16146. super.update();
  16147. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  16148. // Update the menu initially or if the number of cues has changed since set
  16149. super.update();
  16150. }
  16151. }
  16152. /**
  16153. * Set the currently selected track for the chapters button.
  16154. *
  16155. * @param {TextTrack} track
  16156. * The new track to select. Nothing will change if this is the currently selected
  16157. * track.
  16158. */
  16159. setTrack(track) {
  16160. if (this.track_ === track) {
  16161. return;
  16162. }
  16163. if (!this.updateHandler_) {
  16164. this.updateHandler_ = this.update.bind(this);
  16165. }
  16166. // here this.track_ refers to the old track instance
  16167. if (this.track_) {
  16168. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16169. if (remoteTextTrackEl) {
  16170. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  16171. }
  16172. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  16173. this.track_ = null;
  16174. }
  16175. this.track_ = track;
  16176. // here this.track_ refers to the new track instance
  16177. if (this.track_) {
  16178. this.track_.mode = 'hidden';
  16179. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16180. if (remoteTextTrackEl) {
  16181. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  16182. }
  16183. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  16184. }
  16185. }
  16186. /**
  16187. * Find the track object that is currently in use by this ChaptersButton
  16188. *
  16189. * @return {TextTrack|undefined}
  16190. * The current track or undefined if none was found.
  16191. */
  16192. findChaptersTrack() {
  16193. const tracks = this.player_.textTracks() || [];
  16194. for (let i = tracks.length - 1; i >= 0; i--) {
  16195. // We will always choose the last track as our chaptersTrack
  16196. const track = tracks[i];
  16197. if (track.kind === this.kind_) {
  16198. return track;
  16199. }
  16200. }
  16201. }
  16202. /**
  16203. * Get the caption for the ChaptersButton based on the track label. This will also
  16204. * use the current tracks localized kind as a fallback if a label does not exist.
  16205. *
  16206. * @return {string}
  16207. * The tracks current label or the localized track kind.
  16208. */
  16209. getMenuCaption() {
  16210. if (this.track_ && this.track_.label) {
  16211. return this.track_.label;
  16212. }
  16213. return this.localize(toTitleCase(this.kind_));
  16214. }
  16215. /**
  16216. * Create menu from chapter track
  16217. *
  16218. * @return {Menu}
  16219. * New menu for the chapter buttons
  16220. */
  16221. createMenu() {
  16222. this.options_.title = this.getMenuCaption();
  16223. return super.createMenu();
  16224. }
  16225. /**
  16226. * Create a menu item for each text track
  16227. *
  16228. * @return {TextTrackMenuItem[]}
  16229. * Array of menu items
  16230. */
  16231. createItems() {
  16232. const items = [];
  16233. if (!this.track_) {
  16234. return items;
  16235. }
  16236. const cues = this.track_.cues;
  16237. if (!cues) {
  16238. return items;
  16239. }
  16240. for (let i = 0, l = cues.length; i < l; i++) {
  16241. const cue = cues[i];
  16242. const mi = new ChaptersTrackMenuItem(this.player_, {
  16243. track: this.track_,
  16244. cue
  16245. });
  16246. items.push(mi);
  16247. }
  16248. return items;
  16249. }
  16250. }
  16251. /**
  16252. * `kind` of TextTrack to look for to associate it with this menu.
  16253. *
  16254. * @type {string}
  16255. * @private
  16256. */
  16257. ChaptersButton.prototype.kind_ = 'chapters';
  16258. /**
  16259. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  16260. *
  16261. * @type {string}
  16262. * @protected
  16263. */
  16264. ChaptersButton.prototype.controlText_ = 'Chapters';
  16265. Component.registerComponent('ChaptersButton', ChaptersButton);
  16266. /**
  16267. * @file descriptions-button.js
  16268. */
  16269. /** @import Player from '../../player' */
  16270. /**
  16271. * The button component for toggling and selecting descriptions
  16272. *
  16273. * @extends TextTrackButton
  16274. */
  16275. class DescriptionsButton extends TextTrackButton {
  16276. /**
  16277. * Creates an instance of this class.
  16278. *
  16279. * @param {Player} player
  16280. * The `Player` that this class should be attached to.
  16281. *
  16282. * @param {Object} [options]
  16283. * The key/value store of player options.
  16284. *
  16285. * @param {Function} [ready]
  16286. * The function to call when this component is ready.
  16287. */
  16288. constructor(player, options, ready) {
  16289. super(player, options, ready);
  16290. this.setIcon('audio-description');
  16291. const tracks = player.textTracks();
  16292. const changeHandler = bind_(this, this.handleTracksChange);
  16293. tracks.addEventListener('change', changeHandler);
  16294. this.on('dispose', function () {
  16295. tracks.removeEventListener('change', changeHandler);
  16296. });
  16297. }
  16298. /**
  16299. * Handle text track change
  16300. *
  16301. * @param {Event} event
  16302. * The event that caused this function to run
  16303. *
  16304. * @listens TextTrackList#change
  16305. */
  16306. handleTracksChange(event) {
  16307. const tracks = this.player().textTracks();
  16308. let disabled = false;
  16309. // Check whether a track of a different kind is showing
  16310. for (let i = 0, l = tracks.length; i < l; i++) {
  16311. const track = tracks[i];
  16312. if (track.kind !== this.kind_ && track.mode === 'showing') {
  16313. disabled = true;
  16314. break;
  16315. }
  16316. }
  16317. // If another track is showing, disable this menu button
  16318. if (disabled) {
  16319. this.disable();
  16320. } else {
  16321. this.enable();
  16322. }
  16323. }
  16324. /**
  16325. * Builds the default DOM `className`.
  16326. *
  16327. * @return {string}
  16328. * The DOM `className` for this object.
  16329. */
  16330. buildCSSClass() {
  16331. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  16332. }
  16333. buildWrapperCSSClass() {
  16334. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  16335. }
  16336. }
  16337. /**
  16338. * `kind` of TextTrack to look for to associate it with this menu.
  16339. *
  16340. * @type {string}
  16341. * @private
  16342. */
  16343. DescriptionsButton.prototype.kind_ = 'descriptions';
  16344. /**
  16345. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  16346. *
  16347. * @type {string}
  16348. * @protected
  16349. */
  16350. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  16351. Component.registerComponent('DescriptionsButton', DescriptionsButton);
  16352. /**
  16353. * @file subtitles-button.js
  16354. */
  16355. /** @import Player from '../../player' */
  16356. /**
  16357. * The button component for toggling and selecting subtitles
  16358. *
  16359. * @extends TextTrackButton
  16360. */
  16361. class SubtitlesButton extends TextTrackButton {
  16362. /**
  16363. * Creates an instance of this class.
  16364. *
  16365. * @param {Player} player
  16366. * The `Player` that this class should be attached to.
  16367. *
  16368. * @param {Object} [options]
  16369. * The key/value store of player options.
  16370. *
  16371. * @param {Function} [ready]
  16372. * The function to call when this component is ready.
  16373. */
  16374. constructor(player, options, ready) {
  16375. super(player, options, ready);
  16376. this.setIcon('subtitles');
  16377. }
  16378. /**
  16379. * Builds the default DOM `className`.
  16380. *
  16381. * @return {string}
  16382. * The DOM `className` for this object.
  16383. */
  16384. buildCSSClass() {
  16385. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  16386. }
  16387. buildWrapperCSSClass() {
  16388. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  16389. }
  16390. }
  16391. /**
  16392. * `kind` of TextTrack to look for to associate it with this menu.
  16393. *
  16394. * @type {string}
  16395. * @private
  16396. */
  16397. SubtitlesButton.prototype.kind_ = 'subtitles';
  16398. /**
  16399. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  16400. *
  16401. * @type {string}
  16402. * @protected
  16403. */
  16404. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  16405. Component.registerComponent('SubtitlesButton', SubtitlesButton);
  16406. /**
  16407. * @file caption-settings-menu-item.js
  16408. */
  16409. /** @import Player from '../../player' */
  16410. /**
  16411. * The menu item for caption track settings menu
  16412. *
  16413. * @extends TextTrackMenuItem
  16414. */
  16415. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  16416. /**
  16417. * Creates an instance of this class.
  16418. *
  16419. * @param {Player} player
  16420. * The `Player` that this class should be attached to.
  16421. *
  16422. * @param {Object} [options]
  16423. * The key/value store of player options.
  16424. */
  16425. constructor(player, options) {
  16426. options.track = {
  16427. player,
  16428. kind: options.kind,
  16429. label: options.kind + ' settings',
  16430. selectable: false,
  16431. default: false,
  16432. mode: 'disabled'
  16433. };
  16434. // CaptionSettingsMenuItem has no concept of 'selected'
  16435. options.selectable = false;
  16436. options.name = 'CaptionSettingsMenuItem';
  16437. super(player, options);
  16438. this.addClass('vjs-texttrack-settings');
  16439. this.controlText(', opens ' + options.kind + ' settings dialog');
  16440. }
  16441. /**
  16442. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  16443. * {@link ClickableComponent} for more detailed information on what a click can be.
  16444. *
  16445. * @param {Event} [event]
  16446. * The `keydown`, `tap`, or `click` event that caused this function to be
  16447. * called.
  16448. *
  16449. * @listens tap
  16450. * @listens click
  16451. */
  16452. handleClick(event) {
  16453. this.player().getChild('textTrackSettings').open();
  16454. }
  16455. /**
  16456. * Update control text and label on languagechange
  16457. */
  16458. handleLanguagechange() {
  16459. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  16460. super.handleLanguagechange();
  16461. }
  16462. }
  16463. Component.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  16464. /**
  16465. * @file captions-button.js
  16466. */
  16467. /** @import Player from '../../player' */
  16468. /**
  16469. * The button component for toggling and selecting captions
  16470. *
  16471. * @extends TextTrackButton
  16472. */
  16473. class CaptionsButton extends TextTrackButton {
  16474. /**
  16475. * Creates an instance of this class.
  16476. *
  16477. * @param {Player} player
  16478. * The `Player` that this class should be attached to.
  16479. *
  16480. * @param {Object} [options]
  16481. * The key/value store of player options.
  16482. *
  16483. * @param {Function} [ready]
  16484. * The function to call when this component is ready.
  16485. */
  16486. constructor(player, options, ready) {
  16487. super(player, options, ready);
  16488. this.setIcon('captions');
  16489. }
  16490. /**
  16491. * Builds the default DOM `className`.
  16492. *
  16493. * @return {string}
  16494. * The DOM `className` for this object.
  16495. */
  16496. buildCSSClass() {
  16497. return `vjs-captions-button ${super.buildCSSClass()}`;
  16498. }
  16499. buildWrapperCSSClass() {
  16500. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  16501. }
  16502. /**
  16503. * Create caption menu items
  16504. *
  16505. * @return {CaptionSettingsMenuItem[]}
  16506. * The array of current menu items.
  16507. */
  16508. createItems() {
  16509. const items = [];
  16510. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  16511. items.push(new CaptionSettingsMenuItem(this.player_, {
  16512. kind: this.kind_
  16513. }));
  16514. this.hideThreshold_ += 1;
  16515. }
  16516. return super.createItems(items);
  16517. }
  16518. }
  16519. /**
  16520. * `kind` of TextTrack to look for to associate it with this menu.
  16521. *
  16522. * @type {string}
  16523. * @private
  16524. */
  16525. CaptionsButton.prototype.kind_ = 'captions';
  16526. /**
  16527. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  16528. *
  16529. * @type {string}
  16530. * @protected
  16531. */
  16532. CaptionsButton.prototype.controlText_ = 'Captions';
  16533. Component.registerComponent('CaptionsButton', CaptionsButton);
  16534. /**
  16535. * @file subs-caps-menu-item.js
  16536. */
  16537. /**
  16538. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  16539. * in the SubsCapsMenu.
  16540. *
  16541. * @extends TextTrackMenuItem
  16542. */
  16543. class SubsCapsMenuItem extends TextTrackMenuItem {
  16544. createEl(type, props, attrs) {
  16545. const el = super.createEl(type, props, attrs);
  16546. const parentSpan = el.querySelector('.vjs-menu-item-text');
  16547. if (this.options_.track.kind === 'captions') {
  16548. if (this.player_.options_.experimentalSvgIcons) {
  16549. this.setIcon('captions', el);
  16550. } else {
  16551. parentSpan.appendChild(createEl('span', {
  16552. className: 'vjs-icon-placeholder'
  16553. }, {
  16554. 'aria-hidden': true
  16555. }));
  16556. }
  16557. parentSpan.appendChild(createEl('span', {
  16558. className: 'vjs-control-text',
  16559. // space added as the text will visually flow with the
  16560. // label
  16561. textContent: ` ${this.localize('Captions')}`
  16562. }));
  16563. }
  16564. return el;
  16565. }
  16566. }
  16567. Component.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  16568. /**
  16569. * @file sub-caps-button.js
  16570. */
  16571. /** @import Player from '../../player' */
  16572. /**
  16573. * The button component for toggling and selecting captions and/or subtitles
  16574. *
  16575. * @extends TextTrackButton
  16576. */
  16577. class SubsCapsButton extends TextTrackButton {
  16578. /**
  16579. * Creates an instance of this class.
  16580. *
  16581. * @param {Player} player
  16582. * The `Player` that this class should be attached to.
  16583. *
  16584. * @param {Object} [options]
  16585. * The key/value store of player options.
  16586. *
  16587. * @param {Function} [ready]
  16588. * The function to call when this component is ready.
  16589. */
  16590. constructor(player, options = {}) {
  16591. super(player, options);
  16592. // Although North America uses "captions" in most cases for
  16593. // "captions and subtitles" other locales use "subtitles"
  16594. this.label_ = 'subtitles';
  16595. this.setIcon('subtitles');
  16596. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  16597. this.label_ = 'captions';
  16598. this.setIcon('captions');
  16599. }
  16600. this.menuButton_.controlText(toTitleCase(this.label_));
  16601. }
  16602. /**
  16603. * Builds the default DOM `className`.
  16604. *
  16605. * @return {string}
  16606. * The DOM `className` for this object.
  16607. */
  16608. buildCSSClass() {
  16609. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  16610. }
  16611. buildWrapperCSSClass() {
  16612. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  16613. }
  16614. /**
  16615. * Create caption/subtitles menu items
  16616. *
  16617. * @return {CaptionSettingsMenuItem[]}
  16618. * The array of current menu items.
  16619. */
  16620. createItems() {
  16621. let items = [];
  16622. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  16623. items.push(new CaptionSettingsMenuItem(this.player_, {
  16624. kind: this.label_
  16625. }));
  16626. this.hideThreshold_ += 1;
  16627. }
  16628. items = super.createItems(items, SubsCapsMenuItem);
  16629. return items;
  16630. }
  16631. }
  16632. /**
  16633. * `kind`s of TextTrack to look for to associate it with this menu.
  16634. *
  16635. * @type {array}
  16636. * @private
  16637. */
  16638. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  16639. /**
  16640. * The text that should display over the `SubsCapsButton`s controls.
  16641. *
  16642. *
  16643. * @type {string}
  16644. * @protected
  16645. */
  16646. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  16647. Component.registerComponent('SubsCapsButton', SubsCapsButton);
  16648. /**
  16649. * @file audio-track-menu-item.js
  16650. */
  16651. /** @import Player from '../../player' */
  16652. /**
  16653. * An {@link AudioTrack} {@link MenuItem}
  16654. *
  16655. * @extends MenuItem
  16656. */
  16657. class AudioTrackMenuItem extends MenuItem {
  16658. /**
  16659. * Creates an instance of this class.
  16660. *
  16661. * @param {Player} player
  16662. * The `Player` that this class should be attached to.
  16663. *
  16664. * @param {Object} [options]
  16665. * The key/value store of player options.
  16666. */
  16667. constructor(player, options) {
  16668. const track = options.track;
  16669. const tracks = player.audioTracks();
  16670. // Modify options for parent MenuItem class's init.
  16671. options.label = track.label || track.language || 'Unknown';
  16672. options.selected = track.enabled;
  16673. super(player, options);
  16674. this.track = track;
  16675. this.addClass(`vjs-${track.kind}-menu-item`);
  16676. const changeHandler = (...args) => {
  16677. this.handleTracksChange.apply(this, args);
  16678. };
  16679. tracks.addEventListener('change', changeHandler);
  16680. this.on('dispose', () => {
  16681. tracks.removeEventListener('change', changeHandler);
  16682. });
  16683. }
  16684. createEl(type, props, attrs) {
  16685. const el = super.createEl(type, props, attrs);
  16686. const parentSpan = el.querySelector('.vjs-menu-item-text');
  16687. if (['main-desc', 'descriptions'].indexOf(this.options_.track.kind) >= 0) {
  16688. parentSpan.appendChild(createEl('span', {
  16689. className: 'vjs-icon-placeholder'
  16690. }, {
  16691. 'aria-hidden': true
  16692. }));
  16693. parentSpan.appendChild(createEl('span', {
  16694. className: 'vjs-control-text',
  16695. textContent: ' ' + this.localize('Descriptions')
  16696. }));
  16697. }
  16698. return el;
  16699. }
  16700. /**
  16701. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  16702. * for more detailed information on what a click can be.
  16703. *
  16704. * @param {Event} [event]
  16705. * The `keydown`, `tap`, or `click` event that caused this function to be
  16706. * called.
  16707. *
  16708. * @listens tap
  16709. * @listens click
  16710. */
  16711. handleClick(event) {
  16712. super.handleClick(event);
  16713. // the audio track list will automatically toggle other tracks
  16714. // off for us.
  16715. this.track.enabled = true;
  16716. // when native audio tracks are used, we want to make sure that other tracks are turned off
  16717. if (this.player_.tech_.featuresNativeAudioTracks) {
  16718. const tracks = this.player_.audioTracks();
  16719. for (let i = 0; i < tracks.length; i++) {
  16720. const track = tracks[i];
  16721. // skip the current track since we enabled it above
  16722. if (track === this.track) {
  16723. continue;
  16724. }
  16725. track.enabled = track === this.track;
  16726. }
  16727. }
  16728. }
  16729. /**
  16730. * Handle any {@link AudioTrack} change.
  16731. *
  16732. * @param {Event} [event]
  16733. * The {@link AudioTrackList#change} event that caused this to run.
  16734. *
  16735. * @listens AudioTrackList#change
  16736. */
  16737. handleTracksChange(event) {
  16738. this.selected(this.track.enabled);
  16739. }
  16740. }
  16741. Component.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  16742. /**
  16743. * @file audio-track-button.js
  16744. */
  16745. /**
  16746. * The base class for buttons that toggle specific {@link AudioTrack} types.
  16747. *
  16748. * @extends TrackButton
  16749. */
  16750. class AudioTrackButton extends TrackButton {
  16751. /**
  16752. * Creates an instance of this class.
  16753. *
  16754. * @param {Player} player
  16755. * The `Player` that this class should be attached to.
  16756. *
  16757. * @param {Object} [options={}]
  16758. * The key/value store of player options.
  16759. */
  16760. constructor(player, options = {}) {
  16761. options.tracks = player.audioTracks();
  16762. super(player, options);
  16763. this.setIcon('audio');
  16764. }
  16765. /**
  16766. * Builds the default DOM `className`.
  16767. *
  16768. * @return {string}
  16769. * The DOM `className` for this object.
  16770. */
  16771. buildCSSClass() {
  16772. return `vjs-audio-button ${super.buildCSSClass()}`;
  16773. }
  16774. buildWrapperCSSClass() {
  16775. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  16776. }
  16777. /**
  16778. * Create a menu item for each audio track
  16779. *
  16780. * @param {AudioTrackMenuItem[]} [items=[]]
  16781. * An array of existing menu items to use.
  16782. *
  16783. * @return {AudioTrackMenuItem[]}
  16784. * An array of menu items
  16785. */
  16786. createItems(items = []) {
  16787. // if there's only one audio track, there no point in showing it
  16788. this.hideThreshold_ = 1;
  16789. const tracks = this.player_.audioTracks();
  16790. for (let i = 0; i < tracks.length; i++) {
  16791. const track = tracks[i];
  16792. items.push(new AudioTrackMenuItem(this.player_, {
  16793. track,
  16794. // MenuItem is selectable
  16795. selectable: true,
  16796. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16797. multiSelectable: false
  16798. }));
  16799. }
  16800. return items;
  16801. }
  16802. }
  16803. /**
  16804. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  16805. *
  16806. * @type {string}
  16807. * @protected
  16808. */
  16809. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  16810. Component.registerComponent('AudioTrackButton', AudioTrackButton);
  16811. /**
  16812. * @file playback-rate-menu-item.js
  16813. */
  16814. /** @import Player from '../../player' */
  16815. /**
  16816. * The specific menu item type for selecting a playback rate.
  16817. *
  16818. * @extends MenuItem
  16819. */
  16820. class PlaybackRateMenuItem extends MenuItem {
  16821. /**
  16822. * Creates an instance of this class.
  16823. *
  16824. * @param {Player} player
  16825. * The `Player` that this class should be attached to.
  16826. *
  16827. * @param {Object} [options]
  16828. * The key/value store of player options.
  16829. */
  16830. constructor(player, options) {
  16831. const label = options.rate;
  16832. const rate = parseFloat(label, 10);
  16833. // Modify options for parent MenuItem class's init.
  16834. options.label = label;
  16835. options.selected = rate === player.playbackRate();
  16836. options.selectable = true;
  16837. options.multiSelectable = false;
  16838. super(player, options);
  16839. this.label = label;
  16840. this.rate = rate;
  16841. this.on(player, 'ratechange', e => this.update(e));
  16842. }
  16843. /**
  16844. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  16845. * {@link ClickableComponent} for more detailed information on what a click can be.
  16846. *
  16847. * @param {Event} [event]
  16848. * The `keydown`, `tap`, or `click` event that caused this function to be
  16849. * called.
  16850. *
  16851. * @listens tap
  16852. * @listens click
  16853. */
  16854. handleClick(event) {
  16855. super.handleClick();
  16856. this.player().playbackRate(this.rate);
  16857. }
  16858. /**
  16859. * Update the PlaybackRateMenuItem when the playbackrate changes.
  16860. *
  16861. * @param {Event} [event]
  16862. * The `ratechange` event that caused this function to run.
  16863. *
  16864. * @listens Player#ratechange
  16865. */
  16866. update(event) {
  16867. this.selected(this.player().playbackRate() === this.rate);
  16868. }
  16869. }
  16870. /**
  16871. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  16872. *
  16873. * @type {string}
  16874. * @private
  16875. */
  16876. PlaybackRateMenuItem.prototype.contentElType = 'button';
  16877. Component.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  16878. /**
  16879. * @file playback-rate-menu-button.js
  16880. */
  16881. /** @import Player from '../../player' */
  16882. /**
  16883. * The component for controlling the playback rate.
  16884. *
  16885. * @extends MenuButton
  16886. */
  16887. class PlaybackRateMenuButton extends MenuButton {
  16888. /**
  16889. * Creates an instance of this class.
  16890. *
  16891. * @param {Player} player
  16892. * The `Player` that this class should be attached to.
  16893. *
  16894. * @param {Object} [options]
  16895. * The key/value store of player options.
  16896. */
  16897. constructor(player, options) {
  16898. super(player, options);
  16899. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  16900. this.updateVisibility();
  16901. this.updateLabel();
  16902. this.on(player, 'loadstart', e => this.updateVisibility(e));
  16903. this.on(player, 'ratechange', e => this.updateLabel(e));
  16904. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  16905. }
  16906. /**
  16907. * Create the `Component`'s DOM element
  16908. *
  16909. * @return {Element}
  16910. * The element that was created.
  16911. */
  16912. createEl() {
  16913. const el = super.createEl();
  16914. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  16915. this.labelEl_ = createEl('div', {
  16916. className: 'vjs-playback-rate-value',
  16917. id: this.labelElId_,
  16918. textContent: '1x'
  16919. });
  16920. el.appendChild(this.labelEl_);
  16921. return el;
  16922. }
  16923. dispose() {
  16924. this.labelEl_ = null;
  16925. super.dispose();
  16926. }
  16927. /**
  16928. * Builds the default DOM `className`.
  16929. *
  16930. * @return {string}
  16931. * The DOM `className` for this object.
  16932. */
  16933. buildCSSClass() {
  16934. return `vjs-playback-rate ${super.buildCSSClass()}`;
  16935. }
  16936. buildWrapperCSSClass() {
  16937. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  16938. }
  16939. /**
  16940. * Create the list of menu items. Specific to each subclass.
  16941. *
  16942. */
  16943. createItems() {
  16944. const rates = this.playbackRates();
  16945. const items = [];
  16946. for (let i = rates.length - 1; i >= 0; i--) {
  16947. items.push(new PlaybackRateMenuItem(this.player(), {
  16948. rate: rates[i] + 'x'
  16949. }));
  16950. }
  16951. return items;
  16952. }
  16953. /**
  16954. * On playbackrateschange, update the menu to account for the new items.
  16955. *
  16956. * @listens Player#playbackrateschange
  16957. */
  16958. handlePlaybackRateschange(event) {
  16959. this.update();
  16960. }
  16961. /**
  16962. * Get possible playback rates
  16963. *
  16964. * @return {Array}
  16965. * All possible playback rates
  16966. */
  16967. playbackRates() {
  16968. const player = this.player();
  16969. return player.playbackRates && player.playbackRates() || [];
  16970. }
  16971. /**
  16972. * Get whether playback rates is supported by the tech
  16973. * and an array of playback rates exists
  16974. *
  16975. * @return {boolean}
  16976. * Whether changing playback rate is supported
  16977. */
  16978. playbackRateSupported() {
  16979. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  16980. }
  16981. /**
  16982. * Hide playback rate controls when they're no playback rate options to select
  16983. *
  16984. * @param {Event} [event]
  16985. * The event that caused this function to run.
  16986. *
  16987. * @listens Player#loadstart
  16988. */
  16989. updateVisibility(event) {
  16990. if (this.playbackRateSupported()) {
  16991. this.removeClass('vjs-hidden');
  16992. } else {
  16993. this.addClass('vjs-hidden');
  16994. }
  16995. }
  16996. /**
  16997. * Update button label when rate changed
  16998. *
  16999. * @param {Event} [event]
  17000. * The event that caused this function to run.
  17001. *
  17002. * @listens Player#ratechange
  17003. */
  17004. updateLabel(event) {
  17005. if (this.playbackRateSupported()) {
  17006. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  17007. }
  17008. }
  17009. }
  17010. /**
  17011. * The text that should display over the `PlaybackRateMenuButton`s controls.
  17012. *
  17013. * Added for localization.
  17014. *
  17015. * @type {string}
  17016. * @protected
  17017. */
  17018. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  17019. Component.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  17020. /**
  17021. * @file spacer.js
  17022. */
  17023. /**
  17024. * Just an empty spacer element that can be used as an append point for plugins, etc.
  17025. * Also can be used to create space between elements when necessary.
  17026. *
  17027. * @extends Component
  17028. */
  17029. class Spacer extends Component {
  17030. /**
  17031. * Builds the default DOM `className`.
  17032. *
  17033. * @return {string}
  17034. * The DOM `className` for this object.
  17035. */
  17036. buildCSSClass() {
  17037. return `vjs-spacer ${super.buildCSSClass()}`;
  17038. }
  17039. /**
  17040. * Create the `Component`'s DOM element
  17041. *
  17042. * @return {Element}
  17043. * The element that was created.
  17044. */
  17045. createEl(tag = 'div', props = {}, attributes = {}) {
  17046. if (!props.className) {
  17047. props.className = this.buildCSSClass();
  17048. }
  17049. return super.createEl(tag, props, attributes);
  17050. }
  17051. }
  17052. Component.registerComponent('Spacer', Spacer);
  17053. /**
  17054. * @file custom-control-spacer.js
  17055. */
  17056. /**
  17057. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  17058. *
  17059. * @extends Spacer
  17060. */
  17061. class CustomControlSpacer extends Spacer {
  17062. /**
  17063. * Builds the default DOM `className`.
  17064. *
  17065. * @return {string}
  17066. * The DOM `className` for this object.
  17067. */
  17068. buildCSSClass() {
  17069. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  17070. }
  17071. /**
  17072. * Create the `Component`'s DOM element
  17073. *
  17074. * @return {Element}
  17075. * The element that was created.
  17076. */
  17077. createEl() {
  17078. return super.createEl('div', {
  17079. className: this.buildCSSClass(),
  17080. // No-flex/table-cell mode requires there be some content
  17081. // in the cell to fill the remaining space of the table.
  17082. textContent: '\u00a0'
  17083. });
  17084. }
  17085. }
  17086. Component.registerComponent('CustomControlSpacer', CustomControlSpacer);
  17087. /**
  17088. * @file control-bar.js
  17089. */
  17090. /**
  17091. * Container of main controls.
  17092. *
  17093. * @extends Component
  17094. */
  17095. class ControlBar extends Component {
  17096. /**
  17097. * Create the `Component`'s DOM element
  17098. *
  17099. * @return {Element}
  17100. * The element that was created.
  17101. */
  17102. createEl() {
  17103. return super.createEl('div', {
  17104. className: 'vjs-control-bar',
  17105. dir: 'ltr'
  17106. });
  17107. }
  17108. }
  17109. /**
  17110. * Default options for `ControlBar`
  17111. *
  17112. * @type {Object}
  17113. * @private
  17114. */
  17115. ControlBar.prototype.options_ = {
  17116. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'pictureInPictureToggle', 'fullscreenToggle']
  17117. };
  17118. Component.registerComponent('ControlBar', ControlBar);
  17119. /**
  17120. * @file error-display.js
  17121. */
  17122. /** @import Player from './player' */
  17123. /**
  17124. * A display that indicates an error has occurred. This means that the video
  17125. * is unplayable.
  17126. *
  17127. * @extends ModalDialog
  17128. */
  17129. class ErrorDisplay extends ModalDialog {
  17130. /**
  17131. * Creates an instance of this class.
  17132. *
  17133. * @param {Player} player
  17134. * The `Player` that this class should be attached to.
  17135. *
  17136. * @param {Object} [options]
  17137. * The key/value store of player options.
  17138. */
  17139. constructor(player, options) {
  17140. super(player, options);
  17141. this.on(player, 'error', e => {
  17142. this.open(e);
  17143. });
  17144. }
  17145. /**
  17146. * Builds the default DOM `className`.
  17147. *
  17148. * @return {string}
  17149. * The DOM `className` for this object.
  17150. *
  17151. * @deprecated Since version 5.
  17152. */
  17153. buildCSSClass() {
  17154. return `vjs-error-display ${super.buildCSSClass()}`;
  17155. }
  17156. /**
  17157. * Gets the localized error message based on the `Player`s error.
  17158. *
  17159. * @return {string}
  17160. * The `Player`s error message localized or an empty string.
  17161. */
  17162. content() {
  17163. const error = this.player().error();
  17164. return error ? this.localize(error.message) : '';
  17165. }
  17166. }
  17167. /**
  17168. * The default options for an `ErrorDisplay`.
  17169. *
  17170. * @private
  17171. */
  17172. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  17173. pauseOnOpen: false,
  17174. fillAlways: true,
  17175. temporary: false,
  17176. uncloseable: true
  17177. });
  17178. Component.registerComponent('ErrorDisplay', ErrorDisplay);
  17179. /** @import Player from './player' */
  17180. /** @import { ContentDescriptor } from '../utils/dom' */
  17181. /**
  17182. * Creates DOM element of 'select' & its options.
  17183. *
  17184. * @extends Component
  17185. */
  17186. class TextTrackSelect extends Component {
  17187. /**
  17188. * Creates an instance of this class.
  17189. *
  17190. * @param {Player} player
  17191. * The `Player` that this class should be attached to.
  17192. *
  17193. * @param {Object} [options]
  17194. * The key/value store of player options.
  17195. *
  17196. * @param {ContentDescriptor} [options.content=undefined]
  17197. * Provide customized content for this modal.
  17198. *
  17199. * @param {string} [options.legendId]
  17200. * A text with part of an string to create atribute of aria-labelledby.
  17201. *
  17202. * @param {string} [options.id]
  17203. * A text with part of an string to create atribute of aria-labelledby.
  17204. *
  17205. * @param {Array} [options.SelectOptions]
  17206. * Array that contains the value & textContent of for each of the
  17207. * options elements.
  17208. */
  17209. constructor(player, options = {}) {
  17210. super(player, options);
  17211. this.el_.setAttribute('aria-labelledby', this.selectLabelledbyIds);
  17212. }
  17213. /**
  17214. * Create the `TextTrackSelect`'s DOM element
  17215. *
  17216. * @return {Element}
  17217. * The DOM element that gets created.
  17218. */
  17219. createEl() {
  17220. this.selectLabelledbyIds = [this.options_.legendId, this.options_.labelId].join(' ').trim();
  17221. // Create select & inner options
  17222. const selectoptions = createEl('select', {
  17223. id: this.options_.id
  17224. }, {}, this.options_.SelectOptions.map(optionText => {
  17225. // Constructs an id for the <option>.
  17226. // For the colour settings that have two <selects> with a <label> each, generates an id based off the label value
  17227. // For font size/family and edge style with one <select> and no <label>, generates an id with a guid
  17228. const optionId = (this.options_.labelId ? this.options_.labelId : `vjs-track-option-${newGUID()}`) + '-' + optionText[1].replace(/\W+/g, '');
  17229. const option = createEl('option', {
  17230. id: optionId,
  17231. value: this.localize(optionText[0]),
  17232. textContent: this.localize(optionText[1])
  17233. });
  17234. option.setAttribute('aria-labelledby', `${this.selectLabelledbyIds} ${optionId}`);
  17235. return option;
  17236. }));
  17237. return selectoptions;
  17238. }
  17239. }
  17240. Component.registerComponent('TextTrackSelect', TextTrackSelect);
  17241. /** @import Player from './player' */
  17242. /** @import { ContentDescriptor } from '../utils/dom' */
  17243. /**
  17244. * Creates fieldset section of 'TextTrackSettings'.
  17245. * Manganes two versions of fieldsets, one for type of 'colors'
  17246. * & the other for 'font', Component adds diferent DOM elements
  17247. * to that fieldset depending on the type.
  17248. *
  17249. * @extends Component
  17250. */
  17251. class TextTrackFieldset extends Component {
  17252. /**
  17253. * Creates an instance of this class.
  17254. *
  17255. * @param {Player} player
  17256. * The `Player` that this class should be attached to.
  17257. *
  17258. * @param {Object} [options]
  17259. * The key/value store of player options.
  17260. *
  17261. * @param {ContentDescriptor} [options.content=undefined]
  17262. * Provide customized content for this modal.
  17263. *
  17264. * @param {string} [options.legendId]
  17265. * A text with part of an string to create atribute of aria-labelledby.
  17266. * It passes to 'TextTrackSelect'.
  17267. *
  17268. * @param {string} [options.id]
  17269. * A text with part of an string to create atribute of aria-labelledby.
  17270. * It passes to 'TextTrackSelect'.
  17271. *
  17272. * @param {string} [options.legendText]
  17273. * A text to use as the text content of the legend element.
  17274. *
  17275. * @param {Array} [options.selects]
  17276. * Array that contains the selects that are use to create 'selects'
  17277. * components.
  17278. *
  17279. * @param {Array} [options.SelectOptions]
  17280. * Array that contains the value & textContent of for each of the
  17281. * options elements, it passes to 'TextTrackSelect'.
  17282. *
  17283. * @param {string} [options.type]
  17284. * Conditions if some DOM elements will be added to the fieldset
  17285. * component.
  17286. *
  17287. * @param {Object} [options.selectConfigs]
  17288. * Object with the following properties that are the selects configurations:
  17289. * backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,
  17290. * fontPercent, textOpacity, windowColor, windowOpacity.
  17291. * These properties are use to configure the 'TextTrackSelect' Component.
  17292. */
  17293. constructor(player, options = {}) {
  17294. super(player, options);
  17295. // Add Components & DOM Elements
  17296. const legendElement = createEl('legend', {
  17297. textContent: this.localize(this.options_.legendText),
  17298. id: this.options_.legendId
  17299. });
  17300. this.el().appendChild(legendElement);
  17301. const selects = this.options_.selects;
  17302. // Iterate array of selects to create 'selects' components
  17303. for (const i of selects) {
  17304. const selectConfig = this.options_.selectConfigs[i];
  17305. const selectClassName = selectConfig.className;
  17306. const id = selectConfig.id.replace('%s', this.options_.id_);
  17307. let span = null;
  17308. const guid = `vjs_select_${newGUID()}`;
  17309. // Conditionally create span to add on the component
  17310. if (this.options_.type === 'colors') {
  17311. span = createEl('span', {
  17312. className: selectClassName
  17313. });
  17314. const label = createEl('label', {
  17315. id,
  17316. className: 'vjs-label',
  17317. textContent: this.localize(selectConfig.label)
  17318. });
  17319. label.setAttribute('for', guid);
  17320. span.appendChild(label);
  17321. }
  17322. const textTrackSelect = new TextTrackSelect(player, {
  17323. SelectOptions: selectConfig.options,
  17324. legendId: this.options_.legendId,
  17325. id: guid,
  17326. labelId: id
  17327. });
  17328. this.addChild(textTrackSelect);
  17329. // Conditionally append to 'select' component to conditionally created span
  17330. if (this.options_.type === 'colors') {
  17331. span.appendChild(textTrackSelect.el());
  17332. this.el().appendChild(span);
  17333. }
  17334. }
  17335. }
  17336. /**
  17337. * Create the `TextTrackFieldset`'s DOM element
  17338. *
  17339. * @return {Element}
  17340. * The DOM element that gets created.
  17341. */
  17342. createEl() {
  17343. const el = createEl('fieldset', {
  17344. // Prefixing classes of elements within a player with "vjs-"
  17345. // is a convention used in Video.js.
  17346. className: this.options_.className
  17347. });
  17348. return el;
  17349. }
  17350. }
  17351. Component.registerComponent('TextTrackFieldset', TextTrackFieldset);
  17352. /** @import Player from './player' */
  17353. /** @import { ContentDescriptor } from '../utils/dom' */
  17354. /**
  17355. * The component 'TextTrackSettingsColors' displays a set of 'fieldsets'
  17356. * using the component 'TextTrackFieldset'.
  17357. *
  17358. * @extends Component
  17359. */
  17360. class TextTrackSettingsColors extends Component {
  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. * @param {ContentDescriptor} [options.content=undefined]
  17371. * Provide customized content for this modal.
  17372. *
  17373. * @param {Array} [options.fieldSets]
  17374. * Array that contains the configurations for the selects.
  17375. *
  17376. * @param {Object} [options.selectConfigs]
  17377. * Object with the following properties that are the select confugations:
  17378. * backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,
  17379. * fontPercent, textOpacity, windowColor, windowOpacity.
  17380. * it passes to 'TextTrackFieldset'.
  17381. */
  17382. constructor(player, options = {}) {
  17383. super(player, options);
  17384. const id_ = this.options_.textTrackComponentid;
  17385. // createElFgColor_
  17386. const ElFgColorFieldset = new TextTrackFieldset(player, {
  17387. id_,
  17388. legendId: `captions-text-legend-${id_}`,
  17389. legendText: this.localize('Text'),
  17390. className: 'vjs-fg vjs-track-setting',
  17391. selects: this.options_.fieldSets[0],
  17392. selectConfigs: this.options_.selectConfigs,
  17393. type: 'colors'
  17394. });
  17395. this.addChild(ElFgColorFieldset);
  17396. // createElBgColor_
  17397. const ElBgColorFieldset = new TextTrackFieldset(player, {
  17398. id_,
  17399. legendId: `captions-background-${id_}`,
  17400. legendText: this.localize('Text Background'),
  17401. className: 'vjs-bg vjs-track-setting',
  17402. selects: this.options_.fieldSets[1],
  17403. selectConfigs: this.options_.selectConfigs,
  17404. type: 'colors'
  17405. });
  17406. this.addChild(ElBgColorFieldset);
  17407. // createElWinColor_
  17408. const ElWinColorFieldset = new TextTrackFieldset(player, {
  17409. id_,
  17410. legendId: `captions-window-${id_}`,
  17411. legendText: this.localize('Caption Area Background'),
  17412. className: 'vjs-window vjs-track-setting',
  17413. selects: this.options_.fieldSets[2],
  17414. selectConfigs: this.options_.selectConfigs,
  17415. type: 'colors'
  17416. });
  17417. this.addChild(ElWinColorFieldset);
  17418. }
  17419. /**
  17420. * Create the `TextTrackSettingsColors`'s DOM element
  17421. *
  17422. * @return {Element}
  17423. * The DOM element that gets created.
  17424. */
  17425. createEl() {
  17426. const el = createEl('div', {
  17427. className: 'vjs-track-settings-colors'
  17428. });
  17429. return el;
  17430. }
  17431. }
  17432. Component.registerComponent('TextTrackSettingsColors', TextTrackSettingsColors);
  17433. /** @import Player from './player' */
  17434. /** @import { ContentDescriptor } from '../utils/dom' */
  17435. /**
  17436. * The component 'TextTrackSettingsFont' displays a set of 'fieldsets'
  17437. * using the component 'TextTrackFieldset'.
  17438. *
  17439. * @extends Component
  17440. */
  17441. class TextTrackSettingsFont extends Component {
  17442. /**
  17443. * Creates an instance of this class.
  17444. *
  17445. * @param {Player} player
  17446. * The `Player` that this class should be attached to.
  17447. *
  17448. * @param {Object} [options]
  17449. * The key/value store of player options.
  17450. *
  17451. * @param {ContentDescriptor} [options.content=undefined]
  17452. * Provide customized content for this modal.
  17453. *
  17454. * @param {Array} [options.fieldSets]
  17455. * Array that contains the configurations for the selects.
  17456. *
  17457. * @param {Object} [options.selectConfigs]
  17458. * Object with the following properties that are the select confugations:
  17459. * backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,
  17460. * fontPercent, textOpacity, windowColor, windowOpacity.
  17461. * it passes to 'TextTrackFieldset'.
  17462. */
  17463. constructor(player, options = {}) {
  17464. super(player, options);
  17465. const id_ = this.options_.textTrackComponentid;
  17466. const ElFgColorFieldset = new TextTrackFieldset(player, {
  17467. id_,
  17468. legendId: `captions-font-size-${id_}`,
  17469. legendText: 'Font Size',
  17470. className: 'vjs-font-percent vjs-track-setting',
  17471. selects: this.options_.fieldSets[0],
  17472. selectConfigs: this.options_.selectConfigs,
  17473. type: 'font'
  17474. });
  17475. this.addChild(ElFgColorFieldset);
  17476. const ElBgColorFieldset = new TextTrackFieldset(player, {
  17477. id_,
  17478. legendId: `captions-edge-style-${id_}`,
  17479. legendText: this.localize('Text Edge Style'),
  17480. className: 'vjs-edge-style vjs-track-setting',
  17481. selects: this.options_.fieldSets[1],
  17482. selectConfigs: this.options_.selectConfigs,
  17483. type: 'font'
  17484. });
  17485. this.addChild(ElBgColorFieldset);
  17486. const ElWinColorFieldset = new TextTrackFieldset(player, {
  17487. id_,
  17488. legendId: `captions-font-family-${id_}`,
  17489. legendText: this.localize('Font Family'),
  17490. className: 'vjs-font-family vjs-track-setting',
  17491. selects: this.options_.fieldSets[2],
  17492. selectConfigs: this.options_.selectConfigs,
  17493. type: 'font'
  17494. });
  17495. this.addChild(ElWinColorFieldset);
  17496. }
  17497. /**
  17498. * Create the `TextTrackSettingsFont`'s DOM element
  17499. *
  17500. * @return {Element}
  17501. * The DOM element that gets created.
  17502. */
  17503. createEl() {
  17504. const el = createEl('div', {
  17505. className: 'vjs-track-settings-font'
  17506. });
  17507. return el;
  17508. }
  17509. }
  17510. Component.registerComponent('TextTrackSettingsFont', TextTrackSettingsFont);
  17511. /**
  17512. * Buttons of reset & done that modal 'TextTrackSettings'
  17513. * uses as part of its content.
  17514. *
  17515. * 'Reset': Resets all settings on 'TextTrackSettings'.
  17516. * 'Done': Closes 'TextTrackSettings' modal.
  17517. *
  17518. * @extends Component
  17519. */
  17520. class TrackSettingsControls extends Component {
  17521. constructor(player, options = {}) {
  17522. super(player, options);
  17523. // Create DOM elements
  17524. const defaultsDescription = this.localize('restore all settings to the default values');
  17525. const resetButton = new Button(player, {
  17526. controlText: defaultsDescription,
  17527. className: 'vjs-default-button'
  17528. });
  17529. resetButton.el().classList.remove('vjs-control', 'vjs-button');
  17530. resetButton.el().textContent = this.localize('Reset');
  17531. this.addChild(resetButton);
  17532. const doneButton = new Button(player, {
  17533. controlText: defaultsDescription,
  17534. className: 'vjs-done-button'
  17535. });
  17536. // Remove unrequired style classes
  17537. doneButton.el().classList.remove('vjs-control', 'vjs-button');
  17538. doneButton.el().textContent = this.localize('Done');
  17539. this.addChild(doneButton);
  17540. }
  17541. /**
  17542. * Create the `TrackSettingsControls`'s DOM element
  17543. *
  17544. * @return {Element}
  17545. * The DOM element that gets created.
  17546. */
  17547. createEl() {
  17548. const el = createEl('div', {
  17549. className: 'vjs-track-settings-controls'
  17550. });
  17551. return el;
  17552. }
  17553. }
  17554. Component.registerComponent('TrackSettingsControls', TrackSettingsControls);
  17555. /**
  17556. * @file text-track-settings.js
  17557. */
  17558. /** @import Player from '../player' */
  17559. const LOCAL_STORAGE_KEY = 'vjs-text-track-settings';
  17560. const COLOR_BLACK = ['#000', 'Black'];
  17561. const COLOR_BLUE = ['#00F', 'Blue'];
  17562. const COLOR_CYAN = ['#0FF', 'Cyan'];
  17563. const COLOR_GREEN = ['#0F0', 'Green'];
  17564. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  17565. const COLOR_RED = ['#F00', 'Red'];
  17566. const COLOR_WHITE = ['#FFF', 'White'];
  17567. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  17568. const OPACITY_OPAQUE = ['1', 'Opaque'];
  17569. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  17570. const OPACITY_TRANS = ['0', 'Transparent'];
  17571. // Configuration for the various <select> elements in the DOM of this component.
  17572. //
  17573. // Possible keys include:
  17574. //
  17575. // `default`:
  17576. // The default option index. Only needs to be provided if not zero.
  17577. // `parser`:
  17578. // A function which is used to parse the value from the selected option in
  17579. // a customized way.
  17580. // `selector`:
  17581. // The selector used to find the associated <select> element.
  17582. const selectConfigs = {
  17583. backgroundColor: {
  17584. selector: '.vjs-bg-color > select',
  17585. id: 'captions-background-color-%s',
  17586. label: 'Color',
  17587. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN],
  17588. className: 'vjs-bg-color'
  17589. },
  17590. backgroundOpacity: {
  17591. selector: '.vjs-bg-opacity > select',
  17592. id: 'captions-background-opacity-%s',
  17593. label: 'Opacity',
  17594. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS],
  17595. className: 'vjs-bg-opacity vjs-opacity'
  17596. },
  17597. color: {
  17598. selector: '.vjs-text-color > select',
  17599. id: 'captions-foreground-color-%s',
  17600. label: 'Color',
  17601. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN],
  17602. className: 'vjs-text-color'
  17603. },
  17604. edgeStyle: {
  17605. selector: '.vjs-edge-style > select',
  17606. id: '',
  17607. label: 'Text Edge Style',
  17608. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Drop shadow']]
  17609. },
  17610. fontFamily: {
  17611. selector: '.vjs-font-family > select',
  17612. id: '',
  17613. label: 'Font Family',
  17614. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  17615. },
  17616. fontPercent: {
  17617. selector: '.vjs-font-percent > select',
  17618. id: '',
  17619. label: 'Font Size',
  17620. 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%']],
  17621. default: 2,
  17622. parser: v => v === '1.00' ? null : Number(v)
  17623. },
  17624. textOpacity: {
  17625. selector: '.vjs-text-opacity > select',
  17626. id: 'captions-foreground-opacity-%s',
  17627. label: 'Opacity',
  17628. options: [OPACITY_OPAQUE, OPACITY_SEMI],
  17629. className: 'vjs-text-opacity vjs-opacity'
  17630. },
  17631. // Options for this object are defined below.
  17632. windowColor: {
  17633. selector: '.vjs-window-color > select',
  17634. id: 'captions-window-color-%s',
  17635. label: 'Color',
  17636. className: 'vjs-window-color'
  17637. },
  17638. // Options for this object are defined below.
  17639. windowOpacity: {
  17640. selector: '.vjs-window-opacity > select',
  17641. id: 'captions-window-opacity-%s',
  17642. label: 'Opacity',
  17643. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE],
  17644. className: 'vjs-window-opacity vjs-opacity'
  17645. }
  17646. };
  17647. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  17648. /**
  17649. * Get the actual value of an option.
  17650. *
  17651. * @param {string} value
  17652. * The value to get
  17653. *
  17654. * @param {Function} [parser]
  17655. * Optional function to adjust the value.
  17656. *
  17657. * @return {*}
  17658. * - Will be `undefined` if no value exists
  17659. * - Will be `undefined` if the given value is "none".
  17660. * - Will be the actual value otherwise.
  17661. *
  17662. * @private
  17663. */
  17664. function parseOptionValue(value, parser) {
  17665. if (parser) {
  17666. value = parser(value);
  17667. }
  17668. if (value && value !== 'none') {
  17669. return value;
  17670. }
  17671. }
  17672. /**
  17673. * Gets the value of the selected <option> element within a <select> element.
  17674. *
  17675. * @param {Element} el
  17676. * the element to look in
  17677. *
  17678. * @param {Function} [parser]
  17679. * Optional function to adjust the value.
  17680. *
  17681. * @return {*}
  17682. * - Will be `undefined` if no value exists
  17683. * - Will be `undefined` if the given value is "none".
  17684. * - Will be the actual value otherwise.
  17685. *
  17686. * @private
  17687. */
  17688. function getSelectedOptionValue(el, parser) {
  17689. const value = el.options[el.options.selectedIndex].value;
  17690. return parseOptionValue(value, parser);
  17691. }
  17692. /**
  17693. * Sets the selected <option> element within a <select> element based on a
  17694. * given value.
  17695. *
  17696. * @param {Element} el
  17697. * The element to look in.
  17698. *
  17699. * @param {string} value
  17700. * the property to look on.
  17701. *
  17702. * @param {Function} [parser]
  17703. * Optional function to adjust the value before comparing.
  17704. *
  17705. * @private
  17706. */
  17707. function setSelectedOption(el, value, parser) {
  17708. if (!value) {
  17709. return;
  17710. }
  17711. for (let i = 0; i < el.options.length; i++) {
  17712. if (parseOptionValue(el.options[i].value, parser) === value) {
  17713. el.selectedIndex = i;
  17714. break;
  17715. }
  17716. }
  17717. }
  17718. /**
  17719. * Manipulate Text Tracks settings.
  17720. *
  17721. * @extends ModalDialog
  17722. */
  17723. class TextTrackSettings extends ModalDialog {
  17724. /**
  17725. * Creates an instance of this class.
  17726. *
  17727. * @param {Player} player
  17728. * The `Player` that this class should be attached to.
  17729. *
  17730. * @param {Object} [options]
  17731. * The key/value store of player options.
  17732. */
  17733. constructor(player, options) {
  17734. options.temporary = false;
  17735. super(player, options);
  17736. this.updateDisplay = this.updateDisplay.bind(this);
  17737. // fill the modal and pretend we have opened it
  17738. this.fill();
  17739. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  17740. this.renderModalComponents(player);
  17741. this.endDialog = createEl('p', {
  17742. className: 'vjs-control-text',
  17743. textContent: this.localize('End of dialog window.')
  17744. });
  17745. this.el().appendChild(this.endDialog);
  17746. this.setDefaults();
  17747. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  17748. if (options.persistTextTrackSettings === undefined) {
  17749. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  17750. }
  17751. this.bindFunctionsToSelectsAndButtons();
  17752. if (this.options_.persistTextTrackSettings) {
  17753. this.restoreSettings();
  17754. }
  17755. }
  17756. renderModalComponents(player) {
  17757. const textTrackSettingsColors = new TextTrackSettingsColors(player, {
  17758. textTrackComponentid: this.id_,
  17759. selectConfigs,
  17760. fieldSets: [['color', 'textOpacity'], ['backgroundColor', 'backgroundOpacity'], ['windowColor', 'windowOpacity']]
  17761. });
  17762. this.addChild(textTrackSettingsColors);
  17763. const textTrackSettingsFont = new TextTrackSettingsFont(player, {
  17764. textTrackComponentid: this.id_,
  17765. selectConfigs,
  17766. fieldSets: [['fontPercent'], ['edgeStyle'], ['fontFamily']]
  17767. });
  17768. this.addChild(textTrackSettingsFont);
  17769. const trackSettingsControls = new TrackSettingsControls(player);
  17770. this.addChild(trackSettingsControls);
  17771. }
  17772. bindFunctionsToSelectsAndButtons() {
  17773. this.on(this.$('.vjs-done-button'), ['click', 'tap'], () => {
  17774. this.saveSettings();
  17775. this.close();
  17776. });
  17777. this.on(this.$('.vjs-default-button'), ['click', 'tap'], () => {
  17778. this.setDefaults();
  17779. this.updateDisplay();
  17780. });
  17781. each(selectConfigs, config => {
  17782. this.on(this.$(config.selector), 'change', this.updateDisplay);
  17783. });
  17784. }
  17785. dispose() {
  17786. this.endDialog = null;
  17787. super.dispose();
  17788. }
  17789. label() {
  17790. return this.localize('Caption Settings Dialog');
  17791. }
  17792. description() {
  17793. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  17794. }
  17795. buildCSSClass() {
  17796. return super.buildCSSClass() + ' vjs-text-track-settings';
  17797. }
  17798. /**
  17799. * Gets an object of text track settings (or null).
  17800. *
  17801. * @return {Object}
  17802. * An object with config values parsed from the DOM or localStorage.
  17803. */
  17804. getValues() {
  17805. return reduce(selectConfigs, (accum, config, key) => {
  17806. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  17807. if (value !== undefined) {
  17808. accum[key] = value;
  17809. }
  17810. return accum;
  17811. }, {});
  17812. }
  17813. /**
  17814. * Sets text track settings from an object of values.
  17815. *
  17816. * @param {Object} values
  17817. * An object with config values parsed from the DOM or localStorage.
  17818. */
  17819. setValues(values) {
  17820. each(selectConfigs, (config, key) => {
  17821. setSelectedOption(this.$(config.selector), values[key], config.parser);
  17822. });
  17823. }
  17824. /**
  17825. * Sets all `<select>` elements to their default values.
  17826. */
  17827. setDefaults() {
  17828. each(selectConfigs, config => {
  17829. const index = config.hasOwnProperty('default') ? config.default : 0;
  17830. this.$(config.selector).selectedIndex = index;
  17831. });
  17832. }
  17833. /**
  17834. * Restore texttrack settings from localStorage
  17835. */
  17836. restoreSettings() {
  17837. let values;
  17838. try {
  17839. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY));
  17840. } catch (err) {
  17841. log.warn(err);
  17842. }
  17843. if (values) {
  17844. this.setValues(values);
  17845. }
  17846. }
  17847. /**
  17848. * Save text track settings to localStorage
  17849. */
  17850. saveSettings() {
  17851. if (!this.options_.persistTextTrackSettings) {
  17852. return;
  17853. }
  17854. const values = this.getValues();
  17855. try {
  17856. if (Object.keys(values).length) {
  17857. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values));
  17858. } else {
  17859. window.localStorage.removeItem(LOCAL_STORAGE_KEY);
  17860. }
  17861. } catch (err) {
  17862. log.warn(err);
  17863. }
  17864. }
  17865. /**
  17866. * Update display of text track settings
  17867. */
  17868. updateDisplay() {
  17869. const ttDisplay = this.player_.getChild('textTrackDisplay');
  17870. if (ttDisplay) {
  17871. ttDisplay.updateDisplay();
  17872. }
  17873. }
  17874. /**
  17875. * Repopulate dialog with new localizations on languagechange
  17876. */
  17877. handleLanguagechange() {
  17878. this.fill();
  17879. this.renderModalComponents(this.player_);
  17880. this.bindFunctionsToSelectsAndButtons();
  17881. }
  17882. }
  17883. Component.registerComponent('TextTrackSettings', TextTrackSettings);
  17884. /**
  17885. * @file resize-manager.js
  17886. */
  17887. /**
  17888. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  17889. *
  17890. * 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}.
  17891. *
  17892. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  17893. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  17894. *
  17895. * @example <caption>How to disable the resize manager</caption>
  17896. * const player = videojs('#vid', {
  17897. * resizeManager: false
  17898. * });
  17899. *
  17900. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  17901. *
  17902. * @extends Component
  17903. */
  17904. class ResizeManager extends Component {
  17905. /**
  17906. * Create the ResizeManager.
  17907. *
  17908. * @param {Object} player
  17909. * The `Player` that this class should be attached to.
  17910. *
  17911. * @param {Object} [options]
  17912. * The key/value store of ResizeManager options.
  17913. *
  17914. * @param {Object} [options.ResizeObserver]
  17915. * A polyfill for ResizeObserver can be passed in here.
  17916. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  17917. */
  17918. constructor(player, options) {
  17919. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
  17920. // if `null` was passed, we want to disable the ResizeObserver
  17921. if (options.ResizeObserver === null) {
  17922. RESIZE_OBSERVER_AVAILABLE = false;
  17923. }
  17924. // Only create an element when ResizeObserver isn't available
  17925. const options_ = merge({
  17926. createEl: !RESIZE_OBSERVER_AVAILABLE,
  17927. reportTouchActivity: false
  17928. }, options);
  17929. super(player, options_);
  17930. this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  17931. this.loadListener_ = null;
  17932. this.resizeObserver_ = null;
  17933. this.debouncedHandler_ = debounce(() => {
  17934. this.resizeHandler();
  17935. }, 100, false, this);
  17936. if (RESIZE_OBSERVER_AVAILABLE) {
  17937. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  17938. this.resizeObserver_.observe(player.el());
  17939. } else {
  17940. this.loadListener_ = () => {
  17941. if (!this.el_ || !this.el_.contentWindow) {
  17942. return;
  17943. }
  17944. const debouncedHandler_ = this.debouncedHandler_;
  17945. let unloadListener_ = this.unloadListener_ = function () {
  17946. off(this, 'resize', debouncedHandler_);
  17947. off(this, 'unload', unloadListener_);
  17948. unloadListener_ = null;
  17949. };
  17950. // safari and edge can unload the iframe before resizemanager dispose
  17951. // we have to dispose of event handlers correctly before that happens
  17952. on(this.el_.contentWindow, 'unload', unloadListener_);
  17953. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  17954. };
  17955. this.one('load', this.loadListener_);
  17956. }
  17957. }
  17958. createEl() {
  17959. return super.createEl('iframe', {
  17960. className: 'vjs-resize-manager',
  17961. tabIndex: -1,
  17962. title: this.localize('No content')
  17963. }, {
  17964. 'aria-hidden': 'true'
  17965. });
  17966. }
  17967. /**
  17968. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  17969. *
  17970. * @fires Player#playerresize
  17971. */
  17972. resizeHandler() {
  17973. /**
  17974. * Called when the player size has changed
  17975. *
  17976. * @event Player#playerresize
  17977. * @type {Event}
  17978. */
  17979. // make sure player is still around to trigger
  17980. // prevents this from causing an error after dispose
  17981. if (!this.player_ || !this.player_.trigger) {
  17982. return;
  17983. }
  17984. this.player_.trigger('playerresize');
  17985. }
  17986. dispose() {
  17987. if (this.debouncedHandler_) {
  17988. this.debouncedHandler_.cancel();
  17989. }
  17990. if (this.resizeObserver_) {
  17991. if (this.player_.el()) {
  17992. this.resizeObserver_.unobserve(this.player_.el());
  17993. }
  17994. this.resizeObserver_.disconnect();
  17995. }
  17996. if (this.loadListener_) {
  17997. this.off('load', this.loadListener_);
  17998. }
  17999. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  18000. this.unloadListener_.call(this.el_.contentWindow);
  18001. }
  18002. this.ResizeObserver = null;
  18003. this.resizeObserver = null;
  18004. this.debouncedHandler_ = null;
  18005. this.loadListener_ = null;
  18006. super.dispose();
  18007. }
  18008. }
  18009. Component.registerComponent('ResizeManager', ResizeManager);
  18010. /** @import Player from './player' */
  18011. const defaults$1 = {
  18012. trackingThreshold: 20,
  18013. liveTolerance: 15
  18014. };
  18015. /*
  18016. track when we are at the live edge, and other helpers for live playback */
  18017. /**
  18018. * A class for checking live current time and determining when the player
  18019. * is at or behind the live edge.
  18020. */
  18021. class LiveTracker extends Component {
  18022. /**
  18023. * Creates an instance of this class.
  18024. *
  18025. * @param {Player} player
  18026. * The `Player` that this class should be attached to.
  18027. *
  18028. * @param {Object} [options]
  18029. * The key/value store of player options.
  18030. *
  18031. * @param {number} [options.trackingThreshold=20]
  18032. * Number of seconds of live window (seekableEnd - seekableStart) that
  18033. * media needs to have before the liveui will be shown.
  18034. *
  18035. * @param {number} [options.liveTolerance=15]
  18036. * Number of seconds behind live that we have to be
  18037. * before we will be considered non-live. Note that this will only
  18038. * be used when playing at the live edge. This allows large seekable end
  18039. * changes to not effect whether we are live or not.
  18040. */
  18041. constructor(player, options) {
  18042. // LiveTracker does not need an element
  18043. const options_ = merge(defaults$1, options, {
  18044. createEl: false
  18045. });
  18046. super(player, options_);
  18047. this.trackLiveHandler_ = () => this.trackLive_();
  18048. this.handlePlay_ = e => this.handlePlay(e);
  18049. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  18050. this.handleSeeked_ = e => this.handleSeeked(e);
  18051. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  18052. this.reset_();
  18053. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  18054. // we should try to toggle tracking on canplay as native playback engines, like Safari
  18055. // may not have the proper values for things like seekableEnd until then
  18056. this.on(this.player_, 'canplay', () => this.toggleTracking());
  18057. }
  18058. /**
  18059. * all the functionality for tracking when seek end changes
  18060. * and for tracking how far past seek end we should be
  18061. */
  18062. trackLive_() {
  18063. const seekable = this.player_.seekable();
  18064. // skip undefined seekable
  18065. if (!seekable || !seekable.length) {
  18066. return;
  18067. }
  18068. const newTime = Number(window.performance.now().toFixed(4));
  18069. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  18070. this.lastTime_ = newTime;
  18071. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  18072. const liveCurrentTime = this.liveCurrentTime();
  18073. const currentTime = this.player_.currentTime();
  18074. // we are behind live if any are true
  18075. // 1. the player is paused
  18076. // 2. the user seeked to a location 2 seconds away from live
  18077. // 3. the difference between live and current time is greater
  18078. // liveTolerance which defaults to 15s
  18079. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  18080. // we cannot be behind if
  18081. // 1. until we have not seen a timeupdate yet
  18082. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  18083. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  18084. isBehind = false;
  18085. }
  18086. if (isBehind !== this.behindLiveEdge_) {
  18087. this.behindLiveEdge_ = isBehind;
  18088. this.trigger('liveedgechange');
  18089. }
  18090. }
  18091. /**
  18092. * handle a durationchange event on the player
  18093. * and start/stop tracking accordingly.
  18094. */
  18095. handleDurationchange() {
  18096. this.toggleTracking();
  18097. }
  18098. /**
  18099. * start/stop tracking
  18100. */
  18101. toggleTracking() {
  18102. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  18103. if (this.player_.options_.liveui) {
  18104. this.player_.addClass('vjs-liveui');
  18105. }
  18106. this.startTracking();
  18107. } else {
  18108. this.player_.removeClass('vjs-liveui');
  18109. this.stopTracking();
  18110. }
  18111. }
  18112. /**
  18113. * start tracking live playback
  18114. */
  18115. startTracking() {
  18116. if (this.isTracking()) {
  18117. return;
  18118. }
  18119. // If we haven't seen a timeupdate, we need to check whether playback
  18120. // began before this component started tracking. This can happen commonly
  18121. // when using autoplay.
  18122. if (!this.timeupdateSeen_) {
  18123. this.timeupdateSeen_ = this.player_.hasStarted();
  18124. }
  18125. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  18126. this.trackLive_();
  18127. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18128. if (!this.timeupdateSeen_) {
  18129. this.one(this.player_, 'play', this.handlePlay_);
  18130. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18131. } else {
  18132. this.on(this.player_, 'seeked', this.handleSeeked_);
  18133. }
  18134. }
  18135. /**
  18136. * handle the first timeupdate on the player if it wasn't already playing
  18137. * when live tracker started tracking.
  18138. */
  18139. handleFirstTimeupdate() {
  18140. this.timeupdateSeen_ = true;
  18141. this.on(this.player_, 'seeked', this.handleSeeked_);
  18142. }
  18143. /**
  18144. * Keep track of what time a seek starts, and listen for seeked
  18145. * to find where a seek ends.
  18146. */
  18147. handleSeeked() {
  18148. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  18149. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  18150. this.nextSeekedFromUser_ = false;
  18151. this.trackLive_();
  18152. }
  18153. /**
  18154. * handle the first play on the player, and make sure that we seek
  18155. * right to the live edge.
  18156. */
  18157. handlePlay() {
  18158. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18159. }
  18160. /**
  18161. * Stop tracking, and set all internal variables to
  18162. * their initial value.
  18163. */
  18164. reset_() {
  18165. this.lastTime_ = -1;
  18166. this.pastSeekEnd_ = 0;
  18167. this.lastSeekEnd_ = -1;
  18168. this.behindLiveEdge_ = true;
  18169. this.timeupdateSeen_ = false;
  18170. this.seekedBehindLive_ = false;
  18171. this.nextSeekedFromUser_ = false;
  18172. this.clearInterval(this.trackingInterval_);
  18173. this.trackingInterval_ = null;
  18174. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18175. this.off(this.player_, 'seeked', this.handleSeeked_);
  18176. this.off(this.player_, 'play', this.handlePlay_);
  18177. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18178. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18179. }
  18180. /**
  18181. * The next seeked event is from the user. Meaning that any seek
  18182. * > 2s behind live will be considered behind live for real and
  18183. * liveTolerance will be ignored.
  18184. */
  18185. nextSeekedFromUser() {
  18186. this.nextSeekedFromUser_ = true;
  18187. }
  18188. /**
  18189. * stop tracking live playback
  18190. */
  18191. stopTracking() {
  18192. if (!this.isTracking()) {
  18193. return;
  18194. }
  18195. this.reset_();
  18196. this.trigger('liveedgechange');
  18197. }
  18198. /**
  18199. * A helper to get the player seekable end
  18200. * so that we don't have to null check everywhere
  18201. *
  18202. * @return {number}
  18203. * The furthest seekable end or Infinity.
  18204. */
  18205. seekableEnd() {
  18206. const seekable = this.player_.seekable();
  18207. const seekableEnds = [];
  18208. let i = seekable ? seekable.length : 0;
  18209. while (i--) {
  18210. seekableEnds.push(seekable.end(i));
  18211. }
  18212. // grab the furthest seekable end after sorting, or if there are none
  18213. // default to Infinity
  18214. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  18215. }
  18216. /**
  18217. * A helper to get the player seekable start
  18218. * so that we don't have to null check everywhere
  18219. *
  18220. * @return {number}
  18221. * The earliest seekable start or 0.
  18222. */
  18223. seekableStart() {
  18224. const seekable = this.player_.seekable();
  18225. const seekableStarts = [];
  18226. let i = seekable ? seekable.length : 0;
  18227. while (i--) {
  18228. seekableStarts.push(seekable.start(i));
  18229. }
  18230. // grab the first seekable start after sorting, or if there are none
  18231. // default to 0
  18232. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  18233. }
  18234. /**
  18235. * Get the live time window aka
  18236. * the amount of time between seekable start and
  18237. * live current time.
  18238. *
  18239. * @return {number}
  18240. * The amount of seconds that are seekable in
  18241. * the live video.
  18242. */
  18243. liveWindow() {
  18244. const liveCurrentTime = this.liveCurrentTime();
  18245. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  18246. if (liveCurrentTime === Infinity) {
  18247. return 0;
  18248. }
  18249. return liveCurrentTime - this.seekableStart();
  18250. }
  18251. /**
  18252. * Determines if the player is live, only checks if this component
  18253. * is tracking live playback or not
  18254. *
  18255. * @return {boolean}
  18256. * Whether liveTracker is tracking
  18257. */
  18258. isLive() {
  18259. return this.isTracking();
  18260. }
  18261. /**
  18262. * Determines if currentTime is at the live edge and won't fall behind
  18263. * on each seekableendchange
  18264. *
  18265. * @return {boolean}
  18266. * Whether playback is at the live edge
  18267. */
  18268. atLiveEdge() {
  18269. return !this.behindLiveEdge();
  18270. }
  18271. /**
  18272. * get what we expect the live current time to be
  18273. *
  18274. * @return {number}
  18275. * The expected live current time
  18276. */
  18277. liveCurrentTime() {
  18278. return this.pastSeekEnd() + this.seekableEnd();
  18279. }
  18280. /**
  18281. * The number of seconds that have occurred after seekable end
  18282. * changed. This will be reset to 0 once seekable end changes.
  18283. *
  18284. * @return {number}
  18285. * Seconds past the current seekable end
  18286. */
  18287. pastSeekEnd() {
  18288. const seekableEnd = this.seekableEnd();
  18289. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  18290. this.pastSeekEnd_ = 0;
  18291. }
  18292. this.lastSeekEnd_ = seekableEnd;
  18293. return this.pastSeekEnd_;
  18294. }
  18295. /**
  18296. * If we are currently behind the live edge, aka currentTime will be
  18297. * behind on a seekableendchange
  18298. *
  18299. * @return {boolean}
  18300. * If we are behind the live edge
  18301. */
  18302. behindLiveEdge() {
  18303. return this.behindLiveEdge_;
  18304. }
  18305. /**
  18306. * Whether live tracker is currently tracking or not.
  18307. */
  18308. isTracking() {
  18309. return typeof this.trackingInterval_ === 'number';
  18310. }
  18311. /**
  18312. * Seek to the live edge if we are behind the live edge
  18313. */
  18314. seekToLiveEdge() {
  18315. this.seekedBehindLive_ = false;
  18316. if (this.atLiveEdge()) {
  18317. return;
  18318. }
  18319. this.nextSeekedFromUser_ = false;
  18320. this.player_.currentTime(this.liveCurrentTime());
  18321. }
  18322. /**
  18323. * Dispose of liveTracker
  18324. */
  18325. dispose() {
  18326. this.stopTracking();
  18327. super.dispose();
  18328. }
  18329. }
  18330. Component.registerComponent('LiveTracker', LiveTracker);
  18331. /**
  18332. * Displays an element over the player which contains an optional title and
  18333. * description for the current content.
  18334. *
  18335. * Much of the code for this component originated in the now obsolete
  18336. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  18337. *
  18338. * @extends Component
  18339. */
  18340. class TitleBar extends Component {
  18341. constructor(player, options) {
  18342. super(player, options);
  18343. this.on('statechanged', e => this.updateDom_());
  18344. this.updateDom_();
  18345. }
  18346. /**
  18347. * Create the `TitleBar`'s DOM element
  18348. *
  18349. * @return {Element}
  18350. * The element that was created.
  18351. */
  18352. createEl() {
  18353. this.els = {
  18354. title: createEl('div', {
  18355. className: 'vjs-title-bar-title',
  18356. id: `vjs-title-bar-title-${newGUID()}`
  18357. }),
  18358. description: createEl('div', {
  18359. className: 'vjs-title-bar-description',
  18360. id: `vjs-title-bar-description-${newGUID()}`
  18361. })
  18362. };
  18363. return createEl('div', {
  18364. className: 'vjs-title-bar'
  18365. }, {}, values(this.els));
  18366. }
  18367. /**
  18368. * Updates the DOM based on the component's state object.
  18369. */
  18370. updateDom_() {
  18371. const tech = this.player_.tech_;
  18372. const techEl = tech && tech.el_;
  18373. const techAriaAttrs = {
  18374. title: 'aria-labelledby',
  18375. description: 'aria-describedby'
  18376. };
  18377. ['title', 'description'].forEach(k => {
  18378. const value = this.state[k];
  18379. const el = this.els[k];
  18380. const techAriaAttr = techAriaAttrs[k];
  18381. emptyEl(el);
  18382. if (value) {
  18383. textContent(el, value);
  18384. }
  18385. // If there is a tech element available, update its ARIA attributes
  18386. // according to whether a title and/or description have been provided.
  18387. if (techEl) {
  18388. techEl.removeAttribute(techAriaAttr);
  18389. if (value) {
  18390. techEl.setAttribute(techAriaAttr, el.id);
  18391. }
  18392. }
  18393. });
  18394. if (this.state.title || this.state.description) {
  18395. this.show();
  18396. } else {
  18397. this.hide();
  18398. }
  18399. }
  18400. /**
  18401. * Update the contents of the title bar component with new title and
  18402. * description text.
  18403. *
  18404. * If both title and description are missing, the title bar will be hidden.
  18405. *
  18406. * If either title or description are present, the title bar will be visible.
  18407. *
  18408. * NOTE: Any previously set value will be preserved. To unset a previously
  18409. * set value, you must pass an empty string or null.
  18410. *
  18411. * For example:
  18412. *
  18413. * ```
  18414. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  18415. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  18416. * update({title: ''}) // title: '', description: 'bar2'
  18417. * update({title: 'foo', description: null}) // title: 'foo', description: null
  18418. * ```
  18419. *
  18420. * @param {Object} [options={}]
  18421. * An options object. When empty, the title bar will be hidden.
  18422. *
  18423. * @param {string} [options.title]
  18424. * A title to display in the title bar.
  18425. *
  18426. * @param {string} [options.description]
  18427. * A description to display in the title bar.
  18428. */
  18429. update(options) {
  18430. this.setState(options);
  18431. }
  18432. /**
  18433. * Dispose the component.
  18434. */
  18435. dispose() {
  18436. const tech = this.player_.tech_;
  18437. const techEl = tech && tech.el_;
  18438. if (techEl) {
  18439. techEl.removeAttribute('aria-labelledby');
  18440. techEl.removeAttribute('aria-describedby');
  18441. }
  18442. super.dispose();
  18443. this.els = null;
  18444. }
  18445. }
  18446. Component.registerComponent('TitleBar', TitleBar);
  18447. /** @import Player from './player' */
  18448. /**
  18449. * @typedef {object} TransientButtonOptions
  18450. * @property {string} [controlText] Control text, usually visible for these buttons
  18451. * @property {number} [initialDisplay=4000] Time in ms that button should initially remain visible
  18452. * @property {Array<'top'|'neartop'|'bottom'|'left'|'right'>} [position] Array of position strings to add basic styles for positioning
  18453. * @property {string} [className] Class(es) to add
  18454. * @property {boolean} [takeFocus=false] Whether element sohuld take focus when shown
  18455. * @property {Function} [clickHandler] Function called on button activation
  18456. */
  18457. /** @type {TransientButtonOptions} */
  18458. const defaults = {
  18459. initialDisplay: 4000,
  18460. position: [],
  18461. takeFocus: false
  18462. };
  18463. /**
  18464. * A floating transient button.
  18465. * It's recommended to insert these buttons _before_ the control bar with the this argument to `addChild`
  18466. * for a logical tab order.
  18467. *
  18468. * @example
  18469. * ```
  18470. * player.addChild(
  18471. * 'TransientButton',
  18472. * options,
  18473. * player.children().indexOf(player.getChild("ControlBar"))
  18474. * )
  18475. * ```
  18476. *
  18477. * @extends Button
  18478. */
  18479. class TransientButton extends Button {
  18480. /**
  18481. * TransientButton constructor
  18482. *
  18483. * @param {Player} player The button's player
  18484. * @param {TransientButtonOptions} options Options for the transient button
  18485. */
  18486. constructor(player, options) {
  18487. options = merge(defaults, options);
  18488. super(player, options);
  18489. this.controlText(options.controlText);
  18490. this.hide();
  18491. // When shown, the float button will be visible even if the user is inactive.
  18492. // Clear this if there is any interaction.
  18493. this.on(this.player_, ['useractive', 'userinactive'], e => {
  18494. this.removeClass('force-display');
  18495. });
  18496. }
  18497. /**
  18498. * Return CSS class including position classes
  18499. *
  18500. * @return {string} CSS class list
  18501. */
  18502. buildCSSClass() {
  18503. return `vjs-transient-button focus-visible ${this.options_.position.map(c => `vjs-${c}`).join(' ')}`;
  18504. }
  18505. /**
  18506. * Create the button element
  18507. *
  18508. * @return {HTMLButtonElement} The button element
  18509. */
  18510. createEl() {
  18511. /** @type HTMLButtonElement */
  18512. const el = createEl('button', {}, {
  18513. type: 'button',
  18514. class: this.buildCSSClass()
  18515. }, createEl('span'));
  18516. this.controlTextEl_ = el.querySelector('span');
  18517. return el;
  18518. }
  18519. /**
  18520. * Show the button. The button will remain visible for the `initialDisplay` time, default 4s,
  18521. * and when there is user activity.
  18522. */
  18523. show() {
  18524. super.show();
  18525. this.addClass('force-display');
  18526. if (this.options_.takeFocus) {
  18527. this.el().focus({
  18528. preventScroll: true
  18529. });
  18530. }
  18531. this.forceDisplayTimeout = this.player_.setTimeout(() => {
  18532. this.removeClass('force-display');
  18533. }, this.options_.initialDisplay);
  18534. }
  18535. /**
  18536. * Hide the display, even if during the `initialDisplay` time.
  18537. */
  18538. hide() {
  18539. this.removeClass('force-display');
  18540. super.hide();
  18541. }
  18542. /**
  18543. * Dispose the component
  18544. */
  18545. dispose() {
  18546. this.player_.clearTimeout(this.forceDisplayTimeout);
  18547. super.dispose();
  18548. }
  18549. }
  18550. Component.registerComponent('TransientButton', TransientButton);
  18551. /** @import Html5 from './html5' */
  18552. /**
  18553. * This function is used to fire a sourceset when there is something
  18554. * similar to `mediaEl.load()` being called. It will try to find the source via
  18555. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  18556. * with the source that was found or empty string if we cannot know. If it cannot
  18557. * find a source then `sourceset` will not be fired.
  18558. *
  18559. * @param {Html5} tech
  18560. * The tech object that sourceset was setup on
  18561. *
  18562. * @return {boolean}
  18563. * returns false if the sourceset was not fired and true otherwise.
  18564. */
  18565. const sourcesetLoad = tech => {
  18566. const el = tech.el();
  18567. // if `el.src` is set, that source will be loaded.
  18568. if (el.hasAttribute('src')) {
  18569. tech.triggerSourceset(el.src);
  18570. return true;
  18571. }
  18572. /**
  18573. * Since there isn't a src property on the media element, source elements will be used for
  18574. * implementing the source selection algorithm. This happens asynchronously and
  18575. * for most cases were there is more than one source we cannot tell what source will
  18576. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  18577. * going to do that. There are three special cases that we do handle here though:
  18578. *
  18579. * 1. If there are no sources, do not fire `sourceset`.
  18580. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  18581. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  18582. * That will be our src.
  18583. */
  18584. const sources = tech.$$('source');
  18585. const srcUrls = [];
  18586. let src = '';
  18587. // if there are no sources, do not fire sourceset
  18588. if (!sources.length) {
  18589. return false;
  18590. }
  18591. // only count valid/non-duplicate source elements
  18592. for (let i = 0; i < sources.length; i++) {
  18593. const url = sources[i].src;
  18594. if (url && srcUrls.indexOf(url) === -1) {
  18595. srcUrls.push(url);
  18596. }
  18597. }
  18598. // there were no valid sources
  18599. if (!srcUrls.length) {
  18600. return false;
  18601. }
  18602. // there is only one valid source element url
  18603. // use that
  18604. if (srcUrls.length === 1) {
  18605. src = srcUrls[0];
  18606. }
  18607. tech.triggerSourceset(src);
  18608. return true;
  18609. };
  18610. /**
  18611. * our implementation of an `innerHTML` descriptor for browsers
  18612. * that do not have one.
  18613. */
  18614. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  18615. get() {
  18616. return this.cloneNode(true).innerHTML;
  18617. },
  18618. set(v) {
  18619. // make a dummy node to use innerHTML on
  18620. const dummy = document.createElement(this.nodeName.toLowerCase());
  18621. // set innerHTML to the value provided
  18622. dummy.innerHTML = v;
  18623. // make a document fragment to hold the nodes from dummy
  18624. const docFrag = document.createDocumentFragment();
  18625. // copy all of the nodes created by the innerHTML on dummy
  18626. // to the document fragment
  18627. while (dummy.childNodes.length) {
  18628. docFrag.appendChild(dummy.childNodes[0]);
  18629. }
  18630. // remove content
  18631. this.innerText = '';
  18632. // now we add all of that html in one by appending the
  18633. // document fragment. This is how innerHTML does it.
  18634. window.Element.prototype.appendChild.call(this, docFrag);
  18635. // then return the result that innerHTML's setter would
  18636. return this.innerHTML;
  18637. }
  18638. });
  18639. /**
  18640. * Get a property descriptor given a list of priorities and the
  18641. * property to get.
  18642. */
  18643. const getDescriptor = (priority, prop) => {
  18644. let descriptor = {};
  18645. for (let i = 0; i < priority.length; i++) {
  18646. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  18647. if (descriptor && descriptor.set && descriptor.get) {
  18648. break;
  18649. }
  18650. }
  18651. descriptor.enumerable = true;
  18652. descriptor.configurable = true;
  18653. return descriptor;
  18654. };
  18655. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  18656. /**
  18657. * Patches browser internal functions so that we can tell synchronously
  18658. * if a `<source>` was appended to the media element. For some reason this
  18659. * causes a `sourceset` if the the media element is ready and has no source.
  18660. * This happens when:
  18661. * - The page has just loaded and the media element does not have a source.
  18662. * - The media element was emptied of all sources, then `load()` was called.
  18663. *
  18664. * It does this by patching the following functions/properties when they are supported:
  18665. *
  18666. * - `append()` - can be used to add a `<source>` element to the media element
  18667. * - `appendChild()` - can be used to add a `<source>` element to the media element
  18668. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  18669. * - `innerHTML` - can be used to add a `<source>` element to the media element
  18670. *
  18671. * @param {Html5} tech
  18672. * The tech object that sourceset is being setup on.
  18673. */
  18674. const firstSourceWatch = function (tech) {
  18675. const el = tech.el();
  18676. // make sure firstSourceWatch isn't setup twice.
  18677. if (el.resetSourceWatch_) {
  18678. return;
  18679. }
  18680. const old = {};
  18681. const innerDescriptor = getInnerHTMLDescriptor(tech);
  18682. const appendWrapper = appendFn => (...args) => {
  18683. const retval = appendFn.apply(el, args);
  18684. sourcesetLoad(tech);
  18685. return retval;
  18686. };
  18687. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  18688. if (!el[k]) {
  18689. return;
  18690. }
  18691. // store the old function
  18692. old[k] = el[k];
  18693. // call the old function with a sourceset if a source
  18694. // was loaded
  18695. el[k] = appendWrapper(old[k]);
  18696. });
  18697. Object.defineProperty(el, 'innerHTML', merge(innerDescriptor, {
  18698. set: appendWrapper(innerDescriptor.set)
  18699. }));
  18700. el.resetSourceWatch_ = () => {
  18701. el.resetSourceWatch_ = null;
  18702. Object.keys(old).forEach(k => {
  18703. el[k] = old[k];
  18704. });
  18705. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  18706. };
  18707. // on the first sourceset, we need to revert our changes
  18708. tech.one('sourceset', el.resetSourceWatch_);
  18709. };
  18710. /**
  18711. * our implementation of a `src` descriptor for browsers
  18712. * that do not have one
  18713. */
  18714. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  18715. get() {
  18716. if (this.hasAttribute('src')) {
  18717. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  18718. }
  18719. return '';
  18720. },
  18721. set(v) {
  18722. window.Element.prototype.setAttribute.call(this, 'src', v);
  18723. return v;
  18724. }
  18725. });
  18726. const getSrcDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  18727. /**
  18728. * setup `sourceset` handling on the `Html5` tech. This function
  18729. * patches the following element properties/functions:
  18730. *
  18731. * - `src` - to determine when `src` is set
  18732. * - `setAttribute()` - to determine when `src` is set
  18733. * - `load()` - this re-triggers the source selection algorithm, and can
  18734. * cause a sourceset.
  18735. *
  18736. * If there is no source when we are adding `sourceset` support or during a `load()`
  18737. * we also patch the functions listed in `firstSourceWatch`.
  18738. *
  18739. * @param {Html5} tech
  18740. * The tech to patch
  18741. */
  18742. const setupSourceset = function (tech) {
  18743. if (!tech.featuresSourceset) {
  18744. return;
  18745. }
  18746. const el = tech.el();
  18747. // make sure sourceset isn't setup twice.
  18748. if (el.resetSourceset_) {
  18749. return;
  18750. }
  18751. const srcDescriptor = getSrcDescriptor(tech);
  18752. const oldSetAttribute = el.setAttribute;
  18753. const oldLoad = el.load;
  18754. Object.defineProperty(el, 'src', merge(srcDescriptor, {
  18755. set: v => {
  18756. const retval = srcDescriptor.set.call(el, v);
  18757. // we use the getter here to get the actual value set on src
  18758. tech.triggerSourceset(el.src);
  18759. return retval;
  18760. }
  18761. }));
  18762. el.setAttribute = (n, v) => {
  18763. const retval = oldSetAttribute.call(el, n, v);
  18764. if (/src/i.test(n)) {
  18765. tech.triggerSourceset(el.src);
  18766. }
  18767. return retval;
  18768. };
  18769. el.load = () => {
  18770. const retval = oldLoad.call(el);
  18771. // if load was called, but there was no source to fire
  18772. // sourceset on. We have to watch for a source append
  18773. // as that can trigger a `sourceset` when the media element
  18774. // has no source
  18775. if (!sourcesetLoad(tech)) {
  18776. tech.triggerSourceset('');
  18777. firstSourceWatch(tech);
  18778. }
  18779. return retval;
  18780. };
  18781. if (el.currentSrc) {
  18782. tech.triggerSourceset(el.currentSrc);
  18783. } else if (!sourcesetLoad(tech)) {
  18784. firstSourceWatch(tech);
  18785. }
  18786. el.resetSourceset_ = () => {
  18787. el.resetSourceset_ = null;
  18788. el.load = oldLoad;
  18789. el.setAttribute = oldSetAttribute;
  18790. Object.defineProperty(el, 'src', srcDescriptor);
  18791. if (el.resetSourceWatch_) {
  18792. el.resetSourceWatch_();
  18793. }
  18794. };
  18795. };
  18796. /**
  18797. * @file html5.js
  18798. */
  18799. /**
  18800. * HTML5 Media Controller - Wrapper for HTML5 Media API
  18801. *
  18802. * @mixes Tech~SourceHandlerAdditions
  18803. * @extends Tech
  18804. */
  18805. class Html5 extends Tech {
  18806. /**
  18807. * Create an instance of this Tech.
  18808. *
  18809. * @param {Object} [options]
  18810. * The key/value store of player options.
  18811. *
  18812. * @param {Function} [ready]
  18813. * Callback function to call when the `HTML5` Tech is ready.
  18814. */
  18815. constructor(options, ready) {
  18816. super(options, ready);
  18817. const source = options.source;
  18818. let crossoriginTracks = false;
  18819. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  18820. // Set the source if one is provided
  18821. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  18822. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  18823. // anyway so the error gets fired.
  18824. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  18825. this.setSource(source);
  18826. } else {
  18827. this.handleLateInit_(this.el_);
  18828. }
  18829. // setup sourceset after late sourceset/init
  18830. if (options.enableSourceset) {
  18831. this.setupSourcesetHandling_();
  18832. }
  18833. this.isScrubbing_ = false;
  18834. if (this.el_.hasChildNodes()) {
  18835. const nodes = this.el_.childNodes;
  18836. let nodesLength = nodes.length;
  18837. const removeNodes = [];
  18838. while (nodesLength--) {
  18839. const node = nodes[nodesLength];
  18840. const nodeName = node.nodeName.toLowerCase();
  18841. if (nodeName === 'track') {
  18842. if (!this.featuresNativeTextTracks) {
  18843. // Empty video tag tracks so the built-in player doesn't use them also.
  18844. // This may not be fast enough to stop HTML5 browsers from reading the tags
  18845. // so we'll need to turn off any default tracks if we're manually doing
  18846. // captions and subtitles. videoElement.textTracks
  18847. removeNodes.push(node);
  18848. } else {
  18849. // store HTMLTrackElement and TextTrack to remote list
  18850. this.remoteTextTrackEls().addTrackElement_(node);
  18851. this.remoteTextTracks().addTrack(node.track);
  18852. this.textTracks().addTrack(node.track);
  18853. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  18854. crossoriginTracks = true;
  18855. }
  18856. }
  18857. }
  18858. }
  18859. for (let i = 0; i < removeNodes.length; i++) {
  18860. this.el_.removeChild(removeNodes[i]);
  18861. }
  18862. }
  18863. this.proxyNativeTracks_();
  18864. if (this.featuresNativeTextTracks && crossoriginTracks) {
  18865. 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.');
  18866. }
  18867. // prevent iOS Safari from disabling metadata text tracks during native playback
  18868. this.restoreMetadataTracksInIOSNativePlayer_();
  18869. // Determine if native controls should be used
  18870. // Our goal should be to get the custom controls on mobile solid everywhere
  18871. // so we can remove this all together. Right now this will block custom
  18872. // controls on touch enabled laptops like the Chrome Pixel
  18873. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  18874. this.setControls(true);
  18875. }
  18876. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  18877. // into a `fullscreenchange` event
  18878. this.proxyWebkitFullscreen_();
  18879. this.triggerReady();
  18880. }
  18881. /**
  18882. * Dispose of `HTML5` media element and remove all tracks.
  18883. */
  18884. dispose() {
  18885. if (this.el_ && this.el_.resetSourceset_) {
  18886. this.el_.resetSourceset_();
  18887. }
  18888. Html5.disposeMediaElement(this.el_);
  18889. this.options_ = null;
  18890. // tech will handle clearing of the emulated track list
  18891. super.dispose();
  18892. }
  18893. /**
  18894. * Modify the media element so that we can detect when
  18895. * the source is changed. Fires `sourceset` just after the source has changed
  18896. */
  18897. setupSourcesetHandling_() {
  18898. setupSourceset(this);
  18899. }
  18900. /**
  18901. * When a captions track is enabled in the iOS Safari native player, all other
  18902. * tracks are disabled (including metadata tracks), which nulls all of their
  18903. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  18904. * state in those cases so that cue points are not needlessly lost.
  18905. *
  18906. * @private
  18907. */
  18908. restoreMetadataTracksInIOSNativePlayer_() {
  18909. const textTracks = this.textTracks();
  18910. let metadataTracksPreFullscreenState;
  18911. // captures a snapshot of every metadata track's current state
  18912. const takeMetadataTrackSnapshot = () => {
  18913. metadataTracksPreFullscreenState = [];
  18914. for (let i = 0; i < textTracks.length; i++) {
  18915. const track = textTracks[i];
  18916. if (track.kind === 'metadata') {
  18917. metadataTracksPreFullscreenState.push({
  18918. track,
  18919. storedMode: track.mode
  18920. });
  18921. }
  18922. }
  18923. };
  18924. // snapshot each metadata track's initial state, and update the snapshot
  18925. // each time there is a track 'change' event
  18926. takeMetadataTrackSnapshot();
  18927. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  18928. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  18929. const restoreTrackMode = () => {
  18930. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  18931. const storedTrack = metadataTracksPreFullscreenState[i];
  18932. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  18933. storedTrack.track.mode = storedTrack.storedMode;
  18934. }
  18935. }
  18936. // we only want this handler to be executed on the first 'change' event
  18937. textTracks.removeEventListener('change', restoreTrackMode);
  18938. };
  18939. // when we enter fullscreen playback, stop updating the snapshot and
  18940. // restore all track modes to their pre-fullscreen state
  18941. this.on('webkitbeginfullscreen', () => {
  18942. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  18943. // remove the listener before adding it just in case it wasn't previously removed
  18944. textTracks.removeEventListener('change', restoreTrackMode);
  18945. textTracks.addEventListener('change', restoreTrackMode);
  18946. });
  18947. // start updating the snapshot again after leaving fullscreen
  18948. this.on('webkitendfullscreen', () => {
  18949. // remove the listener before adding it just in case it wasn't previously removed
  18950. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  18951. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  18952. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  18953. textTracks.removeEventListener('change', restoreTrackMode);
  18954. });
  18955. }
  18956. /**
  18957. * Attempt to force override of tracks for the given type
  18958. *
  18959. * @param {string} type - Track type to override, possible values include 'Audio',
  18960. * 'Video', and 'Text'.
  18961. * @param {boolean} override - If set to true native audio/video will be overridden,
  18962. * otherwise native audio/video will potentially be used.
  18963. * @private
  18964. */
  18965. overrideNative_(type, override) {
  18966. // If there is no behavioral change don't add/remove listeners
  18967. if (override !== this[`featuresNative${type}Tracks`]) {
  18968. return;
  18969. }
  18970. const lowerCaseType = type.toLowerCase();
  18971. if (this[`${lowerCaseType}TracksListeners_`]) {
  18972. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  18973. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  18974. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  18975. });
  18976. }
  18977. this[`featuresNative${type}Tracks`] = !override;
  18978. this[`${lowerCaseType}TracksListeners_`] = null;
  18979. this.proxyNativeTracksForType_(lowerCaseType);
  18980. }
  18981. /**
  18982. * Attempt to force override of native audio tracks.
  18983. *
  18984. * @param {boolean} override - If set to true native audio will be overridden,
  18985. * otherwise native audio will potentially be used.
  18986. */
  18987. overrideNativeAudioTracks(override) {
  18988. this.overrideNative_('Audio', override);
  18989. }
  18990. /**
  18991. * Attempt to force override of native video tracks.
  18992. *
  18993. * @param {boolean} override - If set to true native video will be overridden,
  18994. * otherwise native video will potentially be used.
  18995. */
  18996. overrideNativeVideoTracks(override) {
  18997. this.overrideNative_('Video', override);
  18998. }
  18999. /**
  19000. * Proxy native track list events for the given type to our track
  19001. * lists if the browser we are playing in supports that type of track list.
  19002. *
  19003. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  19004. * @private
  19005. */
  19006. proxyNativeTracksForType_(name) {
  19007. const props = NORMAL[name];
  19008. const elTracks = this.el()[props.getterName];
  19009. const techTracks = this[props.getterName]();
  19010. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  19011. return;
  19012. }
  19013. const listeners = {
  19014. change: e => {
  19015. const event = {
  19016. type: 'change',
  19017. target: techTracks,
  19018. currentTarget: techTracks,
  19019. srcElement: techTracks
  19020. };
  19021. techTracks.trigger(event);
  19022. // if we are a text track change event, we should also notify the
  19023. // remote text track list. This can potentially cause a false positive
  19024. // if we were to get a change event on a non-remote track and
  19025. // we triggered the event on the remote text track list which doesn't
  19026. // contain that track. However, best practices mean looping through the
  19027. // list of tracks and searching for the appropriate mode value, so,
  19028. // this shouldn't pose an issue
  19029. if (name === 'text') {
  19030. this[REMOTE.remoteText.getterName]().trigger(event);
  19031. }
  19032. },
  19033. addtrack(e) {
  19034. techTracks.addTrack(e.track);
  19035. },
  19036. removetrack(e) {
  19037. techTracks.removeTrack(e.track);
  19038. }
  19039. };
  19040. const removeOldTracks = function () {
  19041. const removeTracks = [];
  19042. for (let i = 0; i < techTracks.length; i++) {
  19043. let found = false;
  19044. for (let j = 0; j < elTracks.length; j++) {
  19045. if (elTracks[j] === techTracks[i]) {
  19046. found = true;
  19047. break;
  19048. }
  19049. }
  19050. if (!found) {
  19051. removeTracks.push(techTracks[i]);
  19052. }
  19053. }
  19054. while (removeTracks.length) {
  19055. techTracks.removeTrack(removeTracks.shift());
  19056. }
  19057. };
  19058. this[props.getterName + 'Listeners_'] = listeners;
  19059. Object.keys(listeners).forEach(eventName => {
  19060. const listener = listeners[eventName];
  19061. elTracks.addEventListener(eventName, listener);
  19062. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  19063. });
  19064. // Remove (native) tracks that are not used anymore
  19065. this.on('loadstart', removeOldTracks);
  19066. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  19067. }
  19068. /**
  19069. * Proxy all native track list events to our track lists if the browser we are playing
  19070. * in supports that type of track list.
  19071. *
  19072. * @private
  19073. */
  19074. proxyNativeTracks_() {
  19075. NORMAL.names.forEach(name => {
  19076. this.proxyNativeTracksForType_(name);
  19077. });
  19078. }
  19079. /**
  19080. * Create the `Html5` Tech's DOM element.
  19081. *
  19082. * @return {Element}
  19083. * The element that gets created.
  19084. */
  19085. createEl() {
  19086. let el = this.options_.tag;
  19087. // Check if this browser supports moving the element into the box.
  19088. // On the iPhone video will break if you move the element,
  19089. // So we have to create a brand new element.
  19090. // If we ingested the player div, we do not need to move the media element.
  19091. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  19092. // If the original tag is still there, clone and remove it.
  19093. if (el) {
  19094. const clone = el.cloneNode(true);
  19095. if (el.parentNode) {
  19096. el.parentNode.insertBefore(clone, el);
  19097. }
  19098. Html5.disposeMediaElement(el);
  19099. el = clone;
  19100. } else {
  19101. el = document.createElement('video');
  19102. // determine if native controls should be used
  19103. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  19104. const attributes = merge({}, tagAttributes);
  19105. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  19106. delete attributes.controls;
  19107. }
  19108. setAttributes(el, Object.assign(attributes, {
  19109. id: this.options_.techId,
  19110. class: 'vjs-tech'
  19111. }));
  19112. }
  19113. el.playerId = this.options_.playerId;
  19114. }
  19115. if (typeof this.options_.preload !== 'undefined') {
  19116. setAttribute(el, 'preload', this.options_.preload);
  19117. }
  19118. if (this.options_.disablePictureInPicture !== undefined) {
  19119. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  19120. }
  19121. // Update specific tag settings, in case they were overridden
  19122. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  19123. // when iOS/Safari or other browsers attempt to autoplay.
  19124. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  19125. for (let i = 0; i < settingsAttrs.length; i++) {
  19126. const attr = settingsAttrs[i];
  19127. const value = this.options_[attr];
  19128. if (typeof value !== 'undefined') {
  19129. if (value) {
  19130. setAttribute(el, attr, attr);
  19131. } else {
  19132. removeAttribute(el, attr);
  19133. }
  19134. el[attr] = value;
  19135. }
  19136. }
  19137. return el;
  19138. }
  19139. /**
  19140. * This will be triggered if the loadstart event has already fired, before videojs was
  19141. * ready. Two known examples of when this can happen are:
  19142. * 1. If we're loading the playback object after it has started loading
  19143. * 2. The media is already playing the (often with autoplay on) then
  19144. *
  19145. * This function will fire another loadstart so that videojs can catchup.
  19146. *
  19147. * @fires Tech#loadstart
  19148. *
  19149. * @return {undefined}
  19150. * returns nothing.
  19151. */
  19152. handleLateInit_(el) {
  19153. if (el.networkState === 0 || el.networkState === 3) {
  19154. // The video element hasn't started loading the source yet
  19155. // or didn't find a source
  19156. return;
  19157. }
  19158. if (el.readyState === 0) {
  19159. // NetworkState is set synchronously BUT loadstart is fired at the
  19160. // end of the current stack, usually before setInterval(fn, 0).
  19161. // So at this point we know loadstart may have already fired or is
  19162. // about to fire, and either way the player hasn't seen it yet.
  19163. // We don't want to fire loadstart prematurely here and cause a
  19164. // double loadstart so we'll wait and see if it happens between now
  19165. // and the next loop, and fire it if not.
  19166. // HOWEVER, we also want to make sure it fires before loadedmetadata
  19167. // which could also happen between now and the next loop, so we'll
  19168. // watch for that also.
  19169. let loadstartFired = false;
  19170. const setLoadstartFired = function () {
  19171. loadstartFired = true;
  19172. };
  19173. this.on('loadstart', setLoadstartFired);
  19174. const triggerLoadstart = function () {
  19175. // We did miss the original loadstart. Make sure the player
  19176. // sees loadstart before loadedmetadata
  19177. if (!loadstartFired) {
  19178. this.trigger('loadstart');
  19179. }
  19180. };
  19181. this.on('loadedmetadata', triggerLoadstart);
  19182. this.ready(function () {
  19183. this.off('loadstart', setLoadstartFired);
  19184. this.off('loadedmetadata', triggerLoadstart);
  19185. if (!loadstartFired) {
  19186. // We did miss the original native loadstart. Fire it now.
  19187. this.trigger('loadstart');
  19188. }
  19189. });
  19190. return;
  19191. }
  19192. // From here on we know that loadstart already fired and we missed it.
  19193. // The other readyState events aren't as much of a problem if we double
  19194. // them, so not going to go to as much trouble as loadstart to prevent
  19195. // that unless we find reason to.
  19196. const eventsToTrigger = ['loadstart'];
  19197. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  19198. eventsToTrigger.push('loadedmetadata');
  19199. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  19200. if (el.readyState >= 2) {
  19201. eventsToTrigger.push('loadeddata');
  19202. }
  19203. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  19204. if (el.readyState >= 3) {
  19205. eventsToTrigger.push('canplay');
  19206. }
  19207. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  19208. if (el.readyState >= 4) {
  19209. eventsToTrigger.push('canplaythrough');
  19210. }
  19211. // We still need to give the player time to add event listeners
  19212. this.ready(function () {
  19213. eventsToTrigger.forEach(function (type) {
  19214. this.trigger(type);
  19215. }, this);
  19216. });
  19217. }
  19218. /**
  19219. * Set whether we are scrubbing or not.
  19220. * This is used to decide whether we should use `fastSeek` or not.
  19221. * `fastSeek` is used to provide trick play on Safari browsers.
  19222. *
  19223. * @param {boolean} isScrubbing
  19224. * - true for we are currently scrubbing
  19225. * - false for we are no longer scrubbing
  19226. */
  19227. setScrubbing(isScrubbing) {
  19228. this.isScrubbing_ = isScrubbing;
  19229. }
  19230. /**
  19231. * Get whether we are scrubbing or not.
  19232. *
  19233. * @return {boolean} isScrubbing
  19234. * - true for we are currently scrubbing
  19235. * - false for we are no longer scrubbing
  19236. */
  19237. scrubbing() {
  19238. return this.isScrubbing_;
  19239. }
  19240. /**
  19241. * Set current time for the `HTML5` tech.
  19242. *
  19243. * @param {number} seconds
  19244. * Set the current time of the media to this.
  19245. */
  19246. setCurrentTime(seconds) {
  19247. try {
  19248. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  19249. this.el_.fastSeek(seconds);
  19250. } else {
  19251. this.el_.currentTime = seconds;
  19252. }
  19253. } catch (e) {
  19254. log(e, 'Video is not ready. (Video.js)');
  19255. // this.warning(VideoJS.warnings.videoNotReady);
  19256. }
  19257. }
  19258. /**
  19259. * Get the current duration of the HTML5 media element.
  19260. *
  19261. * @return {number}
  19262. * The duration of the media or 0 if there is no duration.
  19263. */
  19264. duration() {
  19265. // Android Chrome will report duration as Infinity for VOD HLS until after
  19266. // playback has started, which triggers the live display erroneously.
  19267. // Return NaN if playback has not started and trigger a durationupdate once
  19268. // the duration can be reliably known.
  19269. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  19270. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  19271. // several with 0
  19272. const checkProgress = () => {
  19273. if (this.el_.currentTime > 0) {
  19274. // Trigger durationchange for genuinely live video
  19275. if (this.el_.duration === Infinity) {
  19276. this.trigger('durationchange');
  19277. }
  19278. this.off('timeupdate', checkProgress);
  19279. }
  19280. };
  19281. this.on('timeupdate', checkProgress);
  19282. return NaN;
  19283. }
  19284. return this.el_.duration || NaN;
  19285. }
  19286. /**
  19287. * Get the current width of the HTML5 media element.
  19288. *
  19289. * @return {number}
  19290. * The width of the HTML5 media element.
  19291. */
  19292. width() {
  19293. return this.el_.offsetWidth;
  19294. }
  19295. /**
  19296. * Get the current height of the HTML5 media element.
  19297. *
  19298. * @return {number}
  19299. * The height of the HTML5 media element.
  19300. */
  19301. height() {
  19302. return this.el_.offsetHeight;
  19303. }
  19304. /**
  19305. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  19306. * `fullscreenchange` event.
  19307. *
  19308. * @private
  19309. * @fires fullscreenchange
  19310. * @listens webkitendfullscreen
  19311. * @listens webkitbeginfullscreen
  19312. * @listens webkitbeginfullscreen
  19313. */
  19314. proxyWebkitFullscreen_() {
  19315. if (!('webkitDisplayingFullscreen' in this.el_)) {
  19316. return;
  19317. }
  19318. const endFn = function () {
  19319. this.trigger('fullscreenchange', {
  19320. isFullscreen: false
  19321. });
  19322. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  19323. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  19324. this.el_.controls = false;
  19325. }
  19326. };
  19327. const beginFn = function () {
  19328. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  19329. this.one('webkitendfullscreen', endFn);
  19330. this.trigger('fullscreenchange', {
  19331. isFullscreen: true,
  19332. // set a flag in case another tech triggers fullscreenchange
  19333. nativeIOSFullscreen: true
  19334. });
  19335. }
  19336. };
  19337. this.on('webkitbeginfullscreen', beginFn);
  19338. this.on('dispose', () => {
  19339. this.off('webkitbeginfullscreen', beginFn);
  19340. this.off('webkitendfullscreen', endFn);
  19341. });
  19342. }
  19343. /**
  19344. * Check if fullscreen is supported on the video el.
  19345. *
  19346. * @return {boolean}
  19347. * - True if fullscreen is supported.
  19348. * - False if fullscreen is not supported.
  19349. */
  19350. supportsFullScreen() {
  19351. return typeof this.el_.webkitEnterFullScreen === 'function';
  19352. }
  19353. /**
  19354. * Request that the `HTML5` Tech enter fullscreen.
  19355. */
  19356. enterFullScreen() {
  19357. const video = this.el_;
  19358. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  19359. // attempt to prime the video element for programmatic access
  19360. // this isn't necessary on the desktop but shouldn't hurt
  19361. silencePromise(this.el_.play());
  19362. // playing and pausing synchronously during the transition to fullscreen
  19363. // can get iOS ~6.1 devices into a play/pause loop
  19364. this.setTimeout(function () {
  19365. video.pause();
  19366. try {
  19367. video.webkitEnterFullScreen();
  19368. } catch (e) {
  19369. this.trigger('fullscreenerror', e);
  19370. }
  19371. }, 0);
  19372. } else {
  19373. try {
  19374. video.webkitEnterFullScreen();
  19375. } catch (e) {
  19376. this.trigger('fullscreenerror', e);
  19377. }
  19378. }
  19379. }
  19380. /**
  19381. * Request that the `HTML5` Tech exit fullscreen.
  19382. */
  19383. exitFullScreen() {
  19384. if (!this.el_.webkitDisplayingFullscreen) {
  19385. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  19386. return;
  19387. }
  19388. this.el_.webkitExitFullScreen();
  19389. }
  19390. /**
  19391. * Create a floating video window always on top of other windows so that users may
  19392. * continue consuming media while they interact with other content sites, or
  19393. * applications on their device.
  19394. *
  19395. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  19396. *
  19397. * @return {Promise}
  19398. * A promise with a Picture-in-Picture window.
  19399. */
  19400. requestPictureInPicture() {
  19401. return this.el_.requestPictureInPicture();
  19402. }
  19403. /**
  19404. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  19405. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  19406. * Needs to be checked later than the constructor
  19407. * This will be a false positive for clear sources loaded after a Fairplay source
  19408. *
  19409. * @param {function} cb function to call
  19410. * @return {number} id of request
  19411. */
  19412. requestVideoFrameCallback(cb) {
  19413. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19414. return this.el_.requestVideoFrameCallback(cb);
  19415. }
  19416. return super.requestVideoFrameCallback(cb);
  19417. }
  19418. /**
  19419. * Native or fallback requestVideoFrameCallback
  19420. *
  19421. * @param {number} id request id to cancel
  19422. */
  19423. cancelVideoFrameCallback(id) {
  19424. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19425. this.el_.cancelVideoFrameCallback(id);
  19426. } else {
  19427. super.cancelVideoFrameCallback(id);
  19428. }
  19429. }
  19430. /**
  19431. * A getter/setter for the `Html5` Tech's source object.
  19432. * > Note: Please use {@link Html5#setSource}
  19433. *
  19434. * @param {Tech~SourceObject} [src]
  19435. * The source object you want to set on the `HTML5` techs element.
  19436. *
  19437. * @return {Tech~SourceObject|undefined}
  19438. * - The current source object when a source is not passed in.
  19439. * - undefined when setting
  19440. *
  19441. * @deprecated Since version 5.
  19442. */
  19443. src(src) {
  19444. if (src === undefined) {
  19445. return this.el_.src;
  19446. }
  19447. // Setting src through `src` instead of `setSrc` will be deprecated
  19448. this.setSrc(src);
  19449. }
  19450. /**
  19451. * Add a <source> element to the <video> element.
  19452. *
  19453. * @param {string} srcUrl
  19454. * The URL of the video source.
  19455. *
  19456. * @param {string} [mimeType]
  19457. * The MIME type of the video source. Optional but recommended.
  19458. *
  19459. * @return {boolean}
  19460. * Returns true if the source element was successfully added, false otherwise.
  19461. */
  19462. addSourceElement(srcUrl, mimeType) {
  19463. if (!srcUrl) {
  19464. log.error('Invalid source URL.');
  19465. return false;
  19466. }
  19467. const sourceAttributes = {
  19468. src: srcUrl
  19469. };
  19470. if (mimeType) {
  19471. sourceAttributes.type = mimeType;
  19472. }
  19473. const sourceElement = createEl('source', {}, sourceAttributes);
  19474. this.el_.appendChild(sourceElement);
  19475. return true;
  19476. }
  19477. /**
  19478. * Remove a <source> element from the <video> element by its URL.
  19479. *
  19480. * @param {string} srcUrl
  19481. * The URL of the source to remove.
  19482. *
  19483. * @return {boolean}
  19484. * Returns true if the source element was successfully removed, false otherwise.
  19485. */
  19486. removeSourceElement(srcUrl) {
  19487. if (!srcUrl) {
  19488. log.error('Source URL is required to remove the source element.');
  19489. return false;
  19490. }
  19491. const sourceElements = this.el_.querySelectorAll('source');
  19492. for (const sourceElement of sourceElements) {
  19493. if (sourceElement.src === srcUrl) {
  19494. this.el_.removeChild(sourceElement);
  19495. return true;
  19496. }
  19497. }
  19498. log.warn(`No matching source element found with src: ${srcUrl}`);
  19499. return false;
  19500. }
  19501. /**
  19502. * Reset the tech by removing all sources and then calling
  19503. * {@link Html5.resetMediaElement}.
  19504. */
  19505. reset() {
  19506. Html5.resetMediaElement(this.el_);
  19507. }
  19508. /**
  19509. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  19510. * the HTML5 media element.
  19511. *
  19512. * @return {Tech~SourceObject}
  19513. * The current source object from the HTML5 tech. With a fallback to the
  19514. * elements source.
  19515. */
  19516. currentSrc() {
  19517. if (this.currentSource_) {
  19518. return this.currentSource_.src;
  19519. }
  19520. return this.el_.currentSrc;
  19521. }
  19522. /**
  19523. * Set controls attribute for the HTML5 media Element.
  19524. *
  19525. * @param {string} val
  19526. * Value to set the controls attribute to
  19527. */
  19528. setControls(val) {
  19529. this.el_.controls = !!val;
  19530. }
  19531. /**
  19532. * Create and returns a remote {@link TextTrack} object.
  19533. *
  19534. * @param {string} kind
  19535. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  19536. *
  19537. * @param {string} [label]
  19538. * Label to identify the text track
  19539. *
  19540. * @param {string} [language]
  19541. * Two letter language abbreviation
  19542. *
  19543. * @return {TextTrack}
  19544. * The TextTrack that gets created.
  19545. */
  19546. addTextTrack(kind, label, language) {
  19547. if (!this.featuresNativeTextTracks) {
  19548. return super.addTextTrack(kind, label, language);
  19549. }
  19550. return this.el_.addTextTrack(kind, label, language);
  19551. }
  19552. /**
  19553. * Creates either native TextTrack or an emulated TextTrack depending
  19554. * on the value of `featuresNativeTextTracks`
  19555. *
  19556. * @param {Object} options
  19557. * The object should contain the options to initialize the TextTrack with.
  19558. *
  19559. * @param {string} [options.kind]
  19560. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  19561. *
  19562. * @param {string} [options.label]
  19563. * Label to identify the text track
  19564. *
  19565. * @param {string} [options.language]
  19566. * Two letter language abbreviation.
  19567. *
  19568. * @param {boolean} [options.default]
  19569. * Default this track to on.
  19570. *
  19571. * @param {string} [options.id]
  19572. * The internal id to assign this track.
  19573. *
  19574. * @param {string} [options.src]
  19575. * A source url for the track.
  19576. *
  19577. * @return {HTMLTrackElement}
  19578. * The track element that gets created.
  19579. */
  19580. createRemoteTextTrack(options) {
  19581. if (!this.featuresNativeTextTracks) {
  19582. return super.createRemoteTextTrack(options);
  19583. }
  19584. const htmlTrackElement = document.createElement('track');
  19585. if (options.kind) {
  19586. htmlTrackElement.kind = options.kind;
  19587. }
  19588. if (options.label) {
  19589. htmlTrackElement.label = options.label;
  19590. }
  19591. if (options.language || options.srclang) {
  19592. htmlTrackElement.srclang = options.language || options.srclang;
  19593. }
  19594. if (options.default) {
  19595. htmlTrackElement.default = options.default;
  19596. }
  19597. if (options.id) {
  19598. htmlTrackElement.id = options.id;
  19599. }
  19600. if (options.src) {
  19601. htmlTrackElement.src = options.src;
  19602. }
  19603. return htmlTrackElement;
  19604. }
  19605. /**
  19606. * Creates a remote text track object and returns an html track element.
  19607. *
  19608. * @param {Object} options The object should contain values for
  19609. * kind, language, label, and src (location of the WebVTT file)
  19610. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  19611. * will not be removed from the TextTrackList and HtmlTrackElementList
  19612. * after a source change
  19613. * @return {HTMLTrackElement} An Html Track Element.
  19614. * This can be an emulated {@link HTMLTrackElement} or a native one.
  19615. *
  19616. */
  19617. addRemoteTextTrack(options, manualCleanup) {
  19618. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  19619. if (this.featuresNativeTextTracks) {
  19620. this.el().appendChild(htmlTrackElement);
  19621. }
  19622. return htmlTrackElement;
  19623. }
  19624. /**
  19625. * Remove remote `TextTrack` from `TextTrackList` object
  19626. *
  19627. * @param {TextTrack} track
  19628. * `TextTrack` object to remove
  19629. */
  19630. removeRemoteTextTrack(track) {
  19631. super.removeRemoteTextTrack(track);
  19632. if (this.featuresNativeTextTracks) {
  19633. const tracks = this.$$('track');
  19634. let i = tracks.length;
  19635. while (i--) {
  19636. if (track === tracks[i] || track === tracks[i].track) {
  19637. this.el().removeChild(tracks[i]);
  19638. }
  19639. }
  19640. }
  19641. }
  19642. /**
  19643. * Gets available media playback quality metrics as specified by the W3C's Media
  19644. * Playback Quality API.
  19645. *
  19646. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  19647. *
  19648. * @return {Object}
  19649. * An object with supported media playback quality metrics
  19650. */
  19651. getVideoPlaybackQuality() {
  19652. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  19653. return this.el().getVideoPlaybackQuality();
  19654. }
  19655. const videoPlaybackQuality = {};
  19656. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  19657. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  19658. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  19659. }
  19660. if (window.performance) {
  19661. videoPlaybackQuality.creationTime = window.performance.now();
  19662. }
  19663. return videoPlaybackQuality;
  19664. }
  19665. }
  19666. /* HTML5 Support Testing ---------------------------------------------------- */
  19667. /**
  19668. * Element for testing browser HTML5 media capabilities
  19669. *
  19670. * @type {Element}
  19671. * @constant
  19672. * @private
  19673. */
  19674. defineLazyProperty(Html5, 'TEST_VID', function () {
  19675. if (!isReal()) {
  19676. return;
  19677. }
  19678. const video = document.createElement('video');
  19679. const track = document.createElement('track');
  19680. track.kind = 'captions';
  19681. track.srclang = 'en';
  19682. track.label = 'English';
  19683. video.appendChild(track);
  19684. return video;
  19685. });
  19686. /**
  19687. * Check if HTML5 media is supported by this browser/device.
  19688. *
  19689. * @return {boolean}
  19690. * - True if HTML5 media is supported.
  19691. * - False if HTML5 media is not supported.
  19692. */
  19693. Html5.isSupported = function () {
  19694. // IE with no Media Player is a LIAR! (#984)
  19695. try {
  19696. Html5.TEST_VID.volume = 0.5;
  19697. } catch (e) {
  19698. return false;
  19699. }
  19700. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  19701. };
  19702. /**
  19703. * Check if the tech can support the given type
  19704. *
  19705. * @param {string} type
  19706. * The mimetype to check
  19707. * @return {string} 'probably', 'maybe', or '' (empty string)
  19708. */
  19709. Html5.canPlayType = function (type) {
  19710. return Html5.TEST_VID.canPlayType(type);
  19711. };
  19712. /**
  19713. * Check if the tech can support the given source
  19714. *
  19715. * @param {Object} srcObj
  19716. * The source object
  19717. * @param {Object} options
  19718. * The options passed to the tech
  19719. * @return {string} 'probably', 'maybe', or '' (empty string)
  19720. */
  19721. Html5.canPlaySource = function (srcObj, options) {
  19722. return Html5.canPlayType(srcObj.type);
  19723. };
  19724. /**
  19725. * Check if the volume can be changed in this browser/device.
  19726. * Volume cannot be changed in a lot of mobile devices.
  19727. * Specifically, it can't be changed from 1 on iOS.
  19728. *
  19729. * @return {boolean}
  19730. * - True if volume can be controlled
  19731. * - False otherwise
  19732. */
  19733. Html5.canControlVolume = function () {
  19734. // IE will error if Windows Media Player not installed #3315
  19735. try {
  19736. const volume = Html5.TEST_VID.volume;
  19737. Html5.TEST_VID.volume = volume / 2 + 0.1;
  19738. const canControl = volume !== Html5.TEST_VID.volume;
  19739. // With the introduction of iOS 15, there are cases where the volume is read as
  19740. // changed but reverts back to its original state at the start of the next tick.
  19741. // To determine whether volume can be controlled on iOS,
  19742. // a timeout is set and the volume is checked asynchronously.
  19743. // Since `features` doesn't currently work asynchronously, the value is manually set.
  19744. if (canControl && IS_IOS) {
  19745. window.setTimeout(() => {
  19746. if (Html5 && Html5.prototype) {
  19747. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  19748. }
  19749. });
  19750. // default iOS to false, which will be updated in the timeout above.
  19751. return false;
  19752. }
  19753. return canControl;
  19754. } catch (e) {
  19755. return false;
  19756. }
  19757. };
  19758. /**
  19759. * Check if the volume can be muted in this browser/device.
  19760. * Some devices, e.g. iOS, don't allow changing volume
  19761. * but permits muting/unmuting.
  19762. *
  19763. * @return {boolean}
  19764. * - True if volume can be muted
  19765. * - False otherwise
  19766. */
  19767. Html5.canMuteVolume = function () {
  19768. try {
  19769. const muted = Html5.TEST_VID.muted;
  19770. // in some versions of iOS muted property doesn't always
  19771. // work, so we want to set both property and attribute
  19772. Html5.TEST_VID.muted = !muted;
  19773. if (Html5.TEST_VID.muted) {
  19774. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  19775. } else {
  19776. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  19777. }
  19778. return muted !== Html5.TEST_VID.muted;
  19779. } catch (e) {
  19780. return false;
  19781. }
  19782. };
  19783. /**
  19784. * Check if the playback rate can be changed in this browser/device.
  19785. *
  19786. * @return {boolean}
  19787. * - True if playback rate can be controlled
  19788. * - False otherwise
  19789. */
  19790. Html5.canControlPlaybackRate = function () {
  19791. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  19792. // https://github.com/videojs/video.js/issues/3180
  19793. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  19794. return false;
  19795. }
  19796. // IE will error if Windows Media Player not installed #3315
  19797. try {
  19798. const playbackRate = Html5.TEST_VID.playbackRate;
  19799. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  19800. return playbackRate !== Html5.TEST_VID.playbackRate;
  19801. } catch (e) {
  19802. return false;
  19803. }
  19804. };
  19805. /**
  19806. * Check if we can override a video/audio elements attributes, with
  19807. * Object.defineProperty.
  19808. *
  19809. * @return {boolean}
  19810. * - True if builtin attributes can be overridden
  19811. * - False otherwise
  19812. */
  19813. Html5.canOverrideAttributes = function () {
  19814. // if we cannot overwrite the src/innerHTML property, there is no support
  19815. // iOS 7 safari for instance cannot do this.
  19816. try {
  19817. const noop = () => {};
  19818. Object.defineProperty(document.createElement('video'), 'src', {
  19819. get: noop,
  19820. set: noop
  19821. });
  19822. Object.defineProperty(document.createElement('audio'), 'src', {
  19823. get: noop,
  19824. set: noop
  19825. });
  19826. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  19827. get: noop,
  19828. set: noop
  19829. });
  19830. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  19831. get: noop,
  19832. set: noop
  19833. });
  19834. } catch (e) {
  19835. return false;
  19836. }
  19837. return true;
  19838. };
  19839. /**
  19840. * Check to see if native `TextTrack`s are supported by this browser/device.
  19841. *
  19842. * @return {boolean}
  19843. * - True if native `TextTrack`s are supported.
  19844. * - False otherwise
  19845. */
  19846. Html5.supportsNativeTextTracks = function () {
  19847. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  19848. };
  19849. /**
  19850. * Check to see if native `VideoTrack`s are supported by this browser/device
  19851. *
  19852. * @return {boolean}
  19853. * - True if native `VideoTrack`s are supported.
  19854. * - False otherwise
  19855. */
  19856. Html5.supportsNativeVideoTracks = function () {
  19857. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  19858. };
  19859. /**
  19860. * Check to see if native `AudioTrack`s are supported by this browser/device
  19861. *
  19862. * @return {boolean}
  19863. * - True if native `AudioTrack`s are supported.
  19864. * - False otherwise
  19865. */
  19866. Html5.supportsNativeAudioTracks = function () {
  19867. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  19868. };
  19869. /**
  19870. * An array of events available on the Html5 tech.
  19871. *
  19872. * @private
  19873. * @type {Array}
  19874. */
  19875. 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'];
  19876. /**
  19877. * Boolean indicating whether the `Tech` supports volume control.
  19878. *
  19879. * @type {boolean}
  19880. * @default {@link Html5.canControlVolume}
  19881. */
  19882. /**
  19883. * Boolean indicating whether the `Tech` supports muting volume.
  19884. *
  19885. * @type {boolean}
  19886. * @default {@link Html5.canMuteVolume}
  19887. */
  19888. /**
  19889. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  19890. * plays. Examples:
  19891. * - Set player to play 2x (twice) as fast
  19892. * - Set player to play 0.5x (half) as fast
  19893. *
  19894. * @type {boolean}
  19895. * @default {@link Html5.canControlPlaybackRate}
  19896. */
  19897. /**
  19898. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  19899. *
  19900. * @type {boolean}
  19901. * @default
  19902. */
  19903. /**
  19904. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  19905. *
  19906. * @type {boolean}
  19907. * @default {@link Html5.supportsNativeTextTracks}
  19908. */
  19909. /**
  19910. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  19911. *
  19912. * @type {boolean}
  19913. * @default {@link Html5.supportsNativeVideoTracks}
  19914. */
  19915. /**
  19916. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  19917. *
  19918. * @type {boolean}
  19919. * @default {@link Html5.supportsNativeAudioTracks}
  19920. */
  19921. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  19922. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  19923. });
  19924. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  19925. /**
  19926. * Boolean indicating whether the `HTML5` tech currently supports the media element
  19927. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  19928. * false there. Everywhere else this should be true.
  19929. *
  19930. * @type {boolean}
  19931. * @default
  19932. */
  19933. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  19934. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  19935. // Is this true?
  19936. /**
  19937. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  19938. * when going into fullscreen.
  19939. *
  19940. * @type {boolean}
  19941. * @default
  19942. */
  19943. Html5.prototype.featuresFullscreenResize = true;
  19944. /**
  19945. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  19946. * If this is false, manual `progress` events will be triggered instead.
  19947. *
  19948. * @type {boolean}
  19949. * @default
  19950. */
  19951. Html5.prototype.featuresProgressEvents = true;
  19952. /**
  19953. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  19954. * If this is false, manual `timeupdate` events will be triggered instead.
  19955. *
  19956. * @default
  19957. */
  19958. Html5.prototype.featuresTimeupdateEvents = true;
  19959. /**
  19960. * Whether the HTML5 el supports `requestVideoFrameCallback`
  19961. *
  19962. * @type {boolean}
  19963. */
  19964. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  19965. Html5.disposeMediaElement = function (el) {
  19966. if (!el) {
  19967. return;
  19968. }
  19969. if (el.parentNode) {
  19970. el.parentNode.removeChild(el);
  19971. }
  19972. // remove any child track or source nodes to prevent their loading
  19973. while (el.hasChildNodes()) {
  19974. el.removeChild(el.firstChild);
  19975. }
  19976. // remove any src reference. not setting `src=''` because that causes a warning
  19977. // in firefox
  19978. el.removeAttribute('src');
  19979. // force the media element to update its loading state by calling load()
  19980. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  19981. if (typeof el.load === 'function') {
  19982. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  19983. (function () {
  19984. try {
  19985. el.load();
  19986. } catch (e) {
  19987. // not supported
  19988. }
  19989. })();
  19990. }
  19991. };
  19992. Html5.resetMediaElement = function (el) {
  19993. if (!el) {
  19994. return;
  19995. }
  19996. const sources = el.querySelectorAll('source');
  19997. let i = sources.length;
  19998. while (i--) {
  19999. el.removeChild(sources[i]);
  20000. }
  20001. // remove any src reference.
  20002. // not setting `src=''` because that throws an error
  20003. el.removeAttribute('src');
  20004. if (typeof el.load === 'function') {
  20005. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  20006. (function () {
  20007. try {
  20008. el.load();
  20009. } catch (e) {
  20010. // satisfy linter
  20011. }
  20012. })();
  20013. }
  20014. };
  20015. /* Native HTML5 element property wrapping ----------------------------------- */
  20016. // Wrap native boolean attributes with getters that check both property and attribute
  20017. // The list is as followed:
  20018. // muted, defaultMuted, autoplay, controls, loop, playsinline
  20019. [
  20020. /**
  20021. * Get the value of `muted` from the media element. `muted` indicates
  20022. * that the volume for the media should be set to silent. This does not actually change
  20023. * the `volume` attribute.
  20024. *
  20025. * @method Html5#muted
  20026. * @return {boolean}
  20027. * - True if the value of `volume` should be ignored and the audio set to silent.
  20028. * - False if the value of `volume` should be used.
  20029. *
  20030. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  20031. */
  20032. 'muted',
  20033. /**
  20034. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  20035. * whether the media should start muted or not. Only changes the default state of the
  20036. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  20037. * current state.
  20038. *
  20039. * @method Html5#defaultMuted
  20040. * @return {boolean}
  20041. * - The value of `defaultMuted` from the media element.
  20042. * - True indicates that the media should start muted.
  20043. * - False indicates that the media should not start muted
  20044. *
  20045. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  20046. */
  20047. 'defaultMuted',
  20048. /**
  20049. * Get the value of `autoplay` from the media element. `autoplay` indicates
  20050. * that the media should start to play as soon as the page is ready.
  20051. *
  20052. * @method Html5#autoplay
  20053. * @return {boolean}
  20054. * - The value of `autoplay` from the media element.
  20055. * - True indicates that the media should start as soon as the page loads.
  20056. * - False indicates that the media should not start as soon as the page loads.
  20057. *
  20058. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  20059. */
  20060. 'autoplay',
  20061. /**
  20062. * Get the value of `controls` from the media element. `controls` indicates
  20063. * whether the native media controls should be shown or hidden.
  20064. *
  20065. * @method Html5#controls
  20066. * @return {boolean}
  20067. * - The value of `controls` from the media element.
  20068. * - True indicates that native controls should be showing.
  20069. * - False indicates that native controls should be hidden.
  20070. *
  20071. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  20072. */
  20073. 'controls',
  20074. /**
  20075. * Get the value of `loop` from the media element. `loop` indicates
  20076. * that the media should return to the start of the media and continue playing once
  20077. * it reaches the end.
  20078. *
  20079. * @method Html5#loop
  20080. * @return {boolean}
  20081. * - The value of `loop` from the media element.
  20082. * - True indicates that playback should seek back to start once
  20083. * the end of a media is reached.
  20084. * - False indicates that playback should not loop back to the start when the
  20085. * end of the media is reached.
  20086. *
  20087. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  20088. */
  20089. 'loop',
  20090. /**
  20091. * Get the value of `playsinline` from the media element. `playsinline` indicates
  20092. * to the browser that non-fullscreen playback is preferred when fullscreen
  20093. * playback is the native default, such as in iOS Safari.
  20094. *
  20095. * @method Html5#playsinline
  20096. * @return {boolean}
  20097. * - The value of `playsinline` from the media element.
  20098. * - True indicates that the media should play inline.
  20099. * - False indicates that the media should not play inline.
  20100. *
  20101. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  20102. */
  20103. 'playsinline'].forEach(function (prop) {
  20104. Html5.prototype[prop] = function () {
  20105. return this.el_[prop] || this.el_.hasAttribute(prop);
  20106. };
  20107. });
  20108. // Wrap native boolean attributes with setters that set both property and attribute
  20109. // The list is as followed:
  20110. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  20111. // setControls is special-cased above
  20112. [
  20113. /**
  20114. * Set the value of `muted` on the media element. `muted` indicates that the current
  20115. * audio level should be silent.
  20116. *
  20117. * @method Html5#setMuted
  20118. * @param {boolean} muted
  20119. * - True if the audio should be set to silent
  20120. * - False otherwise
  20121. *
  20122. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  20123. */
  20124. 'muted',
  20125. /**
  20126. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  20127. * audio level should be silent, but will only effect the muted level on initial playback..
  20128. *
  20129. * @method Html5.prototype.setDefaultMuted
  20130. * @param {boolean} defaultMuted
  20131. * - True if the audio should be set to silent
  20132. * - False otherwise
  20133. *
  20134. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  20135. */
  20136. 'defaultMuted',
  20137. /**
  20138. * Set the value of `autoplay` on the media element. `autoplay` indicates
  20139. * that the media should start to play as soon as the page is ready.
  20140. *
  20141. * @method Html5#setAutoplay
  20142. * @param {boolean} autoplay
  20143. * - True indicates that the media should start as soon as the page loads.
  20144. * - False indicates that the media should not start as soon as the page loads.
  20145. *
  20146. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  20147. */
  20148. 'autoplay',
  20149. /**
  20150. * Set the value of `loop` on the media element. `loop` indicates
  20151. * that the media should return to the start of the media and continue playing once
  20152. * it reaches the end.
  20153. *
  20154. * @method Html5#setLoop
  20155. * @param {boolean} loop
  20156. * - True indicates that playback should seek back to start once
  20157. * the end of a media is reached.
  20158. * - False indicates that playback should not loop back to the start when the
  20159. * end of the media is reached.
  20160. *
  20161. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  20162. */
  20163. 'loop',
  20164. /**
  20165. * Set the value of `playsinline` from the media element. `playsinline` indicates
  20166. * to the browser that non-fullscreen playback is preferred when fullscreen
  20167. * playback is the native default, such as in iOS Safari.
  20168. *
  20169. * @method Html5#setPlaysinline
  20170. * @param {boolean} playsinline
  20171. * - True indicates that the media should play inline.
  20172. * - False indicates that the media should not play inline.
  20173. *
  20174. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  20175. */
  20176. 'playsinline'].forEach(function (prop) {
  20177. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  20178. this.el_[prop] = v;
  20179. if (v) {
  20180. this.el_.setAttribute(prop, prop);
  20181. } else {
  20182. this.el_.removeAttribute(prop);
  20183. }
  20184. };
  20185. });
  20186. // Wrap native properties with a getter
  20187. // The list is as followed
  20188. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  20189. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  20190. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  20191. [
  20192. /**
  20193. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  20194. * is currently paused or not.
  20195. *
  20196. * @method Html5#paused
  20197. * @return {boolean}
  20198. * The value of `paused` from the media element.
  20199. *
  20200. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  20201. */
  20202. 'paused',
  20203. /**
  20204. * Get the value of `currentTime` from the media element. `currentTime` indicates
  20205. * the current second that the media is at in playback.
  20206. *
  20207. * @method Html5#currentTime
  20208. * @return {number}
  20209. * The value of `currentTime` from the media element.
  20210. *
  20211. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  20212. */
  20213. 'currentTime',
  20214. /**
  20215. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  20216. * object that represents the parts of the media that are already downloaded and
  20217. * available for playback.
  20218. *
  20219. * @method Html5#buffered
  20220. * @return {TimeRange}
  20221. * The value of `buffered` from the media element.
  20222. *
  20223. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  20224. */
  20225. 'buffered',
  20226. /**
  20227. * Get the value of `volume` from the media element. `volume` indicates
  20228. * the current playback volume of audio for a media. `volume` will be a value from 0
  20229. * (silent) to 1 (loudest and default).
  20230. *
  20231. * @method Html5#volume
  20232. * @return {number}
  20233. * The value of `volume` from the media element. Value will be between 0-1.
  20234. *
  20235. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20236. */
  20237. 'volume',
  20238. /**
  20239. * Get the value of `poster` from the media element. `poster` indicates
  20240. * that the url of an image file that can/will be shown when no media data is available.
  20241. *
  20242. * @method Html5#poster
  20243. * @return {string}
  20244. * The value of `poster` from the media element. Value will be a url to an
  20245. * image.
  20246. *
  20247. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  20248. */
  20249. 'poster',
  20250. /**
  20251. * Get the value of `preload` from the media element. `preload` indicates
  20252. * what should download before the media is interacted with. It can have the following
  20253. * values:
  20254. * - none: nothing should be downloaded
  20255. * - metadata: poster and the first few frames of the media may be downloaded to get
  20256. * media dimensions and other metadata
  20257. * - auto: allow the media and metadata for the media to be downloaded before
  20258. * interaction
  20259. *
  20260. * @method Html5#preload
  20261. * @return {string}
  20262. * The value of `preload` from the media element. Will be 'none', 'metadata',
  20263. * or 'auto'.
  20264. *
  20265. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20266. */
  20267. 'preload',
  20268. /**
  20269. * Get the value of the `error` from the media element. `error` indicates any
  20270. * MediaError that may have occurred during playback. If error returns null there is no
  20271. * current error.
  20272. *
  20273. * @method Html5#error
  20274. * @return {MediaError|null}
  20275. * The value of `error` from the media element. Will be `MediaError` if there
  20276. * is a current error and null otherwise.
  20277. *
  20278. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  20279. */
  20280. 'error',
  20281. /**
  20282. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  20283. * media is currently seeking to a new position or not.
  20284. *
  20285. * @method Html5#seeking
  20286. * @return {boolean}
  20287. * - The value of `seeking` from the media element.
  20288. * - True indicates that the media is currently seeking to a new position.
  20289. * - False indicates that the media is not seeking to a new position at this time.
  20290. *
  20291. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  20292. */
  20293. 'seeking',
  20294. /**
  20295. * Get the value of `seekable` from the media element. `seekable` returns a
  20296. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  20297. *
  20298. * @method Html5#seekable
  20299. * @return {TimeRange}
  20300. * The value of `seekable` from the media element. A `TimeRange` object
  20301. * indicating the current ranges of time that can be seeked to.
  20302. *
  20303. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  20304. */
  20305. 'seekable',
  20306. /**
  20307. * Get the value of `ended` from the media element. `ended` indicates whether
  20308. * the media has reached the end or not.
  20309. *
  20310. * @method Html5#ended
  20311. * @return {boolean}
  20312. * - The value of `ended` from the media element.
  20313. * - True indicates that the media has ended.
  20314. * - False indicates that the media has not ended.
  20315. *
  20316. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  20317. */
  20318. 'ended',
  20319. /**
  20320. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  20321. * the rate at which the media is currently playing back. Examples:
  20322. * - if playbackRate is set to 2, media will play twice as fast.
  20323. * - if playbackRate is set to 0.5, media will play half as fast.
  20324. *
  20325. * @method Html5#playbackRate
  20326. * @return {number}
  20327. * The value of `playbackRate` from the media element. A number indicating
  20328. * the current playback speed of the media, where 1 is normal speed.
  20329. *
  20330. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20331. */
  20332. 'playbackRate',
  20333. /**
  20334. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  20335. * the rate at which the media is currently playing back. This value will not indicate the current
  20336. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  20337. *
  20338. * Examples:
  20339. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  20340. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  20341. *
  20342. * @method Html5.prototype.defaultPlaybackRate
  20343. * @return {number}
  20344. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20345. * the current playback speed of the media, where 1 is normal speed.
  20346. *
  20347. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20348. */
  20349. 'defaultPlaybackRate',
  20350. /**
  20351. * Get the value of 'disablePictureInPicture' from the video element.
  20352. *
  20353. * @method Html5#disablePictureInPicture
  20354. * @return {boolean} value
  20355. * - The value of `disablePictureInPicture` from the video element.
  20356. * - True indicates that the video can't be played in Picture-In-Picture mode
  20357. * - False indicates that the video can be played in Picture-In-Picture mode
  20358. *
  20359. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20360. */
  20361. 'disablePictureInPicture',
  20362. /**
  20363. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  20364. * object representing points in the media timeline that have been played.
  20365. *
  20366. * @method Html5#played
  20367. * @return {TimeRange}
  20368. * The value of `played` from the media element. A `TimeRange` object indicating
  20369. * the ranges of time that have been played.
  20370. *
  20371. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  20372. */
  20373. 'played',
  20374. /**
  20375. * Get the value of `networkState` from the media element. `networkState` indicates
  20376. * the current network state. It returns an enumeration from the following list:
  20377. * - 0: NETWORK_EMPTY
  20378. * - 1: NETWORK_IDLE
  20379. * - 2: NETWORK_LOADING
  20380. * - 3: NETWORK_NO_SOURCE
  20381. *
  20382. * @method Html5#networkState
  20383. * @return {number}
  20384. * The value of `networkState` from the media element. This will be a number
  20385. * from the list in the description.
  20386. *
  20387. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  20388. */
  20389. 'networkState',
  20390. /**
  20391. * Get the value of `readyState` from the media element. `readyState` indicates
  20392. * the current state of the media element. It returns an enumeration from the
  20393. * following list:
  20394. * - 0: HAVE_NOTHING
  20395. * - 1: HAVE_METADATA
  20396. * - 2: HAVE_CURRENT_DATA
  20397. * - 3: HAVE_FUTURE_DATA
  20398. * - 4: HAVE_ENOUGH_DATA
  20399. *
  20400. * @method Html5#readyState
  20401. * @return {number}
  20402. * The value of `readyState` from the media element. This will be a number
  20403. * from the list in the description.
  20404. *
  20405. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  20406. */
  20407. 'readyState',
  20408. /**
  20409. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  20410. * the current width of the video in css pixels.
  20411. *
  20412. * @method Html5#videoWidth
  20413. * @return {number}
  20414. * The value of `videoWidth` from the video element. This will be a number
  20415. * in css pixels.
  20416. *
  20417. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20418. */
  20419. 'videoWidth',
  20420. /**
  20421. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  20422. * the current height of the video in css pixels.
  20423. *
  20424. * @method Html5#videoHeight
  20425. * @return {number}
  20426. * The value of `videoHeight` from the video element. This will be a number
  20427. * in css pixels.
  20428. *
  20429. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20430. */
  20431. 'videoHeight',
  20432. /**
  20433. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20434. * to the browser that should sent the cookies along with the requests for the
  20435. * different assets/playlists
  20436. *
  20437. * @method Html5#crossOrigin
  20438. * @return {string}
  20439. * - anonymous indicates that the media should not sent cookies.
  20440. * - use-credentials indicates that the media should sent cookies along the requests.
  20441. *
  20442. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20443. */
  20444. 'crossOrigin'].forEach(function (prop) {
  20445. Html5.prototype[prop] = function () {
  20446. return this.el_[prop];
  20447. };
  20448. });
  20449. // Wrap native properties with a setter in this format:
  20450. // set + toTitleCase(name)
  20451. // The list is as follows:
  20452. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  20453. // setDisablePictureInPicture, setCrossOrigin
  20454. [
  20455. /**
  20456. * Set the value of `volume` on the media element. `volume` indicates the current
  20457. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  20458. * so on.
  20459. *
  20460. * @method Html5#setVolume
  20461. * @param {number} percentAsDecimal
  20462. * The volume percent as a decimal. Valid range is from 0-1.
  20463. *
  20464. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20465. */
  20466. 'volume',
  20467. /**
  20468. * Set the value of `src` on the media element. `src` indicates the current
  20469. * {@link Tech~SourceObject} for the media.
  20470. *
  20471. * @method Html5#setSrc
  20472. * @param {Tech~SourceObject} src
  20473. * The source object to set as the current source.
  20474. *
  20475. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  20476. */
  20477. 'src',
  20478. /**
  20479. * Set the value of `poster` on the media element. `poster` is the url to
  20480. * an image file that can/will be shown when no media data is available.
  20481. *
  20482. * @method Html5#setPoster
  20483. * @param {string} poster
  20484. * The url to an image that should be used as the `poster` for the media
  20485. * element.
  20486. *
  20487. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  20488. */
  20489. 'poster',
  20490. /**
  20491. * Set the value of `preload` on the media element. `preload` indicates
  20492. * what should download before the media is interacted with. It can have the following
  20493. * values:
  20494. * - none: nothing should be downloaded
  20495. * - metadata: poster and the first few frames of the media may be downloaded to get
  20496. * media dimensions and other metadata
  20497. * - auto: allow the media and metadata for the media to be downloaded before
  20498. * interaction
  20499. *
  20500. * @method Html5#setPreload
  20501. * @param {string} preload
  20502. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  20503. * or 'auto'.
  20504. *
  20505. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20506. */
  20507. 'preload',
  20508. /**
  20509. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  20510. * the rate at which the media should play back. Examples:
  20511. * - if playbackRate is set to 2, media will play twice as fast.
  20512. * - if playbackRate is set to 0.5, media will play half as fast.
  20513. *
  20514. * @method Html5#setPlaybackRate
  20515. * @return {number}
  20516. * The value of `playbackRate` from the media element. A number indicating
  20517. * the current playback speed of the media, where 1 is normal speed.
  20518. *
  20519. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20520. */
  20521. 'playbackRate',
  20522. /**
  20523. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  20524. * the rate at which the media should play back upon initial startup. Changing this value
  20525. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  20526. *
  20527. * Example Values:
  20528. * - if playbackRate is set to 2, media will play twice as fast.
  20529. * - if playbackRate is set to 0.5, media will play half as fast.
  20530. *
  20531. * @method Html5.prototype.setDefaultPlaybackRate
  20532. * @return {number}
  20533. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20534. * the current playback speed of the media, where 1 is normal speed.
  20535. *
  20536. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  20537. */
  20538. 'defaultPlaybackRate',
  20539. /**
  20540. * Prevents the browser from suggesting a Picture-in-Picture context menu
  20541. * or to request Picture-in-Picture automatically in some cases.
  20542. *
  20543. * @method Html5#setDisablePictureInPicture
  20544. * @param {boolean} value
  20545. * The true value will disable Picture-in-Picture mode.
  20546. *
  20547. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20548. */
  20549. 'disablePictureInPicture',
  20550. /**
  20551. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20552. * to the browser that should sent the cookies along with the requests for the
  20553. * different assets/playlists
  20554. *
  20555. * @method Html5#setCrossOrigin
  20556. * @param {string} crossOrigin
  20557. * - anonymous indicates that the media should not sent cookies.
  20558. * - use-credentials indicates that the media should sent cookies along the requests.
  20559. *
  20560. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20561. */
  20562. 'crossOrigin'].forEach(function (prop) {
  20563. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  20564. this.el_[prop] = v;
  20565. };
  20566. });
  20567. // wrap native functions with a function
  20568. // The list is as follows:
  20569. // pause, load, play
  20570. [
  20571. /**
  20572. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  20573. * media elements `pause` function.
  20574. *
  20575. * @method Html5#pause
  20576. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  20577. */
  20578. 'pause',
  20579. /**
  20580. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  20581. * media element `load` function.
  20582. *
  20583. * @method Html5#load
  20584. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  20585. */
  20586. 'load',
  20587. /**
  20588. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  20589. * media element `play` function.
  20590. *
  20591. * @method Html5#play
  20592. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  20593. */
  20594. 'play'].forEach(function (prop) {
  20595. Html5.prototype[prop] = function () {
  20596. return this.el_[prop]();
  20597. };
  20598. });
  20599. Tech.withSourceHandlers(Html5);
  20600. /**
  20601. * Native source handler for Html5, simply passes the source to the media element.
  20602. *
  20603. * @property {Tech~SourceObject} source
  20604. * The source object
  20605. *
  20606. * @property {Html5} tech
  20607. * The instance of the HTML5 tech.
  20608. */
  20609. Html5.nativeSourceHandler = {};
  20610. /**
  20611. * Check if the media element can play the given mime type.
  20612. *
  20613. * @param {string} type
  20614. * The mimetype to check
  20615. *
  20616. * @return {string}
  20617. * 'probably', 'maybe', or '' (empty string)
  20618. */
  20619. Html5.nativeSourceHandler.canPlayType = function (type) {
  20620. // IE without MediaPlayer throws an error (#519)
  20621. try {
  20622. return Html5.TEST_VID.canPlayType(type);
  20623. } catch (e) {
  20624. return '';
  20625. }
  20626. };
  20627. /**
  20628. * Check if the media element can handle a source natively.
  20629. *
  20630. * @param {Tech~SourceObject} source
  20631. * The source object
  20632. *
  20633. * @param {Object} [options]
  20634. * Options to be passed to the tech.
  20635. *
  20636. * @return {string}
  20637. * 'probably', 'maybe', or '' (empty string).
  20638. */
  20639. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  20640. // If a type was provided we should rely on that
  20641. if (source.type) {
  20642. return Html5.nativeSourceHandler.canPlayType(source.type);
  20643. // If no type, fall back to checking 'video/[EXTENSION]'
  20644. } else if (source.src) {
  20645. const ext = getFileExtension(source.src);
  20646. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  20647. }
  20648. return '';
  20649. };
  20650. /**
  20651. * Pass the source to the native media element.
  20652. *
  20653. * @param {Tech~SourceObject} source
  20654. * The source object
  20655. *
  20656. * @param {Html5} tech
  20657. * The instance of the Html5 tech
  20658. *
  20659. * @param {Object} [options]
  20660. * The options to pass to the source
  20661. */
  20662. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  20663. tech.setSrc(source.src);
  20664. };
  20665. /**
  20666. * A noop for the native dispose function, as cleanup is not needed.
  20667. */
  20668. Html5.nativeSourceHandler.dispose = function () {};
  20669. // Register the native source handler
  20670. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  20671. Tech.registerTech('Html5', Html5);
  20672. /**
  20673. * @file player.js
  20674. */
  20675. /** @import { TimeRange } from './utils/time' */
  20676. /** @import HtmlTrackElement from './tracks/html-track-element' */
  20677. /**
  20678. * @callback PlayerReadyCallback
  20679. * @this {Player}
  20680. * @returns {void}
  20681. */
  20682. // The following tech events are simply re-triggered
  20683. // on the player when they happen
  20684. const TECH_EVENTS_RETRIGGER = [
  20685. /**
  20686. * Fired while the user agent is downloading media data.
  20687. *
  20688. * @event Player#progress
  20689. * @type {Event}
  20690. */
  20691. /**
  20692. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  20693. *
  20694. * @private
  20695. * @method Player#handleTechProgress_
  20696. * @fires Player#progress
  20697. * @listens Tech#progress
  20698. */
  20699. 'progress',
  20700. /**
  20701. * Fires when the loading of an audio/video is aborted.
  20702. *
  20703. * @event Player#abort
  20704. * @type {Event}
  20705. */
  20706. /**
  20707. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  20708. *
  20709. * @private
  20710. * @method Player#handleTechAbort_
  20711. * @fires Player#abort
  20712. * @listens Tech#abort
  20713. */
  20714. 'abort',
  20715. /**
  20716. * Fires when the browser is intentionally not getting media data.
  20717. *
  20718. * @event Player#suspend
  20719. * @type {Event}
  20720. */
  20721. /**
  20722. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  20723. *
  20724. * @private
  20725. * @method Player#handleTechSuspend_
  20726. * @fires Player#suspend
  20727. * @listens Tech#suspend
  20728. */
  20729. 'suspend',
  20730. /**
  20731. * Fires when the current playlist is empty.
  20732. *
  20733. * @event Player#emptied
  20734. * @type {Event}
  20735. */
  20736. /**
  20737. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  20738. *
  20739. * @private
  20740. * @method Player#handleTechEmptied_
  20741. * @fires Player#emptied
  20742. * @listens Tech#emptied
  20743. */
  20744. 'emptied',
  20745. /**
  20746. * Fires when the browser is trying to get media data, but data is not available.
  20747. *
  20748. * @event Player#stalled
  20749. * @type {Event}
  20750. */
  20751. /**
  20752. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  20753. *
  20754. * @private
  20755. * @method Player#handleTechStalled_
  20756. * @fires Player#stalled
  20757. * @listens Tech#stalled
  20758. */
  20759. 'stalled',
  20760. /**
  20761. * Fires when the browser has loaded meta data for the audio/video.
  20762. *
  20763. * @event Player#loadedmetadata
  20764. * @type {Event}
  20765. */
  20766. /**
  20767. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  20768. *
  20769. * @private
  20770. * @method Player#handleTechLoadedmetadata_
  20771. * @fires Player#loadedmetadata
  20772. * @listens Tech#loadedmetadata
  20773. */
  20774. 'loadedmetadata',
  20775. /**
  20776. * Fires when the browser has loaded the current frame of the audio/video.
  20777. *
  20778. * @event Player#loadeddata
  20779. * @type {event}
  20780. */
  20781. /**
  20782. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  20783. *
  20784. * @private
  20785. * @method Player#handleTechLoaddeddata_
  20786. * @fires Player#loadeddata
  20787. * @listens Tech#loadeddata
  20788. */
  20789. 'loadeddata',
  20790. /**
  20791. * Fires when the current playback position has changed.
  20792. *
  20793. * @event Player#timeupdate
  20794. * @type {event}
  20795. */
  20796. /**
  20797. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  20798. *
  20799. * @private
  20800. * @method Player#handleTechTimeUpdate_
  20801. * @fires Player#timeupdate
  20802. * @listens Tech#timeupdate
  20803. */
  20804. 'timeupdate',
  20805. /**
  20806. * Fires when the video's intrinsic dimensions change
  20807. *
  20808. * @event Player#resize
  20809. * @type {event}
  20810. */
  20811. /**
  20812. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  20813. *
  20814. * @private
  20815. * @method Player#handleTechResize_
  20816. * @fires Player#resize
  20817. * @listens Tech#resize
  20818. */
  20819. 'resize',
  20820. /**
  20821. * Fires when the volume has been changed
  20822. *
  20823. * @event Player#volumechange
  20824. * @type {event}
  20825. */
  20826. /**
  20827. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  20828. *
  20829. * @private
  20830. * @method Player#handleTechVolumechange_
  20831. * @fires Player#volumechange
  20832. * @listens Tech#volumechange
  20833. */
  20834. 'volumechange',
  20835. /**
  20836. * Fires when the text track has been changed
  20837. *
  20838. * @event Player#texttrackchange
  20839. * @type {event}
  20840. */
  20841. /**
  20842. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  20843. *
  20844. * @private
  20845. * @method Player#handleTechTexttrackchange_
  20846. * @fires Player#texttrackchange
  20847. * @listens Tech#texttrackchange
  20848. */
  20849. 'texttrackchange'];
  20850. // events to queue when playback rate is zero
  20851. // this is a hash for the sole purpose of mapping non-camel-cased event names
  20852. // to camel-cased function names
  20853. const TECH_EVENTS_QUEUE = {
  20854. canplay: 'CanPlay',
  20855. canplaythrough: 'CanPlayThrough',
  20856. playing: 'Playing',
  20857. seeked: 'Seeked'
  20858. };
  20859. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  20860. const BREAKPOINT_CLASSES = {};
  20861. // grep: vjs-layout-tiny
  20862. // grep: vjs-layout-x-small
  20863. // grep: vjs-layout-small
  20864. // grep: vjs-layout-medium
  20865. // grep: vjs-layout-large
  20866. // grep: vjs-layout-x-large
  20867. // grep: vjs-layout-huge
  20868. BREAKPOINT_ORDER.forEach(k => {
  20869. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  20870. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  20871. });
  20872. const DEFAULT_BREAKPOINTS = {
  20873. tiny: 210,
  20874. xsmall: 320,
  20875. small: 425,
  20876. medium: 768,
  20877. large: 1440,
  20878. xlarge: 2560,
  20879. huge: Infinity
  20880. };
  20881. /**
  20882. * An instance of the `Player` class is created when any of the Video.js setup methods
  20883. * are used to initialize a video.
  20884. *
  20885. * After an instance has been created it can be accessed globally in three ways:
  20886. * 1. By calling `videojs.getPlayer('example_video_1');`
  20887. * 2. By calling `videojs('example_video_1');` (not recommended)
  20888. * 2. By using it directly via `videojs.players.example_video_1;`
  20889. *
  20890. * @extends Component
  20891. * @global
  20892. */
  20893. class Player extends Component {
  20894. /**
  20895. * Create an instance of this class.
  20896. *
  20897. * @param {Element} tag
  20898. * The original video DOM element used for configuring options.
  20899. *
  20900. * @param {Object} [options]
  20901. * Object of option names and values.
  20902. *
  20903. * @param {PlayerReadyCallback} [ready]
  20904. * Ready callback function.
  20905. */
  20906. constructor(tag, options, ready) {
  20907. // Make sure tag ID exists
  20908. // also here.. probably better
  20909. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  20910. // Set Options
  20911. // The options argument overrides options set in the video tag
  20912. // which overrides globally set options.
  20913. // This latter part coincides with the load order
  20914. // (tag must exist before Player)
  20915. options = Object.assign(Player.getTagSettings(tag), options);
  20916. // Delay the initialization of children because we need to set up
  20917. // player properties first, and can't use `this` before `super()`
  20918. options.initChildren = false;
  20919. // Same with creating the element
  20920. options.createEl = false;
  20921. // don't auto mixin the evented mixin
  20922. options.evented = false;
  20923. // we don't want the player to report touch activity on itself
  20924. // see enableTouchActivity in Component
  20925. options.reportTouchActivity = false;
  20926. // If language is not set, get the closest lang attribute
  20927. if (!options.language) {
  20928. const closest = tag.closest('[lang]');
  20929. if (closest) {
  20930. options.language = closest.getAttribute('lang');
  20931. }
  20932. }
  20933. // Run base component initializing with new options
  20934. super(null, options, ready);
  20935. // Create bound methods for document listeners.
  20936. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  20937. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  20938. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  20939. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  20940. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  20941. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  20942. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  20943. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  20944. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  20945. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  20946. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  20947. this.boundUpdatePlayerHeightOnAudioOnlyMode_ = e => this.updatePlayerHeightOnAudioOnlyMode_(e);
  20948. // default isFullscreen_ to false
  20949. this.isFullscreen_ = false;
  20950. // create logger
  20951. this.log = createLogger(this.id_);
  20952. // Hold our own reference to fullscreen api so it can be mocked in tests
  20953. this.fsApi_ = FullscreenApi;
  20954. // Tracks when a tech changes the poster
  20955. this.isPosterFromTech_ = false;
  20956. // Holds callback info that gets queued when playback rate is zero
  20957. // and a seek is happening
  20958. this.queuedCallbacks_ = [];
  20959. // Turn off API access because we're loading a new tech that might load asynchronously
  20960. this.isReady_ = false;
  20961. // Init state hasStarted_
  20962. this.hasStarted_ = false;
  20963. // Init state userActive_
  20964. this.userActive_ = false;
  20965. // Init debugEnabled_
  20966. this.debugEnabled_ = false;
  20967. // Init state audioOnlyMode_
  20968. this.audioOnlyMode_ = false;
  20969. // Init state audioPosterMode_
  20970. this.audioPosterMode_ = false;
  20971. // Init state audioOnlyCache_
  20972. this.audioOnlyCache_ = {
  20973. controlBarHeight: null,
  20974. playerHeight: null,
  20975. hiddenChildren: []
  20976. };
  20977. // if the global option object was accidentally blown away by
  20978. // someone, bail early with an informative error
  20979. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  20980. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  20981. }
  20982. // Store the original tag used to set options
  20983. this.tag = tag;
  20984. // Store the tag attributes used to restore html5 element
  20985. this.tagAttributes = tag && getAttributes(tag);
  20986. // Update current language
  20987. this.language(this.options_.language);
  20988. // Update Supported Languages
  20989. if (options.languages) {
  20990. // Normalise player option languages to lowercase
  20991. const languagesToLower = {};
  20992. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  20993. languagesToLower[name.toLowerCase()] = options.languages[name];
  20994. });
  20995. this.languages_ = languagesToLower;
  20996. } else {
  20997. this.languages_ = Player.prototype.options_.languages;
  20998. }
  20999. this.resetCache_();
  21000. // Set poster
  21001. /** @type string */
  21002. this.poster_ = options.poster || '';
  21003. // Set controls
  21004. /** @type {boolean} */
  21005. this.controls_ = !!options.controls;
  21006. // Original tag settings stored in options
  21007. // now remove immediately so native controls don't flash.
  21008. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  21009. tag.controls = false;
  21010. tag.removeAttribute('controls');
  21011. this.changingSrc_ = false;
  21012. this.playCallbacks_ = [];
  21013. this.playTerminatedQueue_ = [];
  21014. // the attribute overrides the option
  21015. if (tag.hasAttribute('autoplay')) {
  21016. this.autoplay(true);
  21017. } else {
  21018. // otherwise use the setter to validate and
  21019. // set the correct value.
  21020. this.autoplay(this.options_.autoplay);
  21021. }
  21022. // check plugins
  21023. if (options.plugins) {
  21024. Object.keys(options.plugins).forEach(name => {
  21025. if (typeof this[name] !== 'function') {
  21026. throw new Error(`plugin "${name}" does not exist`);
  21027. }
  21028. });
  21029. }
  21030. /*
  21031. * Store the internal state of scrubbing
  21032. *
  21033. * @private
  21034. * @return {Boolean} True if the user is scrubbing
  21035. */
  21036. this.scrubbing_ = false;
  21037. this.el_ = this.createEl();
  21038. // Make this an evented object and use `el_` as its event bus.
  21039. evented(this, {
  21040. eventBusKey: 'el_'
  21041. });
  21042. // listen to document and player fullscreenchange handlers so we receive those events
  21043. // before a user can receive them so we can update isFullscreen appropriately.
  21044. // make sure that we listen to fullscreenchange events before everything else to make sure that
  21045. // our isFullscreen method is updated properly for internal components as well as external.
  21046. if (this.fsApi_.requestFullscreen) {
  21047. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  21048. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  21049. }
  21050. if (this.fluid_) {
  21051. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21052. }
  21053. // We also want to pass the original player options to each component and plugin
  21054. // as well so they don't need to reach back into the player for options later.
  21055. // We also need to do another copy of this.options_ so we don't end up with
  21056. // an infinite loop.
  21057. const playerOptionsCopy = merge(this.options_);
  21058. // Load plugins
  21059. if (options.plugins) {
  21060. Object.keys(options.plugins).forEach(name => {
  21061. this[name](options.plugins[name]);
  21062. });
  21063. }
  21064. // Enable debug mode to fire debugon event for all plugins.
  21065. if (options.debug) {
  21066. this.debug(true);
  21067. }
  21068. this.options_.playerOptions = playerOptionsCopy;
  21069. this.middleware_ = [];
  21070. this.playbackRates(options.playbackRates);
  21071. if (options.experimentalSvgIcons) {
  21072. // Add SVG Sprite to the DOM
  21073. const parser = new window.DOMParser();
  21074. const parsedSVG = parser.parseFromString(icons, 'image/svg+xml');
  21075. const errorNode = parsedSVG.querySelector('parsererror');
  21076. if (errorNode) {
  21077. log.warn('Failed to load SVG Icons. Falling back to Font Icons.');
  21078. this.options_.experimentalSvgIcons = null;
  21079. } else {
  21080. const sprite = parsedSVG.documentElement;
  21081. sprite.style.display = 'none';
  21082. this.el_.appendChild(sprite);
  21083. this.addClass('vjs-svg-icons-enabled');
  21084. }
  21085. }
  21086. this.initChildren();
  21087. // Set isAudio based on whether or not an audio tag was used
  21088. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  21089. // Update controls className. Can't do this when the controls are initially
  21090. // set because the element doesn't exist yet.
  21091. if (this.controls()) {
  21092. this.addClass('vjs-controls-enabled');
  21093. } else {
  21094. this.addClass('vjs-controls-disabled');
  21095. }
  21096. // Set ARIA label and region role depending on player type
  21097. this.el_.setAttribute('role', 'region');
  21098. if (this.isAudio()) {
  21099. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  21100. } else {
  21101. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  21102. }
  21103. if (this.isAudio()) {
  21104. this.addClass('vjs-audio');
  21105. }
  21106. // Check if spatial navigation is enabled in the options.
  21107. // If enabled, instantiate the SpatialNavigation class.
  21108. if (options.spatialNavigation && options.spatialNavigation.enabled) {
  21109. this.spatialNavigation = new SpatialNavigation(this);
  21110. this.addClass('vjs-spatial-navigation-enabled');
  21111. }
  21112. // TODO: Make this smarter. Toggle user state between touching/mousing
  21113. // using events, since devices can have both touch and mouse events.
  21114. // TODO: Make this check be performed again when the window switches between monitors
  21115. // (See https://github.com/videojs/video.js/issues/5683)
  21116. if (TOUCH_ENABLED) {
  21117. this.addClass('vjs-touch-enabled');
  21118. }
  21119. // iOS Safari has broken hover handling
  21120. if (!IS_IOS) {
  21121. this.addClass('vjs-workinghover');
  21122. }
  21123. // Make player easily findable by ID
  21124. Player.players[this.id_] = this;
  21125. // Add a major version class to aid css in plugins
  21126. const majorVersion = version.split('.')[0];
  21127. this.addClass(`vjs-v${majorVersion}`);
  21128. // When the player is first initialized, trigger activity so components
  21129. // like the control bar show themselves if needed
  21130. this.userActive(true);
  21131. this.reportUserActivity();
  21132. this.one('play', e => this.listenForUserActivity_(e));
  21133. this.on('keydown', e => this.handleKeyDown(e));
  21134. this.on('languagechange', e => this.handleLanguagechange(e));
  21135. this.breakpoints(this.options_.breakpoints);
  21136. this.responsive(this.options_.responsive);
  21137. // Calling both the audio mode methods after the player is fully
  21138. // setup to be able to listen to the events triggered by them
  21139. this.on('ready', () => {
  21140. // Calling the audioPosterMode method first so that
  21141. // the audioOnlyMode can take precedence when both options are set to true
  21142. this.audioPosterMode(this.options_.audioPosterMode);
  21143. this.audioOnlyMode(this.options_.audioOnlyMode);
  21144. });
  21145. }
  21146. /**
  21147. * Destroys the video player and does any necessary cleanup.
  21148. *
  21149. * This is especially helpful if you are dynamically adding and removing videos
  21150. * to/from the DOM.
  21151. *
  21152. * @fires Player#dispose
  21153. */
  21154. dispose() {
  21155. /**
  21156. * Called when the player is being disposed of.
  21157. *
  21158. * @event Player#dispose
  21159. * @type {Event}
  21160. */
  21161. this.trigger('dispose');
  21162. // prevent dispose from being called twice
  21163. this.off('dispose');
  21164. // Make sure all player-specific document listeners are unbound. This is
  21165. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  21166. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  21167. if (this.styleEl_ && this.styleEl_.parentNode) {
  21168. this.styleEl_.parentNode.removeChild(this.styleEl_);
  21169. this.styleEl_ = null;
  21170. }
  21171. // Kill reference to this player
  21172. Player.players[this.id_] = null;
  21173. if (this.tag && this.tag.player) {
  21174. this.tag.player = null;
  21175. }
  21176. if (this.el_ && this.el_.player) {
  21177. this.el_.player = null;
  21178. }
  21179. if (this.tech_) {
  21180. this.tech_.dispose();
  21181. this.isPosterFromTech_ = false;
  21182. this.poster_ = '';
  21183. }
  21184. if (this.playerElIngest_) {
  21185. this.playerElIngest_ = null;
  21186. }
  21187. if (this.tag) {
  21188. this.tag = null;
  21189. }
  21190. clearCacheForPlayer(this);
  21191. // remove all event handlers for track lists
  21192. // all tracks and track listeners are removed on
  21193. // tech dispose
  21194. ALL.names.forEach(name => {
  21195. const props = ALL[name];
  21196. const list = this[props.getterName]();
  21197. // if it is not a native list
  21198. // we have to manually remove event listeners
  21199. if (list && list.off) {
  21200. list.off();
  21201. }
  21202. });
  21203. // the actual .el_ is removed here, or replaced if
  21204. super.dispose({
  21205. restoreEl: this.options_.restoreEl
  21206. });
  21207. }
  21208. /**
  21209. * Create the `Player`'s DOM element.
  21210. *
  21211. * @return {Element}
  21212. * The DOM element that gets created.
  21213. */
  21214. createEl() {
  21215. let tag = this.tag;
  21216. let el;
  21217. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  21218. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  21219. if (playerElIngest) {
  21220. el = this.el_ = tag.parentNode;
  21221. } else if (!divEmbed) {
  21222. el = this.el_ = super.createEl('div');
  21223. }
  21224. // Copy over all the attributes from the tag, including ID and class
  21225. // ID will now reference player box, not the video tag
  21226. const attrs = getAttributes(tag);
  21227. if (divEmbed) {
  21228. el = this.el_ = tag;
  21229. tag = this.tag = document.createElement('video');
  21230. while (el.children.length) {
  21231. tag.appendChild(el.firstChild);
  21232. }
  21233. if (!hasClass(el, 'video-js')) {
  21234. addClass(el, 'video-js');
  21235. }
  21236. el.appendChild(tag);
  21237. playerElIngest = this.playerElIngest_ = el;
  21238. // move properties over from our custom `video-js` element
  21239. // to our new `video` element. This will move things like
  21240. // `src` or `controls` that were set via js before the player
  21241. // was initialized.
  21242. Object.keys(el).forEach(k => {
  21243. try {
  21244. tag[k] = el[k];
  21245. } catch (e) {
  21246. // we got a a property like outerHTML which we can't actually copy, ignore it
  21247. }
  21248. });
  21249. }
  21250. // set tabindex to -1 to remove the video element from the focus order
  21251. tag.setAttribute('tabindex', '-1');
  21252. attrs.tabindex = '-1';
  21253. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  21254. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  21255. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  21256. // doesn't change behavior of Chrome if JAWS is not being used
  21257. if (IS_CHROME && IS_WINDOWS) {
  21258. tag.setAttribute('role', 'application');
  21259. attrs.role = 'application';
  21260. }
  21261. // Remove width/height attrs from tag so CSS can make it 100% width/height
  21262. tag.removeAttribute('width');
  21263. tag.removeAttribute('height');
  21264. if ('width' in attrs) {
  21265. delete attrs.width;
  21266. }
  21267. if ('height' in attrs) {
  21268. delete attrs.height;
  21269. }
  21270. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  21271. // don't copy over the class attribute to the player element when we're in a div embed
  21272. // the class is already set up properly in the divEmbed case
  21273. // and we want to make sure that the `video-js` class doesn't get lost
  21274. if (!(divEmbed && attr === 'class')) {
  21275. el.setAttribute(attr, attrs[attr]);
  21276. }
  21277. if (divEmbed) {
  21278. tag.setAttribute(attr, attrs[attr]);
  21279. }
  21280. });
  21281. // Update tag id/class for use as HTML5 playback tech
  21282. // Might think we should do this after embedding in container so .vjs-tech class
  21283. // doesn't flash 100% width/height, but class only applies with .video-js parent
  21284. tag.playerId = tag.id;
  21285. tag.id += '_html5_api';
  21286. tag.className = 'vjs-tech';
  21287. // Make player findable on elements
  21288. tag.player = el.player = this;
  21289. // Default state of video is paused
  21290. this.addClass('vjs-paused');
  21291. const deviceClassNames = ['IS_SMART_TV', 'IS_TIZEN', 'IS_WEBOS', 'IS_ANDROID', 'IS_IPAD', 'IS_IPHONE', 'IS_CHROMECAST_RECEIVER'].filter(key => browser[key]).map(key => {
  21292. return 'vjs-device-' + key.substring(3).toLowerCase().replace(/\_/g, '-');
  21293. });
  21294. this.addClass(...deviceClassNames);
  21295. // Add a style element in the player that we'll use to set the width/height
  21296. // of the player in a way that's still overridable by CSS, just like the
  21297. // video element
  21298. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  21299. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  21300. const defaultsStyleEl = $('.vjs-styles-defaults');
  21301. const head = $('head');
  21302. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  21303. }
  21304. this.fill_ = false;
  21305. this.fluid_ = false;
  21306. // Pass in the width/height/aspectRatio options which will update the style el
  21307. this.width(this.options_.width);
  21308. this.height(this.options_.height);
  21309. this.fill(this.options_.fill);
  21310. this.fluid(this.options_.fluid);
  21311. this.aspectRatio(this.options_.aspectRatio);
  21312. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  21313. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  21314. // Hide any links within the video/audio tag,
  21315. // because IE doesn't hide them completely from screen readers.
  21316. const links = tag.getElementsByTagName('a');
  21317. for (let i = 0; i < links.length; i++) {
  21318. const linkEl = links.item(i);
  21319. addClass(linkEl, 'vjs-hidden');
  21320. linkEl.setAttribute('hidden', 'hidden');
  21321. }
  21322. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  21323. // keep track of the original for later so we can know if the source originally failed
  21324. tag.initNetworkState_ = tag.networkState;
  21325. // Wrap video tag in div (el/box) container
  21326. if (tag.parentNode && !playerElIngest) {
  21327. tag.parentNode.insertBefore(el, tag);
  21328. }
  21329. // insert the tag as the first child of the player element
  21330. // then manually add it to the children array so that this.addChild
  21331. // will work properly for other components
  21332. //
  21333. // Breaks iPhone, fixed in HTML5 setup.
  21334. prependTo(tag, el);
  21335. this.children_.unshift(tag);
  21336. // Set lang attr on player to ensure CSS :lang() in consistent with player
  21337. // if it's been set to something different to the doc
  21338. this.el_.setAttribute('lang', this.language_);
  21339. this.el_.setAttribute('translate', 'no');
  21340. this.el_ = el;
  21341. return el;
  21342. }
  21343. /**
  21344. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  21345. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  21346. * behavior.
  21347. *
  21348. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  21349. *
  21350. * @param {string|null} [value]
  21351. * The value to set the `Player`'s crossOrigin to. If an argument is
  21352. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  21353. *
  21354. * @return {string|null|undefined}
  21355. * - The current crossOrigin value of the `Player` when getting.
  21356. * - undefined when setting
  21357. */
  21358. crossOrigin(value) {
  21359. // `null` can be set to unset a value
  21360. if (typeof value === 'undefined') {
  21361. return this.techGet_('crossOrigin');
  21362. }
  21363. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  21364. log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  21365. return;
  21366. }
  21367. this.techCall_('setCrossOrigin', value);
  21368. if (this.posterImage) {
  21369. this.posterImage.crossOrigin(value);
  21370. }
  21371. return;
  21372. }
  21373. /**
  21374. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  21375. * To get the current width use `currentWidth()`.
  21376. *
  21377. * @param {number|string} [value]
  21378. * CSS value to set the `Player`'s width to.
  21379. *
  21380. * @return {number|undefined}
  21381. * - The current width of the `Player` when getting.
  21382. * - Nothing when setting
  21383. */
  21384. width(value) {
  21385. return this.dimension('width', value);
  21386. }
  21387. /**
  21388. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  21389. * To get the current height use `currentheight()`.
  21390. *
  21391. * @param {number|string} [value]
  21392. * CSS value to set the `Player`'s height to.
  21393. *
  21394. * @return {number|undefined}
  21395. * - The current height of the `Player` when getting.
  21396. * - Nothing when setting
  21397. */
  21398. height(value) {
  21399. return this.dimension('height', value);
  21400. }
  21401. /**
  21402. * A getter/setter for the `Player`'s width & height.
  21403. *
  21404. * @param {string} dimension
  21405. * This string can be:
  21406. * - 'width'
  21407. * - 'height'
  21408. *
  21409. * @param {number|string} [value]
  21410. * Value for dimension specified in the first argument.
  21411. *
  21412. * @return {number}
  21413. * The dimension arguments value when getting (width/height).
  21414. */
  21415. dimension(dimension, value) {
  21416. const privDimension = dimension + '_';
  21417. if (value === undefined) {
  21418. return this[privDimension] || 0;
  21419. }
  21420. if (value === '' || value === 'auto') {
  21421. // If an empty string is given, reset the dimension to be automatic
  21422. this[privDimension] = undefined;
  21423. this.updateStyleEl_();
  21424. return;
  21425. }
  21426. const parsedVal = parseFloat(value);
  21427. if (isNaN(parsedVal)) {
  21428. log.error(`Improper value "${value}" supplied for for ${dimension}`);
  21429. return;
  21430. }
  21431. this[privDimension] = parsedVal;
  21432. this.updateStyleEl_();
  21433. }
  21434. /**
  21435. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  21436. *
  21437. * Turning this on will turn off fill mode.
  21438. *
  21439. * @param {boolean} [bool]
  21440. * - A value of true adds the class.
  21441. * - A value of false removes the class.
  21442. * - No value will be a getter.
  21443. *
  21444. * @return {boolean|undefined}
  21445. * - The value of fluid when getting.
  21446. * - `undefined` when setting.
  21447. */
  21448. fluid(bool) {
  21449. if (bool === undefined) {
  21450. return !!this.fluid_;
  21451. }
  21452. this.fluid_ = !!bool;
  21453. if (isEvented(this)) {
  21454. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21455. }
  21456. if (bool) {
  21457. this.addClass('vjs-fluid');
  21458. this.fill(false);
  21459. addEventedCallback(this, () => {
  21460. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21461. });
  21462. } else {
  21463. this.removeClass('vjs-fluid');
  21464. }
  21465. this.updateStyleEl_();
  21466. }
  21467. /**
  21468. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  21469. *
  21470. * Turning this on will turn off fluid mode.
  21471. *
  21472. * @param {boolean} [bool]
  21473. * - A value of true adds the class.
  21474. * - A value of false removes the class.
  21475. * - No value will be a getter.
  21476. *
  21477. * @return {boolean|undefined}
  21478. * - The value of fluid when getting.
  21479. * - `undefined` when setting.
  21480. */
  21481. fill(bool) {
  21482. if (bool === undefined) {
  21483. return !!this.fill_;
  21484. }
  21485. this.fill_ = !!bool;
  21486. if (bool) {
  21487. this.addClass('vjs-fill');
  21488. this.fluid(false);
  21489. } else {
  21490. this.removeClass('vjs-fill');
  21491. }
  21492. }
  21493. /**
  21494. * Get/Set the aspect ratio
  21495. *
  21496. * @param {string} [ratio]
  21497. * Aspect ratio for player
  21498. *
  21499. * @return {string|undefined}
  21500. * returns the current aspect ratio when getting
  21501. */
  21502. /**
  21503. * A getter/setter for the `Player`'s aspect ratio.
  21504. *
  21505. * @param {string} [ratio]
  21506. * The value to set the `Player`'s aspect ratio to.
  21507. *
  21508. * @return {string|undefined}
  21509. * - The current aspect ratio of the `Player` when getting.
  21510. * - undefined when setting
  21511. */
  21512. aspectRatio(ratio) {
  21513. if (ratio === undefined) {
  21514. return this.aspectRatio_;
  21515. }
  21516. // Check for width:height format
  21517. if (!/^\d+\:\d+$/.test(ratio)) {
  21518. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  21519. }
  21520. this.aspectRatio_ = ratio;
  21521. // We're assuming if you set an aspect ratio you want fluid mode,
  21522. // because in fixed mode you could calculate width and height yourself.
  21523. this.fluid(true);
  21524. this.updateStyleEl_();
  21525. }
  21526. /**
  21527. * Update styles of the `Player` element (height, width and aspect ratio).
  21528. *
  21529. * @private
  21530. * @listens Tech#loadedmetadata
  21531. */
  21532. updateStyleEl_() {
  21533. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  21534. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  21535. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  21536. const techEl = this.tech_ && this.tech_.el();
  21537. if (techEl) {
  21538. if (width >= 0) {
  21539. techEl.width = width;
  21540. }
  21541. if (height >= 0) {
  21542. techEl.height = height;
  21543. }
  21544. }
  21545. return;
  21546. }
  21547. let width;
  21548. let height;
  21549. let aspectRatio;
  21550. let idClass;
  21551. // The aspect ratio is either used directly or to calculate width and height.
  21552. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  21553. // Use any aspectRatio that's been specifically set
  21554. aspectRatio = this.aspectRatio_;
  21555. } else if (this.videoWidth() > 0) {
  21556. // Otherwise try to get the aspect ratio from the video metadata
  21557. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  21558. } else {
  21559. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  21560. aspectRatio = '16:9';
  21561. }
  21562. // Get the ratio as a decimal we can use to calculate dimensions
  21563. const ratioParts = aspectRatio.split(':');
  21564. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  21565. if (this.width_ !== undefined) {
  21566. // Use any width that's been specifically set
  21567. width = this.width_;
  21568. } else if (this.height_ !== undefined) {
  21569. // Or calculate the width from the aspect ratio if a height has been set
  21570. width = this.height_ / ratioMultiplier;
  21571. } else {
  21572. // Or use the video's metadata, or use the video el's default of 300
  21573. width = this.videoWidth() || 300;
  21574. }
  21575. if (this.height_ !== undefined) {
  21576. // Use any height that's been specifically set
  21577. height = this.height_;
  21578. } else {
  21579. // Otherwise calculate the height from the ratio and the width
  21580. height = width * ratioMultiplier;
  21581. }
  21582. // Ensure the CSS class is valid by starting with an alpha character
  21583. if (/^[^a-zA-Z]/.test(this.id())) {
  21584. idClass = 'dimensions-' + this.id();
  21585. } else {
  21586. idClass = this.id() + '-dimensions';
  21587. }
  21588. // Ensure the right class is still on the player for the style element
  21589. this.addClass(idClass);
  21590. setTextContent(this.styleEl_, `
  21591. .${idClass} {
  21592. width: ${width}px;
  21593. height: ${height}px;
  21594. }
  21595. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  21596. padding-top: ${ratioMultiplier * 100}%;
  21597. }
  21598. `);
  21599. }
  21600. /**
  21601. * Load/Create an instance of playback {@link Tech} including element
  21602. * and API methods. Then append the `Tech` element in `Player` as a child.
  21603. *
  21604. * @param {string} techName
  21605. * name of the playback technology
  21606. *
  21607. * @param {string} source
  21608. * video source
  21609. *
  21610. * @private
  21611. */
  21612. loadTech_(techName, source) {
  21613. // Pause and remove current playback technology
  21614. if (this.tech_) {
  21615. this.unloadTech_();
  21616. }
  21617. const titleTechName = toTitleCase(techName);
  21618. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  21619. // get rid of the HTML5 video tag as soon as we are using another tech
  21620. if (titleTechName !== 'Html5' && this.tag) {
  21621. Tech.getTech('Html5').disposeMediaElement(this.tag);
  21622. this.tag.player = null;
  21623. this.tag = null;
  21624. }
  21625. this.techName_ = titleTechName;
  21626. // Turn off API access because we're loading a new tech that might load asynchronously
  21627. this.isReady_ = false;
  21628. let autoplay = this.autoplay();
  21629. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  21630. // because the player is going to handle autoplay on `loadstart`
  21631. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  21632. autoplay = false;
  21633. }
  21634. // Grab tech-specific options from player options and add source and parent element to use.
  21635. const techOptions = {
  21636. source,
  21637. autoplay,
  21638. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  21639. 'playerId': this.id(),
  21640. 'techId': `${this.id()}_${camelTechName}_api`,
  21641. 'playsinline': this.options_.playsinline,
  21642. 'preload': this.options_.preload,
  21643. 'loop': this.options_.loop,
  21644. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  21645. 'muted': this.options_.muted,
  21646. 'poster': this.poster(),
  21647. 'language': this.language(),
  21648. 'playerElIngest': this.playerElIngest_ || false,
  21649. 'vtt.js': this.options_['vtt.js'],
  21650. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  21651. 'enableSourceset': this.options_.enableSourceset
  21652. };
  21653. ALL.names.forEach(name => {
  21654. const props = ALL[name];
  21655. techOptions[props.getterName] = this[props.privateName];
  21656. });
  21657. Object.assign(techOptions, this.options_[titleTechName]);
  21658. Object.assign(techOptions, this.options_[camelTechName]);
  21659. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  21660. if (this.tag) {
  21661. techOptions.tag = this.tag;
  21662. }
  21663. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  21664. techOptions.startTime = this.cache_.currentTime;
  21665. }
  21666. // Initialize tech instance
  21667. const TechClass = Tech.getTech(techName);
  21668. if (!TechClass) {
  21669. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  21670. }
  21671. this.tech_ = new TechClass(techOptions);
  21672. // player.triggerReady is always async, so don't need this to be async
  21673. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  21674. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  21675. // Listen to all HTML5-defined events and trigger them on the player
  21676. TECH_EVENTS_RETRIGGER.forEach(event => {
  21677. this.on(this.tech_, event, e => this[`handleTech${toTitleCase(event)}_`](e));
  21678. });
  21679. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  21680. this.on(this.tech_, event, eventObj => {
  21681. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  21682. this.queuedCallbacks_.push({
  21683. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  21684. event: eventObj
  21685. });
  21686. return;
  21687. }
  21688. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  21689. });
  21690. });
  21691. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  21692. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  21693. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  21694. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  21695. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  21696. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  21697. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  21698. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  21699. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  21700. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  21701. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  21702. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  21703. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  21704. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  21705. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  21706. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  21707. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  21708. this.usingNativeControls(this.techGet_('controls'));
  21709. if (this.controls() && !this.usingNativeControls()) {
  21710. this.addTechControlsListeners_();
  21711. }
  21712. // Add the tech element in the DOM if it was not already there
  21713. // Make sure to not insert the original video element if using Html5
  21714. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  21715. prependTo(this.tech_.el(), this.el());
  21716. }
  21717. // Get rid of the original video tag reference after the first tech is loaded
  21718. if (this.tag) {
  21719. this.tag.player = null;
  21720. this.tag = null;
  21721. }
  21722. }
  21723. /**
  21724. * Unload and dispose of the current playback {@link Tech}.
  21725. *
  21726. * @private
  21727. */
  21728. unloadTech_() {
  21729. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  21730. ALL.names.forEach(name => {
  21731. const props = ALL[name];
  21732. this[props.privateName] = this[props.getterName]();
  21733. });
  21734. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  21735. this.isReady_ = false;
  21736. this.tech_.dispose();
  21737. this.tech_ = false;
  21738. if (this.isPosterFromTech_) {
  21739. this.poster_ = '';
  21740. this.trigger('posterchange');
  21741. }
  21742. this.isPosterFromTech_ = false;
  21743. }
  21744. /**
  21745. * Return a reference to the current {@link Tech}.
  21746. * It will print a warning by default about the danger of using the tech directly
  21747. * but any argument that is passed in will silence the warning.
  21748. *
  21749. * @param {*} [safety]
  21750. * Anything passed in to silence the warning
  21751. *
  21752. * @return {Tech}
  21753. * The Tech
  21754. */
  21755. tech(safety) {
  21756. if (safety === undefined) {
  21757. 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');
  21758. }
  21759. return this.tech_;
  21760. }
  21761. /**
  21762. * An object that contains Video.js version.
  21763. *
  21764. * @typedef {Object} PlayerVersion
  21765. *
  21766. * @property {string} 'video.js' - Video.js version
  21767. */
  21768. /**
  21769. * Returns an object with Video.js version.
  21770. *
  21771. * @return {PlayerVersion}
  21772. * An object with Video.js version.
  21773. */
  21774. version() {
  21775. return {
  21776. 'video.js': version
  21777. };
  21778. }
  21779. /**
  21780. * Set up click and touch listeners for the playback element
  21781. *
  21782. * - On desktops: a click on the video itself will toggle playback
  21783. * - On mobile devices: a click on the video toggles controls
  21784. * which is done by toggling the user state between active and
  21785. * inactive
  21786. * - A tap can signal that a user has become active or has become inactive
  21787. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  21788. * quick tap should hide them again (signaling the user is in an inactive
  21789. * viewing state)
  21790. * - In addition to this, we still want the user to be considered inactive after
  21791. * a few seconds of inactivity.
  21792. *
  21793. * > Note: the only part of iOS interaction we can't mimic with this setup
  21794. * is a touch and hold on the video element counting as activity in order to
  21795. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  21796. * on any controls will still keep the user active
  21797. *
  21798. * @private
  21799. */
  21800. addTechControlsListeners_() {
  21801. // Make sure to remove all the previous listeners in case we are called multiple times.
  21802. this.removeTechControlsListeners_();
  21803. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  21804. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21805. // If the controls were hidden we don't want that to change without a tap event
  21806. // so we'll check if the controls were already showing before reporting user
  21807. // activity
  21808. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21809. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21810. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21811. // The tap listener needs to come after the touchend listener because the tap
  21812. // listener cancels out any reportedUserActivity when setting userActive(false)
  21813. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  21814. }
  21815. /**
  21816. * Remove the listeners used for click and tap controls. This is needed for
  21817. * toggling to controls disabled, where a tap/touch should do nothing.
  21818. *
  21819. * @private
  21820. */
  21821. removeTechControlsListeners_() {
  21822. // We don't want to just use `this.off()` because there might be other needed
  21823. // listeners added by techs that extend this.
  21824. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  21825. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21826. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21827. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21828. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  21829. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21830. }
  21831. /**
  21832. * Player waits for the tech to be ready
  21833. *
  21834. * @private
  21835. */
  21836. handleTechReady_() {
  21837. this.triggerReady();
  21838. // Keep the same volume as before
  21839. if (this.cache_.volume) {
  21840. this.techCall_('setVolume', this.cache_.volume);
  21841. }
  21842. // Look if the tech found a higher resolution poster while loading
  21843. this.handleTechPosterChange_();
  21844. // Update the duration if available
  21845. this.handleTechDurationChange_();
  21846. }
  21847. /**
  21848. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  21849. *
  21850. * @fires Player#loadstart
  21851. * @listens Tech#loadstart
  21852. * @private
  21853. */
  21854. handleTechLoadStart_() {
  21855. // TODO: Update to use `emptied` event instead. See #1277.
  21856. this.removeClass('vjs-ended', 'vjs-seeking');
  21857. // reset the error state
  21858. this.error(null);
  21859. // Update the duration
  21860. this.handleTechDurationChange_();
  21861. if (!this.paused()) {
  21862. /**
  21863. * Fired when the user agent begins looking for media data
  21864. *
  21865. * @event Player#loadstart
  21866. * @type {Event}
  21867. */
  21868. this.trigger('loadstart');
  21869. } else {
  21870. // reset the hasStarted state
  21871. this.hasStarted(false);
  21872. this.trigger('loadstart');
  21873. }
  21874. // autoplay happens after loadstart for the browser,
  21875. // so we mimic that behavior
  21876. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  21877. }
  21878. /**
  21879. * Handle autoplay string values, rather than the typical boolean
  21880. * values that should be handled by the tech. Note that this is not
  21881. * part of any specification. Valid values and what they do can be
  21882. * found on the autoplay getter at Player#autoplay()
  21883. */
  21884. manualAutoplay_(type) {
  21885. if (!this.tech_ || typeof type !== 'string') {
  21886. return;
  21887. }
  21888. // Save original muted() value, set muted to true, and attempt to play().
  21889. // On promise rejection, restore muted from saved value
  21890. const resolveMuted = () => {
  21891. const previouslyMuted = this.muted();
  21892. this.muted(true);
  21893. const restoreMuted = () => {
  21894. this.muted(previouslyMuted);
  21895. };
  21896. // restore muted on play terminatation
  21897. this.playTerminatedQueue_.push(restoreMuted);
  21898. const mutedPromise = this.play();
  21899. if (!isPromise(mutedPromise)) {
  21900. return;
  21901. }
  21902. return mutedPromise.catch(err => {
  21903. restoreMuted();
  21904. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  21905. });
  21906. };
  21907. let promise;
  21908. // if muted defaults to true
  21909. // the only thing we can do is call play
  21910. if (type === 'any' && !this.muted()) {
  21911. promise = this.play();
  21912. if (isPromise(promise)) {
  21913. promise = promise.catch(resolveMuted);
  21914. }
  21915. } else if (type === 'muted' && !this.muted()) {
  21916. promise = resolveMuted();
  21917. } else {
  21918. promise = this.play();
  21919. }
  21920. if (!isPromise(promise)) {
  21921. return;
  21922. }
  21923. return promise.then(() => {
  21924. this.trigger({
  21925. type: 'autoplay-success',
  21926. autoplay: type
  21927. });
  21928. }).catch(() => {
  21929. this.trigger({
  21930. type: 'autoplay-failure',
  21931. autoplay: type
  21932. });
  21933. });
  21934. }
  21935. /**
  21936. * Update the internal source caches so that we return the correct source from
  21937. * `src()`, `currentSource()`, and `currentSources()`.
  21938. *
  21939. * > Note: `currentSources` will not be updated if the source that is passed in exists
  21940. * in the current `currentSources` cache.
  21941. *
  21942. *
  21943. * @param {Tech~SourceObject} srcObj
  21944. * A string or object source to update our caches to.
  21945. */
  21946. updateSourceCaches_(srcObj = '') {
  21947. let src = srcObj;
  21948. let type = '';
  21949. if (typeof src !== 'string') {
  21950. src = srcObj.src;
  21951. type = srcObj.type;
  21952. }
  21953. // make sure all the caches are set to default values
  21954. // to prevent null checking
  21955. this.cache_.source = this.cache_.source || {};
  21956. this.cache_.sources = this.cache_.sources || [];
  21957. // try to get the type of the src that was passed in
  21958. if (src && !type) {
  21959. type = findMimetype(this, src);
  21960. }
  21961. // update `currentSource` cache always
  21962. this.cache_.source = merge({}, srcObj, {
  21963. src,
  21964. type
  21965. });
  21966. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  21967. const sourceElSources = [];
  21968. const sourceEls = this.$$('source');
  21969. const matchingSourceEls = [];
  21970. for (let i = 0; i < sourceEls.length; i++) {
  21971. const sourceObj = getAttributes(sourceEls[i]);
  21972. sourceElSources.push(sourceObj);
  21973. if (sourceObj.src && sourceObj.src === src) {
  21974. matchingSourceEls.push(sourceObj.src);
  21975. }
  21976. }
  21977. // if we have matching source els but not matching sources
  21978. // the current source cache is not up to date
  21979. if (matchingSourceEls.length && !matchingSources.length) {
  21980. this.cache_.sources = sourceElSources;
  21981. // if we don't have matching source or source els set the
  21982. // sources cache to the `currentSource` cache
  21983. } else if (!matchingSources.length) {
  21984. this.cache_.sources = [this.cache_.source];
  21985. }
  21986. // update the tech `src` cache
  21987. this.cache_.src = src;
  21988. }
  21989. /**
  21990. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  21991. * causing the media element to reload.
  21992. *
  21993. * It will fire for the initial source and each subsequent source.
  21994. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  21995. *
  21996. * The event object for this event contains a `src` property that will contain the source
  21997. * that was available when the event was triggered. This is generally only necessary if Video.js
  21998. * is switching techs while the source was being changed.
  21999. *
  22000. * It is also fired when `load` is called on the player (or media element)
  22001. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  22002. * says that the resource selection algorithm needs to be aborted and restarted.
  22003. * In this case, it is very likely that the `src` property will be set to the
  22004. * empty string `""` to indicate we do not know what the source will be but
  22005. * that it is changing.
  22006. *
  22007. * *This event is currently still experimental and may change in minor releases.*
  22008. * __To use this, pass `enableSourceset` option to the player.__
  22009. *
  22010. * @event Player#sourceset
  22011. * @type {Event}
  22012. * @prop {string} src
  22013. * The source url available when the `sourceset` was triggered.
  22014. * It will be an empty string if we cannot know what the source is
  22015. * but know that the source will change.
  22016. */
  22017. /**
  22018. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  22019. *
  22020. * @fires Player#sourceset
  22021. * @listens Tech#sourceset
  22022. * @private
  22023. */
  22024. handleTechSourceset_(event) {
  22025. // only update the source cache when the source
  22026. // was not updated using the player api
  22027. if (!this.changingSrc_) {
  22028. let updateSourceCaches = src => this.updateSourceCaches_(src);
  22029. const playerSrc = this.currentSource().src;
  22030. const eventSrc = event.src;
  22031. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  22032. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  22033. // if both the tech source and the player source were updated we assume
  22034. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  22035. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  22036. updateSourceCaches = () => {};
  22037. }
  22038. }
  22039. // update the source to the initial source right away
  22040. // in some cases this will be empty string
  22041. updateSourceCaches(eventSrc);
  22042. // if the `sourceset` `src` was an empty string
  22043. // wait for a `loadstart` to update the cache to `currentSrc`.
  22044. // If a sourceset happens before a `loadstart`, we reset the state
  22045. if (!event.src) {
  22046. this.tech_.any(['sourceset', 'loadstart'], e => {
  22047. // if a sourceset happens before a `loadstart` there
  22048. // is nothing to do as this `handleTechSourceset_`
  22049. // will be called again and this will be handled there.
  22050. if (e.type === 'sourceset') {
  22051. return;
  22052. }
  22053. const techSrc = this.techGet_('currentSrc');
  22054. this.lastSource_.tech = techSrc;
  22055. this.updateSourceCaches_(techSrc);
  22056. });
  22057. }
  22058. }
  22059. this.lastSource_ = {
  22060. player: this.currentSource().src,
  22061. tech: event.src
  22062. };
  22063. this.trigger({
  22064. src: event.src,
  22065. type: 'sourceset'
  22066. });
  22067. }
  22068. /**
  22069. * Add/remove the vjs-has-started class
  22070. *
  22071. *
  22072. * @param {boolean} request
  22073. * - true: adds the class
  22074. * - false: remove the class
  22075. *
  22076. * @return {boolean}
  22077. * the boolean value of hasStarted_
  22078. */
  22079. hasStarted(request) {
  22080. if (request === undefined) {
  22081. // act as getter, if we have no request to change
  22082. return this.hasStarted_;
  22083. }
  22084. if (request === this.hasStarted_) {
  22085. return;
  22086. }
  22087. this.hasStarted_ = request;
  22088. if (this.hasStarted_) {
  22089. this.addClass('vjs-has-started');
  22090. } else {
  22091. this.removeClass('vjs-has-started');
  22092. }
  22093. }
  22094. /**
  22095. * Fired whenever the media begins or resumes playback
  22096. *
  22097. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  22098. * @fires Player#play
  22099. * @listens Tech#play
  22100. * @private
  22101. */
  22102. handleTechPlay_() {
  22103. this.removeClass('vjs-ended', 'vjs-paused');
  22104. this.addClass('vjs-playing');
  22105. // hide the poster when the user hits play
  22106. this.hasStarted(true);
  22107. /**
  22108. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  22109. * playback has started or resumed.
  22110. *
  22111. * @event Player#play
  22112. * @type {Event}
  22113. */
  22114. this.trigger('play');
  22115. }
  22116. /**
  22117. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  22118. *
  22119. * If there were any events queued while the playback rate was zero, fire
  22120. * those events now.
  22121. *
  22122. * @private
  22123. * @method Player#handleTechRateChange_
  22124. * @fires Player#ratechange
  22125. * @listens Tech#ratechange
  22126. */
  22127. handleTechRateChange_() {
  22128. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  22129. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  22130. this.queuedCallbacks_ = [];
  22131. }
  22132. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  22133. /**
  22134. * Fires when the playing speed of the audio/video is changed
  22135. *
  22136. * @event Player#ratechange
  22137. * @type {event}
  22138. */
  22139. this.trigger('ratechange');
  22140. }
  22141. /**
  22142. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  22143. *
  22144. * @fires Player#waiting
  22145. * @listens Tech#waiting
  22146. * @private
  22147. */
  22148. handleTechWaiting_() {
  22149. this.addClass('vjs-waiting');
  22150. /**
  22151. * A readyState change on the DOM element has caused playback to stop.
  22152. *
  22153. * @event Player#waiting
  22154. * @type {Event}
  22155. */
  22156. this.trigger('waiting');
  22157. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  22158. // premature removal of the waiting class, wait for the time to change.
  22159. const timeWhenWaiting = this.currentTime();
  22160. const timeUpdateListener = () => {
  22161. if (timeWhenWaiting !== this.currentTime()) {
  22162. this.removeClass('vjs-waiting');
  22163. this.off('timeupdate', timeUpdateListener);
  22164. }
  22165. };
  22166. this.on('timeupdate', timeUpdateListener);
  22167. }
  22168. /**
  22169. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  22170. * > Note: This is not consistent between browsers. See #1351
  22171. *
  22172. * @fires Player#canplay
  22173. * @listens Tech#canplay
  22174. * @private
  22175. */
  22176. handleTechCanPlay_() {
  22177. this.removeClass('vjs-waiting');
  22178. /**
  22179. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  22180. *
  22181. * @event Player#canplay
  22182. * @type {Event}
  22183. */
  22184. this.trigger('canplay');
  22185. }
  22186. /**
  22187. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  22188. *
  22189. * @fires Player#canplaythrough
  22190. * @listens Tech#canplaythrough
  22191. * @private
  22192. */
  22193. handleTechCanPlayThrough_() {
  22194. this.removeClass('vjs-waiting');
  22195. /**
  22196. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  22197. * entire media file can be played without buffering.
  22198. *
  22199. * @event Player#canplaythrough
  22200. * @type {Event}
  22201. */
  22202. this.trigger('canplaythrough');
  22203. }
  22204. /**
  22205. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  22206. *
  22207. * @fires Player#playing
  22208. * @listens Tech#playing
  22209. * @private
  22210. */
  22211. handleTechPlaying_() {
  22212. this.removeClass('vjs-waiting');
  22213. /**
  22214. * The media is no longer blocked from playback, and has started playing.
  22215. *
  22216. * @event Player#playing
  22217. * @type {Event}
  22218. */
  22219. this.trigger('playing');
  22220. }
  22221. /**
  22222. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  22223. *
  22224. * @fires Player#seeking
  22225. * @listens Tech#seeking
  22226. * @private
  22227. */
  22228. handleTechSeeking_() {
  22229. this.addClass('vjs-seeking');
  22230. /**
  22231. * Fired whenever the player is jumping to a new time
  22232. *
  22233. * @event Player#seeking
  22234. * @type {Event}
  22235. */
  22236. this.trigger('seeking');
  22237. }
  22238. /**
  22239. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  22240. *
  22241. * @fires Player#seeked
  22242. * @listens Tech#seeked
  22243. * @private
  22244. */
  22245. handleTechSeeked_() {
  22246. this.removeClass('vjs-seeking', 'vjs-ended');
  22247. /**
  22248. * Fired when the player has finished jumping to a new time
  22249. *
  22250. * @event Player#seeked
  22251. * @type {Event}
  22252. */
  22253. this.trigger('seeked');
  22254. }
  22255. /**
  22256. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  22257. *
  22258. * @fires Player#pause
  22259. * @listens Tech#pause
  22260. * @private
  22261. */
  22262. handleTechPause_() {
  22263. this.removeClass('vjs-playing');
  22264. this.addClass('vjs-paused');
  22265. /**
  22266. * Fired whenever the media has been paused
  22267. *
  22268. * @event Player#pause
  22269. * @type {Event}
  22270. */
  22271. this.trigger('pause');
  22272. }
  22273. /**
  22274. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  22275. *
  22276. * @fires Player#ended
  22277. * @listens Tech#ended
  22278. * @private
  22279. */
  22280. handleTechEnded_() {
  22281. this.addClass('vjs-ended');
  22282. this.removeClass('vjs-waiting');
  22283. if (this.options_.loop) {
  22284. this.currentTime(0);
  22285. this.play();
  22286. } else if (!this.paused()) {
  22287. this.pause();
  22288. }
  22289. /**
  22290. * Fired when the end of the media resource is reached (currentTime == duration)
  22291. *
  22292. * @event Player#ended
  22293. * @type {Event}
  22294. */
  22295. this.trigger('ended');
  22296. }
  22297. /**
  22298. * Fired when the duration of the media resource is first known or changed
  22299. *
  22300. * @listens Tech#durationchange
  22301. * @private
  22302. */
  22303. handleTechDurationChange_() {
  22304. this.duration(this.techGet_('duration'));
  22305. }
  22306. /**
  22307. * Handle a click on the media element to play/pause
  22308. *
  22309. * @param {Event} event
  22310. * the event that caused this function to trigger
  22311. *
  22312. * @listens Tech#click
  22313. * @private
  22314. */
  22315. handleTechClick_(event) {
  22316. // When controls are disabled a click should not toggle playback because
  22317. // the click is considered a control
  22318. if (!this.controls_) {
  22319. return;
  22320. }
  22321. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  22322. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  22323. this.options_.userActions.click.call(this, event);
  22324. } else if (this.paused()) {
  22325. silencePromise(this.play());
  22326. } else {
  22327. this.pause();
  22328. }
  22329. }
  22330. }
  22331. /**
  22332. * Handle a double-click on the media element to enter/exit fullscreen,
  22333. * or exit documentPictureInPicture mode
  22334. *
  22335. * @param {Event} event
  22336. * the event that caused this function to trigger
  22337. *
  22338. * @listens Tech#dblclick
  22339. * @private
  22340. */
  22341. handleTechDoubleClick_(event) {
  22342. if (!this.controls_) {
  22343. return;
  22344. }
  22345. // we do not want to toggle fullscreen state
  22346. // when double-clicking inside a control bar or a modal
  22347. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  22348. if (!inAllowedEls) {
  22349. /*
  22350. * options.userActions.doubleClick
  22351. *
  22352. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  22353. * Set to `false` to disable double-click handling
  22354. * Set to a function to substitute an external double-click handler
  22355. */
  22356. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  22357. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  22358. this.options_.userActions.doubleClick.call(this, event);
  22359. } else if (this.isInPictureInPicture() && !document.pictureInPictureElement) {
  22360. // Checking the presence of `window.documentPictureInPicture.window` complicates
  22361. // tests, checking `document.pictureInPictureElement` also works. It wouldn't
  22362. // be null in regular picture in picture.
  22363. // Exit picture in picture mode. This gesture can't trigger pip on the main window.
  22364. this.exitPictureInPicture();
  22365. } else if (this.isFullscreen()) {
  22366. this.exitFullscreen();
  22367. } else {
  22368. this.requestFullscreen();
  22369. }
  22370. }
  22371. }
  22372. }
  22373. /**
  22374. * Handle a tap on the media element. It will toggle the user
  22375. * activity state, which hides and shows the controls.
  22376. *
  22377. * @listens Tech#tap
  22378. * @private
  22379. */
  22380. handleTechTap_() {
  22381. this.userActive(!this.userActive());
  22382. }
  22383. /**
  22384. * Handle touch to start
  22385. *
  22386. * @listens Tech#touchstart
  22387. * @private
  22388. */
  22389. handleTechTouchStart_() {
  22390. this.userWasActive = this.userActive();
  22391. }
  22392. /**
  22393. * Handle touch to move
  22394. *
  22395. * @listens Tech#touchmove
  22396. * @private
  22397. */
  22398. handleTechTouchMove_() {
  22399. if (this.userWasActive) {
  22400. this.reportUserActivity();
  22401. }
  22402. }
  22403. /**
  22404. * Handle touch to end
  22405. *
  22406. * @param {Event} event
  22407. * the touchend event that triggered
  22408. * this function
  22409. *
  22410. * @listens Tech#touchend
  22411. * @private
  22412. */
  22413. handleTechTouchEnd_(event) {
  22414. // Stop the mouse events from also happening
  22415. if (event.cancelable) {
  22416. event.preventDefault();
  22417. }
  22418. }
  22419. /**
  22420. * @private
  22421. */
  22422. toggleFullscreenClass_() {
  22423. if (this.isFullscreen()) {
  22424. this.addClass('vjs-fullscreen');
  22425. } else {
  22426. this.removeClass('vjs-fullscreen');
  22427. }
  22428. }
  22429. /**
  22430. * when the document fschange event triggers it calls this
  22431. */
  22432. documentFullscreenChange_(e) {
  22433. const targetPlayer = e.target.player;
  22434. // if another player was fullscreen
  22435. // do a null check for targetPlayer because older firefox's would put document as e.target
  22436. if (targetPlayer && targetPlayer !== this) {
  22437. return;
  22438. }
  22439. const el = this.el();
  22440. let isFs = document[this.fsApi_.fullscreenElement] === el;
  22441. if (!isFs && el.matches) {
  22442. isFs = el.matches(':' + this.fsApi_.fullscreen);
  22443. }
  22444. this.isFullscreen(isFs);
  22445. }
  22446. /**
  22447. * Handle Tech Fullscreen Change
  22448. *
  22449. * @param {Event} event
  22450. * the fullscreenchange event that triggered this function
  22451. *
  22452. * @param {Object} data
  22453. * the data that was sent with the event
  22454. *
  22455. * @private
  22456. * @listens Tech#fullscreenchange
  22457. * @fires Player#fullscreenchange
  22458. */
  22459. handleTechFullscreenChange_(event, data) {
  22460. if (data) {
  22461. if (data.nativeIOSFullscreen) {
  22462. this.addClass('vjs-ios-native-fs');
  22463. this.tech_.one('webkitendfullscreen', () => {
  22464. this.removeClass('vjs-ios-native-fs');
  22465. });
  22466. }
  22467. this.isFullscreen(data.isFullscreen);
  22468. }
  22469. }
  22470. handleTechFullscreenError_(event, err) {
  22471. this.trigger('fullscreenerror', err);
  22472. }
  22473. /**
  22474. * @private
  22475. */
  22476. togglePictureInPictureClass_() {
  22477. if (this.isInPictureInPicture()) {
  22478. this.addClass('vjs-picture-in-picture');
  22479. } else {
  22480. this.removeClass('vjs-picture-in-picture');
  22481. }
  22482. }
  22483. /**
  22484. * Handle Tech Enter Picture-in-Picture.
  22485. *
  22486. * @param {Event} event
  22487. * the enterpictureinpicture event that triggered this function
  22488. *
  22489. * @private
  22490. * @listens Tech#enterpictureinpicture
  22491. */
  22492. handleTechEnterPictureInPicture_(event) {
  22493. this.isInPictureInPicture(true);
  22494. }
  22495. /**
  22496. * Handle Tech Leave Picture-in-Picture.
  22497. *
  22498. * @param {Event} event
  22499. * the leavepictureinpicture event that triggered this function
  22500. *
  22501. * @private
  22502. * @listens Tech#leavepictureinpicture
  22503. */
  22504. handleTechLeavePictureInPicture_(event) {
  22505. this.isInPictureInPicture(false);
  22506. }
  22507. /**
  22508. * Fires when an error occurred during the loading of an audio/video.
  22509. *
  22510. * @private
  22511. * @listens Tech#error
  22512. */
  22513. handleTechError_() {
  22514. const error = this.tech_.error();
  22515. if (error) {
  22516. this.error(error);
  22517. }
  22518. }
  22519. /**
  22520. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  22521. *
  22522. * @fires Player#textdata
  22523. * @listens Tech#textdata
  22524. * @private
  22525. */
  22526. handleTechTextData_() {
  22527. let data = null;
  22528. if (arguments.length > 1) {
  22529. data = arguments[1];
  22530. }
  22531. /**
  22532. * Fires when we get a textdata event from tech
  22533. *
  22534. * @event Player#textdata
  22535. * @type {Event}
  22536. */
  22537. this.trigger('textdata', data);
  22538. }
  22539. /**
  22540. * Get object for cached values.
  22541. *
  22542. * @return {Object}
  22543. * get the current object cache
  22544. */
  22545. getCache() {
  22546. return this.cache_;
  22547. }
  22548. /**
  22549. * Resets the internal cache object.
  22550. *
  22551. * Using this function outside the player constructor or reset method may
  22552. * have unintended side-effects.
  22553. *
  22554. * @private
  22555. */
  22556. resetCache_() {
  22557. this.cache_ = {
  22558. // Right now, the currentTime is not _really_ cached because it is always
  22559. // retrieved from the tech (see: currentTime). However, for completeness,
  22560. // we set it to zero here to ensure that if we do start actually caching
  22561. // it, we reset it along with everything else.
  22562. currentTime: 0,
  22563. initTime: 0,
  22564. inactivityTimeout: this.options_.inactivityTimeout,
  22565. duration: NaN,
  22566. lastVolume: 1,
  22567. lastPlaybackRate: this.defaultPlaybackRate(),
  22568. media: null,
  22569. src: '',
  22570. source: {},
  22571. sources: [],
  22572. playbackRates: [],
  22573. volume: 1
  22574. };
  22575. }
  22576. /**
  22577. * Pass values to the playback tech
  22578. *
  22579. * @param {string} [method]
  22580. * the method to call
  22581. *
  22582. * @param {Object} [arg]
  22583. * the argument to pass
  22584. *
  22585. * @private
  22586. */
  22587. techCall_(method, arg) {
  22588. // If it's not ready yet, call method when it is
  22589. this.ready(function () {
  22590. if (method in allowedSetters) {
  22591. return set(this.middleware_, this.tech_, method, arg);
  22592. } else if (method in allowedMediators) {
  22593. return mediate(this.middleware_, this.tech_, method, arg);
  22594. }
  22595. try {
  22596. if (this.tech_) {
  22597. this.tech_[method](arg);
  22598. }
  22599. } catch (e) {
  22600. log(e);
  22601. throw e;
  22602. }
  22603. }, true);
  22604. }
  22605. /**
  22606. * Mediate attempt to call playback tech method
  22607. * and return the value of the method called.
  22608. *
  22609. * @param {string} method
  22610. * Tech method
  22611. *
  22612. * @return {*}
  22613. * Value returned by the tech method called, undefined if tech
  22614. * is not ready or tech method is not present
  22615. *
  22616. * @private
  22617. */
  22618. techGet_(method) {
  22619. if (!this.tech_ || !this.tech_.isReady_) {
  22620. return;
  22621. }
  22622. if (method in allowedGetters) {
  22623. return get(this.middleware_, this.tech_, method);
  22624. } else if (method in allowedMediators) {
  22625. return mediate(this.middleware_, this.tech_, method);
  22626. }
  22627. // Log error when playback tech object is present but method
  22628. // is undefined or unavailable
  22629. try {
  22630. return this.tech_[method]();
  22631. } catch (e) {
  22632. // When building additional tech libs, an expected method may not be defined yet
  22633. if (this.tech_[method] === undefined) {
  22634. log(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  22635. throw e;
  22636. }
  22637. // When a method isn't available on the object it throws a TypeError
  22638. if (e.name === 'TypeError') {
  22639. log(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  22640. this.tech_.isReady_ = false;
  22641. throw e;
  22642. }
  22643. // If error unknown, just log and throw
  22644. log(e);
  22645. throw e;
  22646. }
  22647. }
  22648. /**
  22649. * Attempt to begin playback at the first opportunity.
  22650. *
  22651. * @return {Promise|undefined}
  22652. * Returns a promise if the browser supports Promises (or one
  22653. * was passed in as an option). This promise will be resolved on
  22654. * the return value of play. If this is undefined it will fulfill the
  22655. * promise chain otherwise the promise chain will be fulfilled when
  22656. * the promise from play is fulfilled.
  22657. */
  22658. play() {
  22659. return new Promise(resolve => {
  22660. this.play_(resolve);
  22661. });
  22662. }
  22663. /**
  22664. * The actual logic for play, takes a callback that will be resolved on the
  22665. * return value of play. This allows us to resolve to the play promise if there
  22666. * is one on modern browsers.
  22667. *
  22668. * @private
  22669. * @param {Function} [callback]
  22670. * The callback that should be called when the techs play is actually called
  22671. */
  22672. play_(callback = silencePromise) {
  22673. this.playCallbacks_.push(callback);
  22674. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  22675. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  22676. // treat calls to play_ somewhat like the `one` event function
  22677. if (this.waitToPlay_) {
  22678. this.off(['ready', 'loadstart'], this.waitToPlay_);
  22679. this.waitToPlay_ = null;
  22680. }
  22681. // if the player/tech is not ready or the src itself is not ready
  22682. // queue up a call to play on `ready` or `loadstart`
  22683. if (!this.isReady_ || !isSrcReady) {
  22684. this.waitToPlay_ = e => {
  22685. this.play_();
  22686. };
  22687. this.one(['ready', 'loadstart'], this.waitToPlay_);
  22688. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  22689. // in that case, we need to prime the video element by calling load so it'll be ready in time
  22690. if (!isSrcReady && isSafariOrIOS) {
  22691. this.load();
  22692. }
  22693. return;
  22694. }
  22695. // If the player/tech is ready and we have a source, we can attempt playback.
  22696. const val = this.techGet_('play');
  22697. // For native playback, reset the progress bar if we get a play call from a replay.
  22698. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  22699. if (isNativeReplay) {
  22700. this.resetProgressBar_();
  22701. }
  22702. // play was terminated if the returned value is null
  22703. if (val === null) {
  22704. this.runPlayTerminatedQueue_();
  22705. } else {
  22706. this.runPlayCallbacks_(val);
  22707. }
  22708. }
  22709. /**
  22710. * These functions will be run when if play is terminated. If play
  22711. * runPlayCallbacks_ is run these function will not be run. This allows us
  22712. * to differentiate between a terminated play and an actual call to play.
  22713. */
  22714. runPlayTerminatedQueue_() {
  22715. const queue = this.playTerminatedQueue_.slice(0);
  22716. this.playTerminatedQueue_ = [];
  22717. queue.forEach(function (q) {
  22718. q();
  22719. });
  22720. }
  22721. /**
  22722. * When a callback to play is delayed we have to run these
  22723. * callbacks when play is actually called on the tech. This function
  22724. * runs the callbacks that were delayed and accepts the return value
  22725. * from the tech.
  22726. *
  22727. * @param {undefined|Promise} val
  22728. * The return value from the tech.
  22729. */
  22730. runPlayCallbacks_(val) {
  22731. const callbacks = this.playCallbacks_.slice(0);
  22732. this.playCallbacks_ = [];
  22733. // clear play terminatedQueue since we finished a real play
  22734. this.playTerminatedQueue_ = [];
  22735. callbacks.forEach(function (cb) {
  22736. cb(val);
  22737. });
  22738. }
  22739. /**
  22740. * Pause the video playback
  22741. */
  22742. pause() {
  22743. this.techCall_('pause');
  22744. }
  22745. /**
  22746. * Check if the player is paused or has yet to play
  22747. *
  22748. * @return {boolean}
  22749. * - false: if the media is currently playing
  22750. * - true: if media is not currently playing
  22751. */
  22752. paused() {
  22753. // The initial state of paused should be true (in Safari it's actually false)
  22754. return this.techGet_('paused') === false ? false : true;
  22755. }
  22756. /**
  22757. * Get a TimeRange object representing the current ranges of time that the user
  22758. * has played.
  22759. *
  22760. * @return {TimeRange}
  22761. * A time range object that represents all the increments of time that have
  22762. * been played.
  22763. */
  22764. played() {
  22765. return this.techGet_('played') || createTimeRanges(0, 0);
  22766. }
  22767. /**
  22768. * Sets or returns whether or not the user is "scrubbing". Scrubbing is
  22769. * when the user has clicked the progress bar handle and is
  22770. * dragging it along the progress bar.
  22771. *
  22772. * @param {boolean} [isScrubbing]
  22773. * whether the user is or is not scrubbing
  22774. *
  22775. * @return {boolean|undefined}
  22776. * - The value of scrubbing when getting
  22777. * - Nothing when setting
  22778. */
  22779. scrubbing(isScrubbing) {
  22780. if (typeof isScrubbing === 'undefined') {
  22781. return this.scrubbing_;
  22782. }
  22783. this.scrubbing_ = !!isScrubbing;
  22784. this.techCall_('setScrubbing', this.scrubbing_);
  22785. if (isScrubbing) {
  22786. this.addClass('vjs-scrubbing');
  22787. } else {
  22788. this.removeClass('vjs-scrubbing');
  22789. }
  22790. }
  22791. /**
  22792. * Get or set the current time (in seconds)
  22793. *
  22794. * @param {number|string} [seconds]
  22795. * The time to seek to in seconds
  22796. *
  22797. * @return {number|undefined}
  22798. * - the current time in seconds when getting
  22799. * - Nothing when setting
  22800. */
  22801. currentTime(seconds) {
  22802. if (seconds === undefined) {
  22803. // cache last currentTime and return. default to 0 seconds
  22804. //
  22805. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  22806. // currentTime when scrubbing, but may not provide much performance benefit after all.
  22807. // Should be tested. Also something has to read the actual current time or the cache will
  22808. // never get updated.
  22809. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  22810. return this.cache_.currentTime;
  22811. }
  22812. if (seconds < 0) {
  22813. seconds = 0;
  22814. }
  22815. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  22816. this.cache_.initTime = seconds;
  22817. this.off('canplay', this.boundApplyInitTime_);
  22818. this.one('canplay', this.boundApplyInitTime_);
  22819. return;
  22820. }
  22821. this.techCall_('setCurrentTime', seconds);
  22822. this.cache_.initTime = 0;
  22823. if (isFinite(seconds)) {
  22824. this.cache_.currentTime = Number(seconds);
  22825. }
  22826. }
  22827. /**
  22828. * Apply the value of initTime stored in cache as currentTime.
  22829. *
  22830. * @private
  22831. */
  22832. applyInitTime_() {
  22833. this.currentTime(this.cache_.initTime);
  22834. }
  22835. /**
  22836. * Normally gets the length in time of the video in seconds;
  22837. * in all but the rarest use cases an argument will NOT be passed to the method
  22838. *
  22839. * > **NOTE**: The video must have started loading before the duration can be
  22840. * known, and depending on preload behaviour may not be known until the video starts
  22841. * playing.
  22842. *
  22843. * @fires Player#durationchange
  22844. *
  22845. * @param {number} [seconds]
  22846. * The duration of the video to set in seconds
  22847. *
  22848. * @return {number|undefined}
  22849. * - The duration of the video in seconds when getting
  22850. * - Nothing when setting
  22851. */
  22852. duration(seconds) {
  22853. if (seconds === undefined) {
  22854. // return NaN if the duration is not known
  22855. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  22856. }
  22857. seconds = parseFloat(seconds);
  22858. // Standardize on Infinity for signaling video is live
  22859. if (seconds < 0) {
  22860. seconds = Infinity;
  22861. }
  22862. if (seconds !== this.cache_.duration) {
  22863. // Cache the last set value for optimized scrubbing
  22864. this.cache_.duration = seconds;
  22865. if (seconds === Infinity) {
  22866. this.addClass('vjs-live');
  22867. } else {
  22868. this.removeClass('vjs-live');
  22869. }
  22870. if (!isNaN(seconds)) {
  22871. // Do not fire durationchange unless the duration value is known.
  22872. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  22873. /**
  22874. * @event Player#durationchange
  22875. * @type {Event}
  22876. */
  22877. this.trigger('durationchange');
  22878. }
  22879. }
  22880. }
  22881. /**
  22882. * Calculates how much time is left in the video. Not part
  22883. * of the native video API.
  22884. *
  22885. * @return {number}
  22886. * The time remaining in seconds
  22887. */
  22888. remainingTime() {
  22889. return this.duration() - this.currentTime();
  22890. }
  22891. /**
  22892. * A remaining time function that is intended to be used when
  22893. * the time is to be displayed directly to the user.
  22894. *
  22895. * @return {number}
  22896. * The rounded time remaining in seconds
  22897. */
  22898. remainingTimeDisplay() {
  22899. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  22900. }
  22901. //
  22902. // Kind of like an array of portions of the video that have been downloaded.
  22903. /**
  22904. * Get a TimeRange object with an array of the times of the video
  22905. * that have been downloaded. If you just want the percent of the
  22906. * video that's been downloaded, use bufferedPercent.
  22907. *
  22908. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  22909. *
  22910. * @return {TimeRange}
  22911. * A mock {@link TimeRanges} object (following HTML spec)
  22912. */
  22913. buffered() {
  22914. let buffered = this.techGet_('buffered');
  22915. if (!buffered || !buffered.length) {
  22916. buffered = createTimeRanges(0, 0);
  22917. }
  22918. return buffered;
  22919. }
  22920. /**
  22921. * Get the TimeRanges of the media that are currently available
  22922. * for seeking to.
  22923. *
  22924. * @see [Seekable Spec]{@link https://html.spec.whatwg.org/multipage/media.html#dom-media-seekable}
  22925. *
  22926. * @return {TimeRange}
  22927. * A mock {@link TimeRanges} object (following HTML spec)
  22928. */
  22929. seekable() {
  22930. let seekable = this.techGet_('seekable');
  22931. if (!seekable || !seekable.length) {
  22932. seekable = createTimeRanges(0, 0);
  22933. }
  22934. return seekable;
  22935. }
  22936. /**
  22937. * Returns whether the player is in the "seeking" state.
  22938. *
  22939. * @return {boolean} True if the player is in the seeking state, false if not.
  22940. */
  22941. seeking() {
  22942. return this.techGet_('seeking');
  22943. }
  22944. /**
  22945. * Returns whether the player is in the "ended" state.
  22946. *
  22947. * @return {boolean} True if the player is in the ended state, false if not.
  22948. */
  22949. ended() {
  22950. return this.techGet_('ended');
  22951. }
  22952. /**
  22953. * Returns the current state of network activity for the element, from
  22954. * the codes in the list below.
  22955. * - NETWORK_EMPTY (numeric value 0)
  22956. * The element has not yet been initialised. All attributes are in
  22957. * their initial states.
  22958. * - NETWORK_IDLE (numeric value 1)
  22959. * The element's resource selection algorithm is active and has
  22960. * selected a resource, but it is not actually using the network at
  22961. * this time.
  22962. * - NETWORK_LOADING (numeric value 2)
  22963. * The user agent is actively trying to download data.
  22964. * - NETWORK_NO_SOURCE (numeric value 3)
  22965. * The element's resource selection algorithm is active, but it has
  22966. * not yet found a resource to use.
  22967. *
  22968. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  22969. * @return {number} the current network activity state
  22970. */
  22971. networkState() {
  22972. return this.techGet_('networkState');
  22973. }
  22974. /**
  22975. * Returns a value that expresses the current state of the element
  22976. * with respect to rendering the current playback position, from the
  22977. * codes in the list below.
  22978. * - HAVE_NOTHING (numeric value 0)
  22979. * No information regarding the media resource is available.
  22980. * - HAVE_METADATA (numeric value 1)
  22981. * Enough of the resource has been obtained that the duration of the
  22982. * resource is available.
  22983. * - HAVE_CURRENT_DATA (numeric value 2)
  22984. * Data for the immediate current playback position is available.
  22985. * - HAVE_FUTURE_DATA (numeric value 3)
  22986. * Data for the immediate current playback position is available, as
  22987. * well as enough data for the user agent to advance the current
  22988. * playback position in the direction of playback.
  22989. * - HAVE_ENOUGH_DATA (numeric value 4)
  22990. * The user agent estimates that enough data is available for
  22991. * playback to proceed uninterrupted.
  22992. *
  22993. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  22994. * @return {number} the current playback rendering state
  22995. */
  22996. readyState() {
  22997. return this.techGet_('readyState');
  22998. }
  22999. /**
  23000. * Get the percent (as a decimal) of the video that's been downloaded.
  23001. * This method is not a part of the native HTML video API.
  23002. *
  23003. * @return {number}
  23004. * A decimal between 0 and 1 representing the percent
  23005. * that is buffered 0 being 0% and 1 being 100%
  23006. */
  23007. bufferedPercent() {
  23008. return bufferedPercent(this.buffered(), this.duration());
  23009. }
  23010. /**
  23011. * Get the ending time of the last buffered time range
  23012. * This is used in the progress bar to encapsulate all time ranges.
  23013. *
  23014. * @return {number}
  23015. * The end of the last buffered time range
  23016. */
  23017. bufferedEnd() {
  23018. const buffered = this.buffered();
  23019. const duration = this.duration();
  23020. let end = buffered.end(buffered.length - 1);
  23021. if (end > duration) {
  23022. end = duration;
  23023. }
  23024. return end;
  23025. }
  23026. /**
  23027. * Get or set the current volume of the media
  23028. *
  23029. * @param {number} [percentAsDecimal]
  23030. * The new volume as a decimal percent:
  23031. * - 0 is muted/0%/off
  23032. * - 1.0 is 100%/full
  23033. * - 0.5 is half volume or 50%
  23034. *
  23035. * @return {number|undefined}
  23036. * The current volume as a percent when getting
  23037. */
  23038. volume(percentAsDecimal) {
  23039. let vol;
  23040. if (percentAsDecimal !== undefined) {
  23041. // Force value to between 0 and 1
  23042. vol = Math.max(0, Math.min(1, percentAsDecimal));
  23043. this.cache_.volume = vol;
  23044. this.techCall_('setVolume', vol);
  23045. if (vol > 0) {
  23046. this.lastVolume_(vol);
  23047. }
  23048. return;
  23049. }
  23050. // Default to 1 when returning current volume.
  23051. vol = parseFloat(this.techGet_('volume'));
  23052. return isNaN(vol) ? 1 : vol;
  23053. }
  23054. /**
  23055. * Get the current muted state, or turn mute on or off
  23056. *
  23057. * @param {boolean} [muted]
  23058. * - true to mute
  23059. * - false to unmute
  23060. *
  23061. * @return {boolean|undefined}
  23062. * - true if mute is on and getting
  23063. * - false if mute is off and getting
  23064. * - nothing if setting
  23065. */
  23066. muted(muted) {
  23067. if (muted !== undefined) {
  23068. this.techCall_('setMuted', muted);
  23069. return;
  23070. }
  23071. return this.techGet_('muted') || false;
  23072. }
  23073. /**
  23074. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  23075. * indicates the state of muted on initial playback.
  23076. *
  23077. * ```js
  23078. * var myPlayer = videojs('some-player-id');
  23079. *
  23080. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  23081. *
  23082. * // get, should be false
  23083. * console.log(myPlayer.defaultMuted());
  23084. * // set to true
  23085. * myPlayer.defaultMuted(true);
  23086. * // get should be true
  23087. * console.log(myPlayer.defaultMuted());
  23088. * ```
  23089. *
  23090. * @param {boolean} [defaultMuted]
  23091. * - true to mute
  23092. * - false to unmute
  23093. *
  23094. * @return {boolean|undefined}
  23095. * - true if defaultMuted is on and getting
  23096. * - false if defaultMuted is off and getting
  23097. * - Nothing when setting
  23098. */
  23099. defaultMuted(defaultMuted) {
  23100. if (defaultMuted !== undefined) {
  23101. this.techCall_('setDefaultMuted', defaultMuted);
  23102. }
  23103. return this.techGet_('defaultMuted') || false;
  23104. }
  23105. /**
  23106. * Get the last volume, or set it
  23107. *
  23108. * @param {number} [percentAsDecimal]
  23109. * The new last volume as a decimal percent:
  23110. * - 0 is muted/0%/off
  23111. * - 1.0 is 100%/full
  23112. * - 0.5 is half volume or 50%
  23113. *
  23114. * @return {number|undefined}
  23115. * - The current value of lastVolume as a percent when getting
  23116. * - Nothing when setting
  23117. *
  23118. * @private
  23119. */
  23120. lastVolume_(percentAsDecimal) {
  23121. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  23122. this.cache_.lastVolume = percentAsDecimal;
  23123. return;
  23124. }
  23125. return this.cache_.lastVolume;
  23126. }
  23127. /**
  23128. * Check if current tech can support native fullscreen
  23129. * (e.g. with built in controls like iOS)
  23130. *
  23131. * @return {boolean}
  23132. * if native fullscreen is supported
  23133. */
  23134. supportsFullScreen() {
  23135. return this.techGet_('supportsFullScreen') || false;
  23136. }
  23137. /**
  23138. * Check if the player is in fullscreen mode or tell the player that it
  23139. * is or is not in fullscreen mode.
  23140. *
  23141. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  23142. * property and instead document.fullscreenElement is used. But isFullscreen is
  23143. * still a valuable property for internal player workings.
  23144. *
  23145. * @param {boolean} [isFS]
  23146. * Set the players current fullscreen state
  23147. *
  23148. * @return {boolean|undefined}
  23149. * - true if fullscreen is on and getting
  23150. * - false if fullscreen is off and getting
  23151. * - Nothing when setting
  23152. */
  23153. isFullscreen(isFS) {
  23154. if (isFS !== undefined) {
  23155. const oldValue = this.isFullscreen_;
  23156. this.isFullscreen_ = Boolean(isFS);
  23157. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  23158. // this is the only place where we trigger fullscreenchange events for older browsers
  23159. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  23160. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  23161. /**
  23162. * @event Player#fullscreenchange
  23163. * @type {Event}
  23164. */
  23165. this.trigger('fullscreenchange');
  23166. }
  23167. this.toggleFullscreenClass_();
  23168. return;
  23169. }
  23170. return this.isFullscreen_;
  23171. }
  23172. /**
  23173. * Increase the size of the video to full screen
  23174. * In some browsers, full screen is not supported natively, so it enters
  23175. * "full window mode", where the video fills the browser window.
  23176. * In browsers and devices that support native full screen, sometimes the
  23177. * browser's default controls will be shown, and not the Video.js custom skin.
  23178. * This includes most mobile devices (iOS, Android) and older versions of
  23179. * Safari.
  23180. *
  23181. * @param {Object} [fullscreenOptions]
  23182. * Override the player fullscreen options
  23183. *
  23184. * @fires Player#fullscreenchange
  23185. */
  23186. requestFullscreen(fullscreenOptions) {
  23187. if (this.isInPictureInPicture()) {
  23188. this.exitPictureInPicture();
  23189. }
  23190. const self = this;
  23191. return new Promise((resolve, reject) => {
  23192. function offHandler() {
  23193. self.off('fullscreenerror', errorHandler);
  23194. self.off('fullscreenchange', changeHandler);
  23195. }
  23196. function changeHandler() {
  23197. offHandler();
  23198. resolve();
  23199. }
  23200. function errorHandler(e, err) {
  23201. offHandler();
  23202. reject(err);
  23203. }
  23204. self.one('fullscreenchange', changeHandler);
  23205. self.one('fullscreenerror', errorHandler);
  23206. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  23207. if (promise) {
  23208. promise.then(offHandler, offHandler);
  23209. promise.then(resolve, reject);
  23210. }
  23211. });
  23212. }
  23213. requestFullscreenHelper_(fullscreenOptions) {
  23214. let fsOptions;
  23215. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  23216. // Use defaults or player configured option unless passed directly to this method.
  23217. if (!this.fsApi_.prefixed) {
  23218. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  23219. if (fullscreenOptions !== undefined) {
  23220. fsOptions = fullscreenOptions;
  23221. }
  23222. }
  23223. // This method works as follows:
  23224. // 1. if a fullscreen api is available, use it
  23225. // 1. call requestFullscreen with potential options
  23226. // 2. if we got a promise from above, use it to update isFullscreen()
  23227. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  23228. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  23229. // 3. otherwise, use "fullWindow" mode
  23230. if (this.fsApi_.requestFullscreen) {
  23231. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  23232. // Even on browsers with promise support this may not return a promise
  23233. if (promise) {
  23234. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  23235. }
  23236. return promise;
  23237. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  23238. // we can't take the video.js controls fullscreen but we can go fullscreen
  23239. // with native controls
  23240. this.techCall_('enterFullScreen');
  23241. } else {
  23242. // fullscreen isn't supported so we'll just stretch the video element to
  23243. // fill the viewport
  23244. this.enterFullWindow();
  23245. }
  23246. }
  23247. /**
  23248. * Return the video to its normal size after having been in full screen mode
  23249. *
  23250. * @fires Player#fullscreenchange
  23251. */
  23252. exitFullscreen() {
  23253. const self = this;
  23254. return new Promise((resolve, reject) => {
  23255. function offHandler() {
  23256. self.off('fullscreenerror', errorHandler);
  23257. self.off('fullscreenchange', changeHandler);
  23258. }
  23259. function changeHandler() {
  23260. offHandler();
  23261. resolve();
  23262. }
  23263. function errorHandler(e, err) {
  23264. offHandler();
  23265. reject(err);
  23266. }
  23267. self.one('fullscreenchange', changeHandler);
  23268. self.one('fullscreenerror', errorHandler);
  23269. const promise = self.exitFullscreenHelper_();
  23270. if (promise) {
  23271. promise.then(offHandler, offHandler);
  23272. // map the promise to our resolve/reject methods
  23273. promise.then(resolve, reject);
  23274. }
  23275. });
  23276. }
  23277. exitFullscreenHelper_() {
  23278. if (this.fsApi_.requestFullscreen) {
  23279. const promise = document[this.fsApi_.exitFullscreen]();
  23280. // Even on browsers with promise support this may not return a promise
  23281. if (promise) {
  23282. // we're splitting the promise here, so, we want to catch the
  23283. // potential error so that this chain doesn't have unhandled errors
  23284. silencePromise(promise.then(() => this.isFullscreen(false)));
  23285. }
  23286. return promise;
  23287. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  23288. this.techCall_('exitFullScreen');
  23289. } else {
  23290. this.exitFullWindow();
  23291. }
  23292. }
  23293. /**
  23294. * When fullscreen isn't supported we can stretch the
  23295. * video container to as wide as the browser will let us.
  23296. *
  23297. * @fires Player#enterFullWindow
  23298. */
  23299. enterFullWindow() {
  23300. this.isFullscreen(true);
  23301. this.isFullWindow = true;
  23302. // Storing original doc overflow value to return to when fullscreen is off
  23303. this.docOrigOverflow = document.documentElement.style.overflow;
  23304. // Add listener for esc key to exit fullscreen
  23305. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  23306. // Hide any scroll bars
  23307. document.documentElement.style.overflow = 'hidden';
  23308. // Apply fullscreen styles
  23309. addClass(document.body, 'vjs-full-window');
  23310. /**
  23311. * @event Player#enterFullWindow
  23312. * @type {Event}
  23313. */
  23314. this.trigger('enterFullWindow');
  23315. }
  23316. /**
  23317. * Check for call to either exit full window or
  23318. * full screen on ESC key
  23319. *
  23320. * @param {string} event
  23321. * Event to check for key press
  23322. */
  23323. fullWindowOnEscKey(event) {
  23324. if (event.key === 'Escape') {
  23325. if (this.isFullscreen() === true) {
  23326. if (!this.isFullWindow) {
  23327. this.exitFullscreen();
  23328. } else {
  23329. this.exitFullWindow();
  23330. }
  23331. }
  23332. }
  23333. }
  23334. /**
  23335. * Exit full window
  23336. *
  23337. * @fires Player#exitFullWindow
  23338. */
  23339. exitFullWindow() {
  23340. this.isFullscreen(false);
  23341. this.isFullWindow = false;
  23342. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  23343. // Unhide scroll bars.
  23344. document.documentElement.style.overflow = this.docOrigOverflow;
  23345. // Remove fullscreen styles
  23346. removeClass(document.body, 'vjs-full-window');
  23347. // Resize the box, controller, and poster to original sizes
  23348. // this.positionAll();
  23349. /**
  23350. * @event Player#exitFullWindow
  23351. * @type {Event}
  23352. */
  23353. this.trigger('exitFullWindow');
  23354. }
  23355. /**
  23356. * Get or set disable Picture-in-Picture mode.
  23357. *
  23358. * @param {boolean} [value]
  23359. * - true will disable Picture-in-Picture mode
  23360. * - false will enable Picture-in-Picture mode
  23361. */
  23362. disablePictureInPicture(value) {
  23363. if (value === undefined) {
  23364. return this.techGet_('disablePictureInPicture');
  23365. }
  23366. this.techCall_('setDisablePictureInPicture', value);
  23367. this.options_.disablePictureInPicture = value;
  23368. this.trigger('disablepictureinpicturechanged');
  23369. }
  23370. /**
  23371. * Check if the player is in Picture-in-Picture mode or tell the player that it
  23372. * is or is not in Picture-in-Picture mode.
  23373. *
  23374. * @param {boolean} [isPiP]
  23375. * Set the players current Picture-in-Picture state
  23376. *
  23377. * @return {boolean|undefined}
  23378. * - true if Picture-in-Picture is on and getting
  23379. * - false if Picture-in-Picture is off and getting
  23380. * - nothing if setting
  23381. */
  23382. isInPictureInPicture(isPiP) {
  23383. if (isPiP !== undefined) {
  23384. this.isInPictureInPicture_ = !!isPiP;
  23385. this.togglePictureInPictureClass_();
  23386. return;
  23387. }
  23388. return !!this.isInPictureInPicture_;
  23389. }
  23390. /**
  23391. * Create a floating video window always on top of other windows so that users may
  23392. * continue consuming media while they interact with other content sites, or
  23393. * applications on their device.
  23394. *
  23395. * This can use document picture-in-picture or element picture in picture
  23396. *
  23397. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  23398. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  23399. *
  23400. *
  23401. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  23402. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  23403. *
  23404. * @fires Player#enterpictureinpicture
  23405. *
  23406. * @return {Promise}
  23407. * A promise with a Picture-in-Picture window.
  23408. */
  23409. requestPictureInPicture() {
  23410. if (this.options_.enableDocumentPictureInPicture && window.documentPictureInPicture) {
  23411. const pipContainer = document.createElement(this.el().tagName);
  23412. pipContainer.classList = this.el().classList;
  23413. pipContainer.classList.add('vjs-pip-container');
  23414. if (this.posterImage) {
  23415. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  23416. }
  23417. if (this.titleBar) {
  23418. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  23419. }
  23420. pipContainer.appendChild(createEl('p', {
  23421. className: 'vjs-pip-text'
  23422. }, {}, this.localize('Playing in picture-in-picture')));
  23423. return window.documentPictureInPicture.requestWindow({
  23424. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  23425. width: this.videoWidth(),
  23426. height: this.videoHeight()
  23427. }).then(pipWindow => {
  23428. copyStyleSheetsToWindow(pipWindow);
  23429. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  23430. pipWindow.document.body.appendChild(this.el_);
  23431. pipWindow.document.body.classList.add('vjs-pip-window');
  23432. this.player_.isInPictureInPicture(true);
  23433. this.player_.trigger({
  23434. type: 'enterpictureinpicture',
  23435. pipWindow
  23436. });
  23437. // Listen for the PiP closing event to move the video back.
  23438. pipWindow.addEventListener('pagehide', event => {
  23439. const pipVideo = event.target.querySelector('.video-js');
  23440. pipContainer.parentNode.replaceChild(pipVideo, pipContainer);
  23441. this.player_.isInPictureInPicture(false);
  23442. this.player_.trigger('leavepictureinpicture');
  23443. });
  23444. return pipWindow;
  23445. });
  23446. }
  23447. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  23448. /**
  23449. * This event fires when the player enters picture in picture mode
  23450. *
  23451. * @event Player#enterpictureinpicture
  23452. * @type {Event}
  23453. */
  23454. return this.techGet_('requestPictureInPicture');
  23455. }
  23456. return Promise.reject('No PiP mode is available');
  23457. }
  23458. /**
  23459. * Exit Picture-in-Picture mode.
  23460. *
  23461. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  23462. *
  23463. * @fires Player#leavepictureinpicture
  23464. *
  23465. * @return {Promise}
  23466. * A promise.
  23467. */
  23468. exitPictureInPicture() {
  23469. if (window.documentPictureInPicture && window.documentPictureInPicture.window) {
  23470. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the pagehide handler
  23471. window.documentPictureInPicture.window.close();
  23472. return Promise.resolve();
  23473. }
  23474. if ('pictureInPictureEnabled' in document) {
  23475. /**
  23476. * This event fires when the player leaves picture in picture mode
  23477. *
  23478. * @event Player#leavepictureinpicture
  23479. * @type {Event}
  23480. */
  23481. return document.exitPictureInPicture();
  23482. }
  23483. }
  23484. /**
  23485. * Called when this Player has focus and a key gets pressed down, or when
  23486. * any Component of this player receives a key press that it doesn't handle.
  23487. * This allows player-wide hotkeys (either as defined below, or optionally
  23488. * by an external function).
  23489. *
  23490. * @param {KeyboardEvent} event
  23491. * The `keydown` event that caused this function to be called.
  23492. *
  23493. * @listens keydown
  23494. */
  23495. handleKeyDown(event) {
  23496. const {
  23497. userActions
  23498. } = this.options_;
  23499. // Bail out if hotkeys are not configured.
  23500. if (!userActions || !userActions.hotkeys) {
  23501. return;
  23502. }
  23503. // Function that determines whether or not to exclude an element from
  23504. // hotkeys handling.
  23505. const excludeElement = el => {
  23506. const tagName = el.tagName.toLowerCase();
  23507. // The first and easiest test is for `contenteditable` elements.
  23508. if (el.isContentEditable) {
  23509. return true;
  23510. }
  23511. // Inputs matching these types will still trigger hotkey handling as
  23512. // they are not text inputs.
  23513. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  23514. if (tagName === 'input') {
  23515. return allowedInputTypes.indexOf(el.type) === -1;
  23516. }
  23517. // The final test is by tag name. These tags will be excluded entirely.
  23518. const excludedTags = ['textarea'];
  23519. return excludedTags.indexOf(tagName) !== -1;
  23520. };
  23521. // Bail out if the user is focused on an interactive form element.
  23522. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  23523. return;
  23524. }
  23525. if (typeof userActions.hotkeys === 'function') {
  23526. userActions.hotkeys.call(this, event);
  23527. } else {
  23528. this.handleHotkeys(event);
  23529. }
  23530. }
  23531. /**
  23532. * Called when this Player receives a hotkey keydown event.
  23533. * Supported player-wide hotkeys are:
  23534. *
  23535. * f - toggle fullscreen
  23536. * m - toggle mute
  23537. * k or Space - toggle play/pause
  23538. *
  23539. * @param {Event} event
  23540. * The `keydown` event that caused this function to be called.
  23541. */
  23542. handleHotkeys(event) {
  23543. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  23544. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  23545. const {
  23546. fullscreenKey = keydownEvent => event.key.toLowerCase() === 'f',
  23547. muteKey = keydownEvent => event.key.toLowerCase() === 'm',
  23548. playPauseKey = keydownEvent => event.key.toLowerCase() === 'k' || event.key.toLowerCase() === ' '
  23549. } = hotkeys;
  23550. if (fullscreenKey.call(this, event)) {
  23551. event.preventDefault();
  23552. event.stopPropagation();
  23553. const FSToggle = Component.getComponent('FullscreenToggle');
  23554. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  23555. FSToggle.prototype.handleClick.call(this, event);
  23556. }
  23557. } else if (muteKey.call(this, event)) {
  23558. event.preventDefault();
  23559. event.stopPropagation();
  23560. const MuteToggle = Component.getComponent('MuteToggle');
  23561. MuteToggle.prototype.handleClick.call(this, event);
  23562. } else if (playPauseKey.call(this, event)) {
  23563. event.preventDefault();
  23564. event.stopPropagation();
  23565. const PlayToggle = Component.getComponent('PlayToggle');
  23566. PlayToggle.prototype.handleClick.call(this, event);
  23567. }
  23568. }
  23569. /**
  23570. * Check whether the player can play a given mimetype
  23571. *
  23572. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  23573. *
  23574. * @param {string} type
  23575. * The mimetype to check
  23576. *
  23577. * @return {string}
  23578. * 'probably', 'maybe', or '' (empty string)
  23579. */
  23580. canPlayType(type) {
  23581. let can;
  23582. // Loop through each playback technology in the options order
  23583. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  23584. const techName = j[i];
  23585. let tech = Tech.getTech(techName);
  23586. // Support old behavior of techs being registered as components.
  23587. // Remove once that deprecated behavior is removed.
  23588. if (!tech) {
  23589. tech = Component.getComponent(techName);
  23590. }
  23591. // Check if the current tech is defined before continuing
  23592. if (!tech) {
  23593. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  23594. continue;
  23595. }
  23596. // Check if the browser supports this technology
  23597. if (tech.isSupported()) {
  23598. can = tech.canPlayType(type);
  23599. if (can) {
  23600. return can;
  23601. }
  23602. }
  23603. }
  23604. return '';
  23605. }
  23606. /**
  23607. * Select source based on tech-order or source-order
  23608. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  23609. * defaults to tech-order selection
  23610. *
  23611. * @param {Array} sources
  23612. * The sources for a media asset
  23613. *
  23614. * @return {Object|boolean}
  23615. * Object of source and tech order or false
  23616. */
  23617. selectSource(sources) {
  23618. // Get only the techs specified in `techOrder` that exist and are supported by the
  23619. // current platform
  23620. const techs = this.options_.techOrder.map(techName => {
  23621. return [techName, Tech.getTech(techName)];
  23622. }).filter(([techName, tech]) => {
  23623. // Check if the current tech is defined before continuing
  23624. if (tech) {
  23625. // Check if the browser supports this technology
  23626. return tech.isSupported();
  23627. }
  23628. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  23629. return false;
  23630. });
  23631. // Iterate over each `innerArray` element once per `outerArray` element and execute
  23632. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  23633. // that value.
  23634. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  23635. let found;
  23636. outerArray.some(outerChoice => {
  23637. return innerArray.some(innerChoice => {
  23638. found = tester(outerChoice, innerChoice);
  23639. if (found) {
  23640. return true;
  23641. }
  23642. });
  23643. });
  23644. return found;
  23645. };
  23646. let foundSourceAndTech;
  23647. const flip = fn => (a, b) => fn(b, a);
  23648. const finder = ([techName, tech], source) => {
  23649. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  23650. return {
  23651. source,
  23652. tech: techName
  23653. };
  23654. }
  23655. };
  23656. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  23657. // to select from them based on their priority.
  23658. if (this.options_.sourceOrder) {
  23659. // Source-first ordering
  23660. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  23661. } else {
  23662. // Tech-first ordering
  23663. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  23664. }
  23665. return foundSourceAndTech || false;
  23666. }
  23667. /**
  23668. * Executes source setting and getting logic
  23669. *
  23670. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23671. * A SourceObject, an array of SourceObjects, or a string referencing
  23672. * a URL to a media source. It is _highly recommended_ that an object
  23673. * or array of objects is used here, so that source selection
  23674. * algorithms can take the `type` into account.
  23675. *
  23676. * If not provided, this method acts as a getter.
  23677. * @param {boolean} [isRetry]
  23678. * Indicates whether this is being called internally as a result of a retry
  23679. *
  23680. * @return {string|undefined}
  23681. * If the `source` argument is missing, returns the current source
  23682. * URL. Otherwise, returns nothing/undefined.
  23683. */
  23684. handleSrc_(source, isRetry) {
  23685. // getter usage
  23686. if (typeof source === 'undefined') {
  23687. return this.cache_.src || '';
  23688. }
  23689. // Reset retry behavior for new source
  23690. if (this.resetRetryOnError_) {
  23691. this.resetRetryOnError_();
  23692. }
  23693. // filter out invalid sources and turn our source into
  23694. // an array of source objects
  23695. const sources = filterSource(source);
  23696. // if a source was passed in then it is invalid because
  23697. // it was filtered to a zero length Array. So we have to
  23698. // show an error
  23699. if (!sources.length) {
  23700. this.setTimeout(function () {
  23701. this.error({
  23702. code: 4,
  23703. message: this.options_.notSupportedMessage
  23704. });
  23705. }, 0);
  23706. return;
  23707. }
  23708. // initial sources
  23709. this.changingSrc_ = true;
  23710. // Only update the cached source list if we are not retrying a new source after error,
  23711. // since in that case we want to include the failed source(s) in the cache
  23712. if (!isRetry) {
  23713. this.cache_.sources = sources;
  23714. }
  23715. this.updateSourceCaches_(sources[0]);
  23716. // middlewareSource is the source after it has been changed by middleware
  23717. setSource(this, sources[0], (middlewareSource, mws) => {
  23718. this.middleware_ = mws;
  23719. // since sourceSet is async we have to update the cache again after we select a source since
  23720. // the source that is selected could be out of order from the cache update above this callback.
  23721. if (!isRetry) {
  23722. this.cache_.sources = sources;
  23723. }
  23724. this.updateSourceCaches_(middlewareSource);
  23725. const err = this.src_(middlewareSource);
  23726. if (err) {
  23727. if (sources.length > 1) {
  23728. return this.handleSrc_(sources.slice(1));
  23729. }
  23730. this.changingSrc_ = false;
  23731. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  23732. this.setTimeout(function () {
  23733. this.error({
  23734. code: 4,
  23735. message: this.options_.notSupportedMessage
  23736. });
  23737. }, 0);
  23738. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  23739. // this needs a better comment about why this is needed
  23740. this.triggerReady();
  23741. return;
  23742. }
  23743. setTech(mws, this.tech_);
  23744. });
  23745. // Try another available source if this one fails before playback.
  23746. if (sources.length > 1) {
  23747. const retry = () => {
  23748. // Remove the error modal
  23749. this.error(null);
  23750. this.handleSrc_(sources.slice(1), true);
  23751. };
  23752. const stopListeningForErrors = () => {
  23753. this.off('error', retry);
  23754. };
  23755. this.one('error', retry);
  23756. this.one('playing', stopListeningForErrors);
  23757. this.resetRetryOnError_ = () => {
  23758. this.off('error', retry);
  23759. this.off('playing', stopListeningForErrors);
  23760. };
  23761. }
  23762. }
  23763. /**
  23764. * Get or set the video source.
  23765. *
  23766. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23767. * A SourceObject, an array of SourceObjects, or a string referencing
  23768. * a URL to a media source. It is _highly recommended_ that an object
  23769. * or array of objects is used here, so that source selection
  23770. * algorithms can take the `type` into account.
  23771. *
  23772. * If not provided, this method acts as a getter.
  23773. *
  23774. * @return {string|undefined}
  23775. * If the `source` argument is missing, returns the current source
  23776. * URL. Otherwise, returns nothing/undefined.
  23777. */
  23778. src(source) {
  23779. return this.handleSrc_(source, false);
  23780. }
  23781. /**
  23782. * Set the source object on the tech, returns a boolean that indicates whether
  23783. * there is a tech that can play the source or not
  23784. *
  23785. * @param {Tech~SourceObject} source
  23786. * The source object to set on the Tech
  23787. *
  23788. * @return {boolean}
  23789. * - True if there is no Tech to playback this source
  23790. * - False otherwise
  23791. *
  23792. * @private
  23793. */
  23794. src_(source) {
  23795. const sourceTech = this.selectSource([source]);
  23796. if (!sourceTech) {
  23797. return true;
  23798. }
  23799. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  23800. this.changingSrc_ = true;
  23801. // load this technology with the chosen source
  23802. this.loadTech_(sourceTech.tech, sourceTech.source);
  23803. this.tech_.ready(() => {
  23804. this.changingSrc_ = false;
  23805. });
  23806. return false;
  23807. }
  23808. // wait until the tech is ready to set the source
  23809. // and set it synchronously if possible (#2326)
  23810. this.ready(function () {
  23811. // The setSource tech method was added with source handlers
  23812. // so older techs won't support it
  23813. // We need to check the direct prototype for the case where subclasses
  23814. // of the tech do not support source handlers
  23815. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  23816. this.techCall_('setSource', source);
  23817. } else {
  23818. this.techCall_('src', source.src);
  23819. }
  23820. this.changingSrc_ = false;
  23821. }, true);
  23822. return false;
  23823. }
  23824. /**
  23825. * Add a <source> element to the <video> element.
  23826. *
  23827. * @param {string} srcUrl
  23828. * The URL of the video source.
  23829. *
  23830. * @param {string} [mimeType]
  23831. * The MIME type of the video source. Optional but recommended.
  23832. *
  23833. * @return {boolean}
  23834. * Returns true if the source element was successfully added, false otherwise.
  23835. */
  23836. addSourceElement(srcUrl, mimeType) {
  23837. if (!this.tech_) {
  23838. return false;
  23839. }
  23840. return this.tech_.addSourceElement(srcUrl, mimeType);
  23841. }
  23842. /**
  23843. * Remove a <source> element from the <video> element by its URL.
  23844. *
  23845. * @param {string} srcUrl
  23846. * The URL of the source to remove.
  23847. *
  23848. * @return {boolean}
  23849. * Returns true if the source element was successfully removed, false otherwise.
  23850. */
  23851. removeSourceElement(srcUrl) {
  23852. if (!this.tech_) {
  23853. return false;
  23854. }
  23855. return this.tech_.removeSourceElement(srcUrl);
  23856. }
  23857. /**
  23858. * Begin loading the src data.
  23859. */
  23860. load() {
  23861. // Workaround to use the load method with the VHS.
  23862. // Does not cover the case when the load method is called directly from the mediaElement.
  23863. if (this.tech_ && this.tech_.vhs) {
  23864. this.src(this.currentSource());
  23865. return;
  23866. }
  23867. this.techCall_('load');
  23868. }
  23869. /**
  23870. * Reset the player. Loads the first tech in the techOrder,
  23871. * removes all the text tracks in the existing `tech`,
  23872. * and calls `reset` on the `tech`.
  23873. */
  23874. reset() {
  23875. if (this.paused()) {
  23876. this.doReset_();
  23877. } else {
  23878. const playPromise = this.play();
  23879. silencePromise(playPromise.then(() => this.doReset_()));
  23880. }
  23881. }
  23882. doReset_() {
  23883. if (this.tech_) {
  23884. this.tech_.clearTracks('text');
  23885. }
  23886. this.removeClass('vjs-playing');
  23887. this.addClass('vjs-paused');
  23888. this.resetCache_();
  23889. this.poster('');
  23890. this.loadTech_(this.options_.techOrder[0], null);
  23891. this.techCall_('reset');
  23892. this.resetControlBarUI_();
  23893. this.error(null);
  23894. if (this.titleBar) {
  23895. this.titleBar.update({
  23896. title: undefined,
  23897. description: undefined
  23898. });
  23899. }
  23900. if (isEvented(this)) {
  23901. this.trigger('playerreset');
  23902. }
  23903. }
  23904. /**
  23905. * Reset Control Bar's UI by calling sub-methods that reset
  23906. * all of Control Bar's components
  23907. */
  23908. resetControlBarUI_() {
  23909. this.resetProgressBar_();
  23910. this.resetPlaybackRate_();
  23911. this.resetVolumeBar_();
  23912. }
  23913. /**
  23914. * Reset tech's progress so progress bar is reset in the UI
  23915. */
  23916. resetProgressBar_() {
  23917. this.currentTime(0);
  23918. const {
  23919. currentTimeDisplay,
  23920. durationDisplay,
  23921. progressControl,
  23922. remainingTimeDisplay
  23923. } = this.controlBar || {};
  23924. const {
  23925. seekBar
  23926. } = progressControl || {};
  23927. if (currentTimeDisplay) {
  23928. currentTimeDisplay.updateContent();
  23929. }
  23930. if (durationDisplay) {
  23931. durationDisplay.updateContent();
  23932. }
  23933. if (remainingTimeDisplay) {
  23934. remainingTimeDisplay.updateContent();
  23935. }
  23936. if (seekBar) {
  23937. seekBar.update();
  23938. if (seekBar.loadProgressBar) {
  23939. seekBar.loadProgressBar.update();
  23940. }
  23941. }
  23942. }
  23943. /**
  23944. * Reset Playback ratio
  23945. */
  23946. resetPlaybackRate_() {
  23947. this.playbackRate(this.defaultPlaybackRate());
  23948. this.handleTechRateChange_();
  23949. }
  23950. /**
  23951. * Reset Volume bar
  23952. */
  23953. resetVolumeBar_() {
  23954. this.volume(1.0);
  23955. this.trigger('volumechange');
  23956. }
  23957. /**
  23958. * Returns all of the current source objects.
  23959. *
  23960. * @return {Tech~SourceObject[]}
  23961. * The current source objects
  23962. */
  23963. currentSources() {
  23964. const source = this.currentSource();
  23965. const sources = [];
  23966. // assume `{}` or `{ src }`
  23967. if (Object.keys(source).length !== 0) {
  23968. sources.push(source);
  23969. }
  23970. return this.cache_.sources || sources;
  23971. }
  23972. /**
  23973. * Returns the current source object.
  23974. *
  23975. * @return {Tech~SourceObject}
  23976. * The current source object
  23977. */
  23978. currentSource() {
  23979. return this.cache_.source || {};
  23980. }
  23981. /**
  23982. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  23983. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  23984. *
  23985. * @return {string}
  23986. * The current source
  23987. */
  23988. currentSrc() {
  23989. return this.currentSource() && this.currentSource().src || '';
  23990. }
  23991. /**
  23992. * Get the current source type e.g. video/mp4
  23993. * This can allow you rebuild the current source object so that you could load the same
  23994. * source and tech later
  23995. *
  23996. * @return {string}
  23997. * The source MIME type
  23998. */
  23999. currentType() {
  24000. return this.currentSource() && this.currentSource().type || '';
  24001. }
  24002. /**
  24003. * Get or set the preload attribute
  24004. *
  24005. * @param {'none'|'auto'|'metadata'} [value]
  24006. * Preload mode to pass to tech
  24007. *
  24008. * @return {string|undefined}
  24009. * - The preload attribute value when getting
  24010. * - Nothing when setting
  24011. */
  24012. preload(value) {
  24013. if (value !== undefined) {
  24014. this.techCall_('setPreload', value);
  24015. this.options_.preload = value;
  24016. return;
  24017. }
  24018. return this.techGet_('preload');
  24019. }
  24020. /**
  24021. * Get or set the autoplay option. When this is a boolean it will
  24022. * modify the attribute on the tech. When this is a string the attribute on
  24023. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  24024. *
  24025. * @param {boolean|'play'|'muted'|'any'} [value]
  24026. * - true: autoplay using the browser behavior
  24027. * - false: do not autoplay
  24028. * - 'play': call play() on every loadstart
  24029. * - 'muted': call muted() then play() on every loadstart
  24030. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  24031. * - *: values other than those listed here will be set `autoplay` to true
  24032. *
  24033. * @return {boolean|string|undefined}
  24034. * - The current value of autoplay when getting
  24035. * - Nothing when setting
  24036. */
  24037. autoplay(value) {
  24038. // getter usage
  24039. if (value === undefined) {
  24040. return this.options_.autoplay || false;
  24041. }
  24042. let techAutoplay;
  24043. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  24044. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  24045. this.options_.autoplay = value;
  24046. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  24047. techAutoplay = false;
  24048. // any falsy value sets autoplay to false in the browser,
  24049. // lets do the same
  24050. } else if (!value) {
  24051. this.options_.autoplay = false;
  24052. // any other value (ie truthy) sets autoplay to true
  24053. } else {
  24054. this.options_.autoplay = true;
  24055. }
  24056. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  24057. // if we don't have a tech then we do not queue up
  24058. // a setAutoplay call on tech ready. We do this because the
  24059. // autoplay option will be passed in the constructor and we
  24060. // do not need to set it twice
  24061. if (this.tech_) {
  24062. this.techCall_('setAutoplay', techAutoplay);
  24063. }
  24064. }
  24065. /**
  24066. * Set or unset the playsinline attribute.
  24067. * Playsinline tells the browser that non-fullscreen playback is preferred.
  24068. *
  24069. * @param {boolean} [value]
  24070. * - true means that we should try to play inline by default
  24071. * - false means that we should use the browser's default playback mode,
  24072. * which in most cases is inline. iOS Safari is a notable exception
  24073. * and plays fullscreen by default.
  24074. *
  24075. * @return {string|undefined}
  24076. * - the current value of playsinline
  24077. * - Nothing when setting
  24078. *
  24079. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  24080. */
  24081. playsinline(value) {
  24082. if (value !== undefined) {
  24083. this.techCall_('setPlaysinline', value);
  24084. this.options_.playsinline = value;
  24085. }
  24086. return this.techGet_('playsinline');
  24087. }
  24088. /**
  24089. * Get or set the loop attribute on the video element.
  24090. *
  24091. * @param {boolean} [value]
  24092. * - true means that we should loop the video
  24093. * - false means that we should not loop the video
  24094. *
  24095. * @return {boolean|undefined}
  24096. * - The current value of loop when getting
  24097. * - Nothing when setting
  24098. */
  24099. loop(value) {
  24100. if (value !== undefined) {
  24101. this.techCall_('setLoop', value);
  24102. this.options_.loop = value;
  24103. return;
  24104. }
  24105. return this.techGet_('loop');
  24106. }
  24107. /**
  24108. * Get or set the poster image source url
  24109. *
  24110. * @fires Player#posterchange
  24111. *
  24112. * @param {string} [src]
  24113. * Poster image source URL
  24114. *
  24115. * @return {string|undefined}
  24116. * - The current value of poster when getting
  24117. * - Nothing when setting
  24118. */
  24119. poster(src) {
  24120. if (src === undefined) {
  24121. return this.poster_;
  24122. }
  24123. // The correct way to remove a poster is to set as an empty string
  24124. // other falsey values will throw errors
  24125. if (!src) {
  24126. src = '';
  24127. }
  24128. if (src === this.poster_) {
  24129. return;
  24130. }
  24131. // update the internal poster variable
  24132. this.poster_ = src;
  24133. // update the tech's poster
  24134. this.techCall_('setPoster', src);
  24135. this.isPosterFromTech_ = false;
  24136. // alert components that the poster has been set
  24137. /**
  24138. * This event fires when the poster image is changed on the player.
  24139. *
  24140. * @event Player#posterchange
  24141. * @type {Event}
  24142. */
  24143. this.trigger('posterchange');
  24144. }
  24145. /**
  24146. * Some techs (e.g. YouTube) can provide a poster source in an
  24147. * asynchronous way. We want the poster component to use this
  24148. * poster source so that it covers up the tech's controls.
  24149. * (YouTube's play button). However we only want to use this
  24150. * source if the player user hasn't set a poster through
  24151. * the normal APIs.
  24152. *
  24153. * @fires Player#posterchange
  24154. * @listens Tech#posterchange
  24155. * @private
  24156. */
  24157. handleTechPosterChange_() {
  24158. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  24159. const newPoster = this.tech_.poster() || '';
  24160. if (newPoster !== this.poster_) {
  24161. this.poster_ = newPoster;
  24162. this.isPosterFromTech_ = true;
  24163. // Let components know the poster has changed
  24164. this.trigger('posterchange');
  24165. }
  24166. }
  24167. }
  24168. /**
  24169. * Get or set whether or not the controls are showing.
  24170. *
  24171. * @fires Player#controlsenabled
  24172. *
  24173. * @param {boolean} [bool]
  24174. * - true to turn controls on
  24175. * - false to turn controls off
  24176. *
  24177. * @return {boolean|undefined}
  24178. * - The current value of controls when getting
  24179. * - Nothing when setting
  24180. */
  24181. controls(bool) {
  24182. if (bool === undefined) {
  24183. return !!this.controls_;
  24184. }
  24185. bool = !!bool;
  24186. // Don't trigger a change event unless it actually changed
  24187. if (this.controls_ === bool) {
  24188. return;
  24189. }
  24190. this.controls_ = bool;
  24191. if (this.usingNativeControls()) {
  24192. this.techCall_('setControls', bool);
  24193. }
  24194. if (this.controls_) {
  24195. this.removeClass('vjs-controls-disabled');
  24196. this.addClass('vjs-controls-enabled');
  24197. /**
  24198. * @event Player#controlsenabled
  24199. * @type {Event}
  24200. */
  24201. this.trigger('controlsenabled');
  24202. if (!this.usingNativeControls()) {
  24203. this.addTechControlsListeners_();
  24204. }
  24205. } else {
  24206. this.removeClass('vjs-controls-enabled');
  24207. this.addClass('vjs-controls-disabled');
  24208. /**
  24209. * @event Player#controlsdisabled
  24210. * @type {Event}
  24211. */
  24212. this.trigger('controlsdisabled');
  24213. if (!this.usingNativeControls()) {
  24214. this.removeTechControlsListeners_();
  24215. }
  24216. }
  24217. }
  24218. /**
  24219. * Toggle native controls on/off. Native controls are the controls built into
  24220. * devices (e.g. default iPhone controls) or other techs
  24221. * (e.g. Vimeo Controls)
  24222. * **This should only be set by the current tech, because only the tech knows
  24223. * if it can support native controls**
  24224. *
  24225. * @fires Player#usingnativecontrols
  24226. * @fires Player#usingcustomcontrols
  24227. *
  24228. * @param {boolean} [bool]
  24229. * - true to turn native controls on
  24230. * - false to turn native controls off
  24231. *
  24232. * @return {boolean|undefined}
  24233. * - The current value of native controls when getting
  24234. * - Nothing when setting
  24235. */
  24236. usingNativeControls(bool) {
  24237. if (bool === undefined) {
  24238. return !!this.usingNativeControls_;
  24239. }
  24240. bool = !!bool;
  24241. // Don't trigger a change event unless it actually changed
  24242. if (this.usingNativeControls_ === bool) {
  24243. return;
  24244. }
  24245. this.usingNativeControls_ = bool;
  24246. if (this.usingNativeControls_) {
  24247. this.addClass('vjs-using-native-controls');
  24248. /**
  24249. * player is using the native device controls
  24250. *
  24251. * @event Player#usingnativecontrols
  24252. * @type {Event}
  24253. */
  24254. this.trigger('usingnativecontrols');
  24255. } else {
  24256. this.removeClass('vjs-using-native-controls');
  24257. /**
  24258. * player is using the custom HTML controls
  24259. *
  24260. * @event Player#usingcustomcontrols
  24261. * @type {Event}
  24262. */
  24263. this.trigger('usingcustomcontrols');
  24264. }
  24265. }
  24266. /**
  24267. * Set or get the current MediaError
  24268. *
  24269. * @fires Player#error
  24270. *
  24271. * @param {MediaError|string|number} [err]
  24272. * A MediaError or a string/number to be turned
  24273. * into a MediaError
  24274. *
  24275. * @return {MediaError|null|undefined}
  24276. * - The current MediaError when getting (or null)
  24277. * - Nothing when setting
  24278. */
  24279. error(err) {
  24280. if (err === undefined) {
  24281. return this.error_ || null;
  24282. }
  24283. // allow hooks to modify error object
  24284. hooks('beforeerror').forEach(hookFunction => {
  24285. const newErr = hookFunction(this, err);
  24286. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  24287. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  24288. return;
  24289. }
  24290. err = newErr;
  24291. });
  24292. // Suppress the first error message for no compatible source until
  24293. // user interaction
  24294. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  24295. const triggerSuppressedError = function () {
  24296. this.error(err);
  24297. };
  24298. this.options_.suppressNotSupportedError = false;
  24299. this.any(['click', 'touchstart'], triggerSuppressedError);
  24300. this.one('loadstart', function () {
  24301. this.off(['click', 'touchstart'], triggerSuppressedError);
  24302. });
  24303. return;
  24304. }
  24305. // restoring to default
  24306. if (err === null) {
  24307. this.error_ = null;
  24308. this.removeClass('vjs-error');
  24309. if (this.errorDisplay) {
  24310. this.errorDisplay.close();
  24311. }
  24312. return;
  24313. }
  24314. this.error_ = new MediaError(err);
  24315. // add the vjs-error classname to the player
  24316. this.addClass('vjs-error');
  24317. // log the name of the error type and any message
  24318. // IE11 logs "[object object]" and required you to expand message to see error object
  24319. log.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  24320. /**
  24321. * @event Player#error
  24322. * @type {Event}
  24323. */
  24324. this.trigger('error');
  24325. // notify hooks of the per player error
  24326. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  24327. return;
  24328. }
  24329. /**
  24330. * Report user activity
  24331. *
  24332. * @param {Object} event
  24333. * Event object
  24334. */
  24335. reportUserActivity(event) {
  24336. this.userActivity_ = true;
  24337. }
  24338. /**
  24339. * Get/set if user is active
  24340. *
  24341. * @fires Player#useractive
  24342. * @fires Player#userinactive
  24343. *
  24344. * @param {boolean} [bool]
  24345. * - true if the user is active
  24346. * - false if the user is inactive
  24347. *
  24348. * @return {boolean|undefined}
  24349. * - The current value of userActive when getting
  24350. * - Nothing when setting
  24351. */
  24352. userActive(bool) {
  24353. if (bool === undefined) {
  24354. return this.userActive_;
  24355. }
  24356. bool = !!bool;
  24357. if (bool === this.userActive_) {
  24358. return;
  24359. }
  24360. this.userActive_ = bool;
  24361. if (this.userActive_) {
  24362. this.userActivity_ = true;
  24363. this.removeClass('vjs-user-inactive');
  24364. this.addClass('vjs-user-active');
  24365. /**
  24366. * @event Player#useractive
  24367. * @type {Event}
  24368. */
  24369. this.trigger('useractive');
  24370. return;
  24371. }
  24372. // Chrome/Safari/IE have bugs where when you change the cursor it can
  24373. // trigger a mousemove event. This causes an issue when you're hiding
  24374. // the cursor when the user is inactive, and a mousemove signals user
  24375. // activity. Making it impossible to go into inactive mode. Specifically
  24376. // this happens in fullscreen when we really need to hide the cursor.
  24377. //
  24378. // When this gets resolved in ALL browsers it can be removed
  24379. // https://code.google.com/p/chromium/issues/detail?id=103041
  24380. if (this.tech_) {
  24381. this.tech_.one('mousemove', function (e) {
  24382. e.stopPropagation();
  24383. e.preventDefault();
  24384. });
  24385. }
  24386. this.userActivity_ = false;
  24387. this.removeClass('vjs-user-active');
  24388. this.addClass('vjs-user-inactive');
  24389. /**
  24390. * @event Player#userinactive
  24391. * @type {Event}
  24392. */
  24393. this.trigger('userinactive');
  24394. }
  24395. /**
  24396. * Listen for user activity based on timeout value
  24397. *
  24398. * @private
  24399. */
  24400. listenForUserActivity_() {
  24401. let mouseInProgress;
  24402. let lastMoveX;
  24403. let lastMoveY;
  24404. const handleActivity = bind_(this, this.reportUserActivity);
  24405. const handleMouseMove = function (e) {
  24406. // #1068 - Prevent mousemove spamming
  24407. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  24408. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  24409. lastMoveX = e.screenX;
  24410. lastMoveY = e.screenY;
  24411. handleActivity();
  24412. }
  24413. };
  24414. const handleMouseDown = function () {
  24415. handleActivity();
  24416. // For as long as the they are touching the device or have their mouse down,
  24417. // we consider them active even if they're not moving their finger or mouse.
  24418. // So we want to continue to update that they are active
  24419. this.clearInterval(mouseInProgress);
  24420. // Setting userActivity=true now and setting the interval to the same time
  24421. // as the activityCheck interval (250) should ensure we never miss the
  24422. // next activityCheck
  24423. mouseInProgress = this.setInterval(handleActivity, 250);
  24424. };
  24425. const handleMouseUpAndMouseLeave = function (event) {
  24426. handleActivity();
  24427. // Stop the interval that maintains activity if the mouse/touch is down
  24428. this.clearInterval(mouseInProgress);
  24429. };
  24430. // Any mouse movement will be considered user activity
  24431. this.on('mousedown', handleMouseDown);
  24432. this.on('mousemove', handleMouseMove);
  24433. this.on('mouseup', handleMouseUpAndMouseLeave);
  24434. this.on('mouseleave', handleMouseUpAndMouseLeave);
  24435. const controlBar = this.getChild('controlBar');
  24436. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  24437. // controlBar would no longer be hidden by default timeout.
  24438. if (controlBar && !IS_IOS && !IS_ANDROID) {
  24439. controlBar.on('mouseenter', function (event) {
  24440. if (this.player().options_.inactivityTimeout !== 0) {
  24441. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  24442. }
  24443. this.player().options_.inactivityTimeout = 0;
  24444. });
  24445. controlBar.on('mouseleave', function (event) {
  24446. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  24447. });
  24448. }
  24449. // Listen for keyboard navigation
  24450. // Shouldn't need to use inProgress interval because of key repeat
  24451. this.on('keydown', handleActivity);
  24452. this.on('keyup', handleActivity);
  24453. // Run an interval every 250 milliseconds instead of stuffing everything into
  24454. // the mousemove/touchmove function itself, to prevent performance degradation.
  24455. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  24456. // then gets picked up by this loop
  24457. // http://ejohn.org/blog/learning-from-twitter/
  24458. let inactivityTimeout;
  24459. /** @this Player */
  24460. const activityCheck = function () {
  24461. // Check to see if mouse/touch activity has happened
  24462. if (!this.userActivity_) {
  24463. return;
  24464. }
  24465. // Reset the activity tracker
  24466. this.userActivity_ = false;
  24467. // If the user state was inactive, set the state to active
  24468. this.userActive(true);
  24469. // Clear any existing inactivity timeout to start the timer over
  24470. this.clearTimeout(inactivityTimeout);
  24471. const timeout = this.options_.inactivityTimeout;
  24472. if (timeout <= 0) {
  24473. return;
  24474. }
  24475. // In <timeout> milliseconds, if no more activity has occurred the
  24476. // user will be considered inactive
  24477. inactivityTimeout = this.setTimeout(function () {
  24478. // Protect against the case where the inactivityTimeout can trigger just
  24479. // before the next user activity is picked up by the activity check loop
  24480. // causing a flicker
  24481. if (!this.userActivity_) {
  24482. this.userActive(false);
  24483. }
  24484. }, timeout);
  24485. };
  24486. this.setInterval(activityCheck, 250);
  24487. }
  24488. /**
  24489. * Gets or sets the current playback rate. A playback rate of
  24490. * 1.0 represents normal speed and 0.5 would indicate half-speed
  24491. * playback, for instance.
  24492. *
  24493. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  24494. *
  24495. * @param {number} [rate]
  24496. * New playback rate to set.
  24497. *
  24498. * @return {number|undefined}
  24499. * - The current playback rate when getting or 1.0
  24500. * - Nothing when setting
  24501. */
  24502. playbackRate(rate) {
  24503. if (rate !== undefined) {
  24504. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  24505. // that is registered above
  24506. this.techCall_('setPlaybackRate', rate);
  24507. return;
  24508. }
  24509. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24510. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  24511. }
  24512. return 1.0;
  24513. }
  24514. /**
  24515. * Gets or sets the current default playback rate. A default playback rate of
  24516. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  24517. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  24518. * not the current playbackRate.
  24519. *
  24520. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  24521. *
  24522. * @param {number} [rate]
  24523. * New default playback rate to set.
  24524. *
  24525. * @return {number|undefined}
  24526. * - The default playback rate when getting or 1.0
  24527. * - Nothing when setting
  24528. */
  24529. defaultPlaybackRate(rate) {
  24530. if (rate !== undefined) {
  24531. return this.techCall_('setDefaultPlaybackRate', rate);
  24532. }
  24533. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24534. return this.techGet_('defaultPlaybackRate');
  24535. }
  24536. return 1.0;
  24537. }
  24538. /**
  24539. * Gets or sets the audio flag
  24540. *
  24541. * @param {boolean} [bool]
  24542. * - true signals that this is an audio player
  24543. * - false signals that this is not an audio player
  24544. *
  24545. * @return {boolean|undefined}
  24546. * - The current value of isAudio when getting
  24547. * - Nothing when setting
  24548. */
  24549. isAudio(bool) {
  24550. if (bool !== undefined) {
  24551. this.isAudio_ = !!bool;
  24552. return;
  24553. }
  24554. return !!this.isAudio_;
  24555. }
  24556. updatePlayerHeightOnAudioOnlyMode_() {
  24557. const controlBar = this.getChild('ControlBar');
  24558. if (!controlBar || this.audioOnlyCache_.controlBarHeight === controlBar.currentHeight()) {
  24559. return;
  24560. }
  24561. this.audioOnlyCache_.controlBarHeight = controlBar.currentHeight();
  24562. this.height(this.audioOnlyCache_.controlBarHeight);
  24563. }
  24564. enableAudioOnlyUI_() {
  24565. // Update styling immediately to show the control bar so we can get its height
  24566. this.addClass('vjs-audio-only-mode');
  24567. const playerChildren = this.children();
  24568. const controlBar = this.getChild('ControlBar');
  24569. const controlBarHeight = controlBar && controlBar.currentHeight();
  24570. // Hide all player components except the control bar. Control bar components
  24571. // needed only for video are hidden with CSS
  24572. playerChildren.forEach(child => {
  24573. if (child === controlBar) {
  24574. return;
  24575. }
  24576. if (child.el_ && !child.hasClass('vjs-hidden')) {
  24577. child.hide();
  24578. this.audioOnlyCache_.hiddenChildren.push(child);
  24579. }
  24580. });
  24581. this.audioOnlyCache_.playerHeight = this.currentHeight();
  24582. this.audioOnlyCache_.controlBarHeight = controlBarHeight;
  24583. this.on('playerresize', this.boundUpdatePlayerHeightOnAudioOnlyMode_);
  24584. // Set the player height the same as the control bar
  24585. this.height(controlBarHeight);
  24586. this.trigger('audioonlymodechange');
  24587. }
  24588. disableAudioOnlyUI_() {
  24589. this.removeClass('vjs-audio-only-mode');
  24590. this.off('playerresize', this.boundUpdatePlayerHeightOnAudioOnlyMode_);
  24591. // Show player components that were previously hidden
  24592. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  24593. // Reset player height
  24594. this.height(this.audioOnlyCache_.playerHeight);
  24595. this.trigger('audioonlymodechange');
  24596. }
  24597. /**
  24598. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  24599. *
  24600. * Setting this to `true` will hide all player components except the control bar,
  24601. * as well as control bar components needed only for video.
  24602. *
  24603. * @param {boolean} [value]
  24604. * The value to set audioOnlyMode to.
  24605. *
  24606. * @return {Promise|boolean}
  24607. * A Promise is returned when setting the state, and a boolean when getting
  24608. * the present state
  24609. */
  24610. audioOnlyMode(value) {
  24611. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  24612. return this.audioOnlyMode_;
  24613. }
  24614. this.audioOnlyMode_ = value;
  24615. // Enable Audio Only Mode
  24616. if (value) {
  24617. const exitPromises = [];
  24618. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  24619. if (this.isInPictureInPicture()) {
  24620. exitPromises.push(this.exitPictureInPicture());
  24621. }
  24622. if (this.isFullscreen()) {
  24623. exitPromises.push(this.exitFullscreen());
  24624. }
  24625. if (this.audioPosterMode()) {
  24626. exitPromises.push(this.audioPosterMode(false));
  24627. }
  24628. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  24629. }
  24630. // Disable Audio Only Mode
  24631. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  24632. }
  24633. enablePosterModeUI_() {
  24634. // Hide the video element and show the poster image to enable posterModeUI
  24635. const tech = this.tech_ && this.tech_;
  24636. tech.hide();
  24637. this.addClass('vjs-audio-poster-mode');
  24638. this.trigger('audiopostermodechange');
  24639. }
  24640. disablePosterModeUI_() {
  24641. // Show the video element and hide the poster image to disable posterModeUI
  24642. const tech = this.tech_ && this.tech_;
  24643. tech.show();
  24644. this.removeClass('vjs-audio-poster-mode');
  24645. this.trigger('audiopostermodechange');
  24646. }
  24647. /**
  24648. * Get the current audioPosterMode state or set audioPosterMode to true or false
  24649. *
  24650. * @param {boolean} [value]
  24651. * The value to set audioPosterMode to.
  24652. *
  24653. * @return {Promise|boolean}
  24654. * A Promise is returned when setting the state, and a boolean when getting
  24655. * the present state
  24656. */
  24657. audioPosterMode(value) {
  24658. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  24659. return this.audioPosterMode_;
  24660. }
  24661. this.audioPosterMode_ = value;
  24662. if (value) {
  24663. if (this.audioOnlyMode()) {
  24664. const audioOnlyModePromise = this.audioOnlyMode(false);
  24665. return audioOnlyModePromise.then(() => {
  24666. // enable audio poster mode after audio only mode is disabled
  24667. this.enablePosterModeUI_();
  24668. });
  24669. }
  24670. return Promise.resolve().then(() => {
  24671. // enable audio poster mode
  24672. this.enablePosterModeUI_();
  24673. });
  24674. }
  24675. return Promise.resolve().then(() => {
  24676. // disable audio poster mode
  24677. this.disablePosterModeUI_();
  24678. });
  24679. }
  24680. /**
  24681. * A helper method for adding a {@link TextTrack} to our
  24682. * {@link TextTrackList}.
  24683. *
  24684. * In addition to the W3C settings we allow adding additional info through options.
  24685. *
  24686. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  24687. *
  24688. * @param {string} [kind]
  24689. * the kind of TextTrack you are adding
  24690. *
  24691. * @param {string} [label]
  24692. * the label to give the TextTrack label
  24693. *
  24694. * @param {string} [language]
  24695. * the language to set on the TextTrack
  24696. *
  24697. * @return {TextTrack|undefined}
  24698. * the TextTrack that was added or undefined
  24699. * if there is no tech
  24700. */
  24701. addTextTrack(kind, label, language) {
  24702. if (this.tech_) {
  24703. return this.tech_.addTextTrack(kind, label, language);
  24704. }
  24705. }
  24706. /**
  24707. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  24708. *
  24709. * @param {Object} options
  24710. * Options to pass to {@link HTMLTrackElement} during creation. See
  24711. * {@link HTMLTrackElement} for object properties that you should use.
  24712. *
  24713. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  24714. * from the TextTrackList and HtmlTrackElementList
  24715. * after a source change
  24716. *
  24717. * @return {HtmlTrackElement}
  24718. * the HTMLTrackElement that was created and added
  24719. * to the HtmlTrackElementList and the remote
  24720. * TextTrackList
  24721. *
  24722. */
  24723. addRemoteTextTrack(options, manualCleanup) {
  24724. if (this.tech_) {
  24725. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  24726. }
  24727. }
  24728. /**
  24729. * Remove a remote {@link TextTrack} from the respective
  24730. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  24731. *
  24732. * @param {Object} track
  24733. * Remote {@link TextTrack} to remove
  24734. *
  24735. * @return {undefined}
  24736. * does not return anything
  24737. */
  24738. removeRemoteTextTrack(obj = {}) {
  24739. let {
  24740. track
  24741. } = obj;
  24742. if (!track) {
  24743. track = obj;
  24744. }
  24745. // destructure the input into an object with a track argument, defaulting to arguments[0]
  24746. // default the whole argument to an empty object if nothing was passed in
  24747. if (this.tech_) {
  24748. return this.tech_.removeRemoteTextTrack(track);
  24749. }
  24750. }
  24751. /**
  24752. * Gets available media playback quality metrics as specified by the W3C's Media
  24753. * Playback Quality API.
  24754. *
  24755. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  24756. *
  24757. * @return {Object|undefined}
  24758. * An object with supported media playback quality metrics or undefined if there
  24759. * is no tech or the tech does not support it.
  24760. */
  24761. getVideoPlaybackQuality() {
  24762. return this.techGet_('getVideoPlaybackQuality');
  24763. }
  24764. /**
  24765. * Get video width
  24766. *
  24767. * @return {number}
  24768. * current video width
  24769. */
  24770. videoWidth() {
  24771. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  24772. }
  24773. /**
  24774. * Get video height
  24775. *
  24776. * @return {number}
  24777. * current video height
  24778. */
  24779. videoHeight() {
  24780. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  24781. }
  24782. /**
  24783. * Set or get the player's language code.
  24784. *
  24785. * Changing the language will trigger
  24786. * [languagechange]{@link Player#event:languagechange}
  24787. * which Components can use to update control text.
  24788. * ClickableComponent will update its control text by default on
  24789. * [languagechange]{@link Player#event:languagechange}.
  24790. *
  24791. * @fires Player#languagechange
  24792. *
  24793. * @param {string} [code]
  24794. * the language code to set the player to
  24795. *
  24796. * @return {string|undefined}
  24797. * - The current language code when getting
  24798. * - Nothing when setting
  24799. */
  24800. language(code) {
  24801. if (code === undefined) {
  24802. return this.language_;
  24803. }
  24804. if (this.language_ !== String(code).toLowerCase()) {
  24805. this.language_ = String(code).toLowerCase();
  24806. // during first init, it's possible some things won't be evented
  24807. if (isEvented(this)) {
  24808. /**
  24809. * fires when the player language change
  24810. *
  24811. * @event Player#languagechange
  24812. * @type {Event}
  24813. */
  24814. this.trigger('languagechange');
  24815. }
  24816. }
  24817. }
  24818. /**
  24819. * Get the player's language dictionary
  24820. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  24821. * Languages specified directly in the player options have precedence
  24822. *
  24823. * @return {Array}
  24824. * An array of of supported languages
  24825. */
  24826. languages() {
  24827. return merge(Player.prototype.options_.languages, this.languages_);
  24828. }
  24829. /**
  24830. * returns a JavaScript object representing the current track
  24831. * information. **DOES not return it as JSON**
  24832. *
  24833. * @return {Object}
  24834. * Object representing the current of track info
  24835. */
  24836. toJSON() {
  24837. const options = merge(this.options_);
  24838. const tracks = options.tracks;
  24839. options.tracks = [];
  24840. for (let i = 0; i < tracks.length; i++) {
  24841. let track = tracks[i];
  24842. // deep merge tracks and null out player so no circular references
  24843. track = merge(track);
  24844. track.player = undefined;
  24845. options.tracks[i] = track;
  24846. }
  24847. return options;
  24848. }
  24849. /**
  24850. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  24851. * component) that immediately overlays the player with arbitrary
  24852. * content and removes itself when closed.
  24853. *
  24854. * @param {string|Function|Element|Array|null} content
  24855. * Same as {@link ModalDialog#content}'s param of the same name.
  24856. * The most straight-forward usage is to provide a string or DOM
  24857. * element.
  24858. *
  24859. * @param {Object} [options]
  24860. * Extra options which will be passed on to the {@link ModalDialog}.
  24861. *
  24862. * @return {ModalDialog}
  24863. * the {@link ModalDialog} that was created
  24864. */
  24865. createModal(content, options) {
  24866. options = options || {};
  24867. options.content = content || '';
  24868. const modal = new ModalDialog(this, options);
  24869. this.addChild(modal);
  24870. modal.on('dispose', () => {
  24871. this.removeChild(modal);
  24872. });
  24873. modal.open();
  24874. return modal;
  24875. }
  24876. /**
  24877. * Change breakpoint classes when the player resizes.
  24878. *
  24879. * @private
  24880. */
  24881. updateCurrentBreakpoint_() {
  24882. if (!this.responsive()) {
  24883. return;
  24884. }
  24885. const currentBreakpoint = this.currentBreakpoint();
  24886. const currentWidth = this.currentWidth();
  24887. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  24888. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  24889. const maxWidth = this.breakpoints_[candidateBreakpoint];
  24890. if (currentWidth <= maxWidth) {
  24891. // The current breakpoint did not change, nothing to do.
  24892. if (currentBreakpoint === candidateBreakpoint) {
  24893. return;
  24894. }
  24895. // Only remove a class if there is a current breakpoint.
  24896. if (currentBreakpoint) {
  24897. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  24898. }
  24899. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  24900. this.breakpoint_ = candidateBreakpoint;
  24901. break;
  24902. }
  24903. }
  24904. }
  24905. /**
  24906. * Removes the current breakpoint.
  24907. *
  24908. * @private
  24909. */
  24910. removeCurrentBreakpoint_() {
  24911. const className = this.currentBreakpointClass();
  24912. this.breakpoint_ = '';
  24913. if (className) {
  24914. this.removeClass(className);
  24915. }
  24916. }
  24917. /**
  24918. * Get or set breakpoints on the player.
  24919. *
  24920. * Calling this method with an object or `true` will remove any previous
  24921. * custom breakpoints and start from the defaults again.
  24922. *
  24923. * @param {Object|boolean} [breakpoints]
  24924. * If an object is given, it can be used to provide custom
  24925. * breakpoints. If `true` is given, will set default breakpoints.
  24926. * If this argument is not given, will simply return the current
  24927. * breakpoints.
  24928. *
  24929. * @param {number} [breakpoints.tiny]
  24930. * The maximum width for the "vjs-layout-tiny" class.
  24931. *
  24932. * @param {number} [breakpoints.xsmall]
  24933. * The maximum width for the "vjs-layout-x-small" class.
  24934. *
  24935. * @param {number} [breakpoints.small]
  24936. * The maximum width for the "vjs-layout-small" class.
  24937. *
  24938. * @param {number} [breakpoints.medium]
  24939. * The maximum width for the "vjs-layout-medium" class.
  24940. *
  24941. * @param {number} [breakpoints.large]
  24942. * The maximum width for the "vjs-layout-large" class.
  24943. *
  24944. * @param {number} [breakpoints.xlarge]
  24945. * The maximum width for the "vjs-layout-x-large" class.
  24946. *
  24947. * @param {number} [breakpoints.huge]
  24948. * The maximum width for the "vjs-layout-huge" class.
  24949. *
  24950. * @return {Object}
  24951. * An object mapping breakpoint names to maximum width values.
  24952. */
  24953. breakpoints(breakpoints) {
  24954. // Used as a getter.
  24955. if (breakpoints === undefined) {
  24956. return Object.assign(this.breakpoints_);
  24957. }
  24958. this.breakpoint_ = '';
  24959. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  24960. // When breakpoint definitions change, we need to update the currently
  24961. // selected breakpoint.
  24962. this.updateCurrentBreakpoint_();
  24963. // Clone the breakpoints before returning.
  24964. return Object.assign(this.breakpoints_);
  24965. }
  24966. /**
  24967. * Get or set a flag indicating whether or not this player should adjust
  24968. * its UI based on its dimensions.
  24969. *
  24970. * @param {boolean} [value]
  24971. * Should be `true` if the player should adjust its UI based on its
  24972. * dimensions; otherwise, should be `false`.
  24973. *
  24974. * @return {boolean|undefined}
  24975. * Will be `true` if this player should adjust its UI based on its
  24976. * dimensions; otherwise, will be `false`.
  24977. * Nothing if setting
  24978. */
  24979. responsive(value) {
  24980. // Used as a getter.
  24981. if (value === undefined) {
  24982. return this.responsive_;
  24983. }
  24984. value = Boolean(value);
  24985. const current = this.responsive_;
  24986. // Nothing changed.
  24987. if (value === current) {
  24988. return;
  24989. }
  24990. // The value actually changed, set it.
  24991. this.responsive_ = value;
  24992. // Start listening for breakpoints and set the initial breakpoint if the
  24993. // player is now responsive.
  24994. if (value) {
  24995. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  24996. this.updateCurrentBreakpoint_();
  24997. // Stop listening for breakpoints if the player is no longer responsive.
  24998. } else {
  24999. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  25000. this.removeCurrentBreakpoint_();
  25001. }
  25002. return value;
  25003. }
  25004. /**
  25005. * Get current breakpoint name, if any.
  25006. *
  25007. * @return {string}
  25008. * If there is currently a breakpoint set, returns a the key from the
  25009. * breakpoints object matching it. Otherwise, returns an empty string.
  25010. */
  25011. currentBreakpoint() {
  25012. return this.breakpoint_;
  25013. }
  25014. /**
  25015. * Get the current breakpoint class name.
  25016. *
  25017. * @return {string}
  25018. * The matching class name (e.g. `"vjs-layout-tiny"` or
  25019. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  25020. * there is no current breakpoint.
  25021. */
  25022. currentBreakpointClass() {
  25023. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  25024. }
  25025. /**
  25026. * An object that describes a single piece of media.
  25027. *
  25028. * Properties that are not part of this type description will be retained; so,
  25029. * this can be viewed as a generic metadata storage mechanism as well.
  25030. *
  25031. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  25032. * @typedef {Object} Player~MediaObject
  25033. *
  25034. * @property {string} [album]
  25035. * Unused, except if this object is passed to the `MediaSession`
  25036. * API.
  25037. *
  25038. * @property {string} [artist]
  25039. * Unused, except if this object is passed to the `MediaSession`
  25040. * API.
  25041. *
  25042. * @property {Object[]} [artwork]
  25043. * Unused, except if this object is passed to the `MediaSession`
  25044. * API. If not specified, will be populated via the `poster`, if
  25045. * available.
  25046. *
  25047. * @property {string} [poster]
  25048. * URL to an image that will display before playback.
  25049. *
  25050. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  25051. * A single source object, an array of source objects, or a string
  25052. * referencing a URL to a media source. It is _highly recommended_
  25053. * that an object or array of objects is used here, so that source
  25054. * selection algorithms can take the `type` into account.
  25055. *
  25056. * @property {string} [title]
  25057. * Unused, except if this object is passed to the `MediaSession`
  25058. * API.
  25059. *
  25060. * @property {Object[]} [textTracks]
  25061. * An array of objects to be used to create text tracks, following
  25062. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  25063. * For ease of removal, these will be created as "remote" text
  25064. * tracks and set to automatically clean up on source changes.
  25065. *
  25066. * These objects may have properties like `src`, `kind`, `label`,
  25067. * and `language`, see {@link Tech#createRemoteTextTrack}.
  25068. */
  25069. /**
  25070. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  25071. *
  25072. * @param {Player~MediaObject} media
  25073. * A media object.
  25074. *
  25075. * @param {Function} ready
  25076. * A callback to be called when the player is ready.
  25077. */
  25078. loadMedia(media, ready) {
  25079. if (!media || typeof media !== 'object') {
  25080. return;
  25081. }
  25082. const crossOrigin = this.crossOrigin();
  25083. this.reset();
  25084. // Clone the media object so it cannot be mutated from outside.
  25085. this.cache_.media = merge(media);
  25086. const {
  25087. artist,
  25088. artwork,
  25089. description,
  25090. poster,
  25091. src,
  25092. textTracks,
  25093. title
  25094. } = this.cache_.media;
  25095. // If `artwork` is not given, create it using `poster`.
  25096. if (!artwork && poster) {
  25097. this.cache_.media.artwork = [{
  25098. src: poster,
  25099. type: getMimetype(poster)
  25100. }];
  25101. }
  25102. if (crossOrigin) {
  25103. this.crossOrigin(crossOrigin);
  25104. }
  25105. if (src) {
  25106. this.src(src);
  25107. }
  25108. if (poster) {
  25109. this.poster(poster);
  25110. }
  25111. if (Array.isArray(textTracks)) {
  25112. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  25113. }
  25114. if (this.titleBar) {
  25115. this.titleBar.update({
  25116. title,
  25117. description: description || artist || ''
  25118. });
  25119. }
  25120. this.ready(ready);
  25121. }
  25122. /**
  25123. * Get a clone of the current {@link Player~MediaObject} for this player.
  25124. *
  25125. * If the `loadMedia` method has not been used, will attempt to return a
  25126. * {@link Player~MediaObject} based on the current state of the player.
  25127. *
  25128. * @return {Player~MediaObject}
  25129. */
  25130. getMedia() {
  25131. if (!this.cache_.media) {
  25132. const poster = this.poster();
  25133. const src = this.currentSources();
  25134. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  25135. kind: tt.kind,
  25136. label: tt.label,
  25137. language: tt.language,
  25138. src: tt.src
  25139. }));
  25140. const media = {
  25141. src,
  25142. textTracks
  25143. };
  25144. if (poster) {
  25145. media.poster = poster;
  25146. media.artwork = [{
  25147. src: media.poster,
  25148. type: getMimetype(media.poster)
  25149. }];
  25150. }
  25151. return media;
  25152. }
  25153. return merge(this.cache_.media);
  25154. }
  25155. /**
  25156. * Gets tag settings
  25157. *
  25158. * @param {Element} tag
  25159. * The player tag
  25160. *
  25161. * @return {Object}
  25162. * An object containing all of the settings
  25163. * for a player tag
  25164. */
  25165. static getTagSettings(tag) {
  25166. const baseOptions = {
  25167. sources: [],
  25168. tracks: []
  25169. };
  25170. const tagOptions = getAttributes(tag);
  25171. const dataSetup = tagOptions['data-setup'];
  25172. if (hasClass(tag, 'vjs-fill')) {
  25173. tagOptions.fill = true;
  25174. }
  25175. if (hasClass(tag, 'vjs-fluid')) {
  25176. tagOptions.fluid = true;
  25177. }
  25178. // Check if data-setup attr exists.
  25179. if (dataSetup !== null) {
  25180. // Parse options JSON
  25181. try {
  25182. // If empty string, make it a parsable json object.
  25183. Object.assign(tagOptions, JSON.parse(dataSetup || '{}'));
  25184. } catch (e) {
  25185. log.error('data-setup', e);
  25186. }
  25187. }
  25188. Object.assign(baseOptions, tagOptions);
  25189. // Get tag children settings
  25190. if (tag.hasChildNodes()) {
  25191. const children = tag.childNodes;
  25192. for (let i = 0, j = children.length; i < j; i++) {
  25193. const child = children[i];
  25194. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  25195. const childName = child.nodeName.toLowerCase();
  25196. if (childName === 'source') {
  25197. baseOptions.sources.push(getAttributes(child));
  25198. } else if (childName === 'track') {
  25199. baseOptions.tracks.push(getAttributes(child));
  25200. }
  25201. }
  25202. }
  25203. return baseOptions;
  25204. }
  25205. /**
  25206. * Set debug mode to enable/disable logs at info level.
  25207. *
  25208. * @param {boolean} enabled
  25209. * @fires Player#debugon
  25210. * @fires Player#debugoff
  25211. * @return {boolean|undefined}
  25212. */
  25213. debug(enabled) {
  25214. if (enabled === undefined) {
  25215. return this.debugEnabled_;
  25216. }
  25217. if (enabled) {
  25218. this.trigger('debugon');
  25219. this.previousLogLevel_ = this.log.level;
  25220. this.log.level('debug');
  25221. this.debugEnabled_ = true;
  25222. } else {
  25223. this.trigger('debugoff');
  25224. this.log.level(this.previousLogLevel_);
  25225. this.previousLogLevel_ = undefined;
  25226. this.debugEnabled_ = false;
  25227. }
  25228. }
  25229. /**
  25230. * Set or get current playback rates.
  25231. * Takes an array and updates the playback rates menu with the new items.
  25232. * Pass in an empty array to hide the menu.
  25233. * Values other than arrays are ignored.
  25234. *
  25235. * @fires Player#playbackrateschange
  25236. * @param {number[]} [newRates]
  25237. * The new rates that the playback rates menu should update to.
  25238. * An empty array will hide the menu
  25239. * @return {number[]} When used as a getter will return the current playback rates
  25240. */
  25241. playbackRates(newRates) {
  25242. if (newRates === undefined) {
  25243. return this.cache_.playbackRates;
  25244. }
  25245. // ignore any value that isn't an array
  25246. if (!Array.isArray(newRates)) {
  25247. return;
  25248. }
  25249. // ignore any arrays that don't only contain numbers
  25250. if (!newRates.every(rate => typeof rate === 'number')) {
  25251. return;
  25252. }
  25253. this.cache_.playbackRates = newRates;
  25254. /**
  25255. * fires when the playback rates in a player are changed
  25256. *
  25257. * @event Player#playbackrateschange
  25258. * @type {Event}
  25259. */
  25260. this.trigger('playbackrateschange');
  25261. }
  25262. /**
  25263. * Reports whether or not a player has a plugin available.
  25264. *
  25265. * This does not report whether or not the plugin has ever been initialized
  25266. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  25267. *
  25268. * @method hasPlugin
  25269. * @param {string} name
  25270. * The name of a plugin.
  25271. *
  25272. * @return {boolean}
  25273. * Whether or not this player has the requested plugin available.
  25274. */
  25275. /**
  25276. * Reports whether or not a player is using a plugin by name.
  25277. *
  25278. * For basic plugins, this only reports whether the plugin has _ever_ been
  25279. * initialized on this player.
  25280. *
  25281. * @method Player#usingPlugin
  25282. * @param {string} name
  25283. * The name of a plugin.
  25284. *
  25285. * @return {boolean}
  25286. * Whether or not this player is using the requested plugin.
  25287. */
  25288. }
  25289. /**
  25290. * Get the {@link VideoTrackList}
  25291. *
  25292. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  25293. *
  25294. * @return {VideoTrackList}
  25295. * the current video track list
  25296. *
  25297. * @method Player.prototype.videoTracks
  25298. */
  25299. /**
  25300. * Get the {@link AudioTrackList}
  25301. *
  25302. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  25303. *
  25304. * @return {AudioTrackList}
  25305. * the current audio track list
  25306. *
  25307. * @method Player.prototype.audioTracks
  25308. */
  25309. /**
  25310. * Get the {@link TextTrackList}
  25311. *
  25312. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  25313. *
  25314. * @return {TextTrackList}
  25315. * the current text track list
  25316. *
  25317. * @method Player.prototype.textTracks
  25318. */
  25319. /**
  25320. * Get the remote {@link TextTrackList}
  25321. *
  25322. * @return {TextTrackList}
  25323. * The current remote text track list
  25324. *
  25325. * @method Player.prototype.remoteTextTracks
  25326. */
  25327. /**
  25328. * Get the remote {@link HtmlTrackElementList} tracks.
  25329. *
  25330. * @return {HtmlTrackElementList}
  25331. * The current remote text track element list
  25332. *
  25333. * @method Player.prototype.remoteTextTrackEls
  25334. */
  25335. ALL.names.forEach(function (name) {
  25336. const props = ALL[name];
  25337. Player.prototype[props.getterName] = function () {
  25338. if (this.tech_) {
  25339. return this.tech_[props.getterName]();
  25340. }
  25341. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  25342. // these will be passed to the tech during loading
  25343. this[props.privateName] = this[props.privateName] || new props.ListClass();
  25344. return this[props.privateName];
  25345. };
  25346. });
  25347. /**
  25348. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  25349. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  25350. * behavior.
  25351. *
  25352. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  25353. *
  25354. * @param {string} [value]
  25355. * The value to set the `Player`'s crossorigin to. If an argument is
  25356. * given, must be one of `anonymous` or `use-credentials`.
  25357. *
  25358. * @return {string|undefined}
  25359. * - The current crossorigin value of the `Player` when getting.
  25360. * - undefined when setting
  25361. */
  25362. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  25363. /**
  25364. * Global enumeration of players.
  25365. *
  25366. * The keys are the player IDs and the values are either the {@link Player}
  25367. * instance or `null` for disposed players.
  25368. *
  25369. * @type {Object}
  25370. */
  25371. Player.players = {};
  25372. const navigator = window.navigator;
  25373. /*
  25374. * Player instance options, surfaced using options
  25375. * options = Player.prototype.options_
  25376. * Make changes in options, not here.
  25377. *
  25378. * @type {Object}
  25379. * @private
  25380. */
  25381. Player.prototype.options_ = {
  25382. // Default order of fallback technology
  25383. techOrder: Tech.defaultTechOrder_,
  25384. html5: {},
  25385. // enable sourceset by default
  25386. enableSourceset: true,
  25387. // default inactivity timeout
  25388. inactivityTimeout: 2000,
  25389. // default playback rates
  25390. playbackRates: [],
  25391. // Add playback rate selection by adding rates
  25392. // 'playbackRates': [0.5, 1, 1.5, 2],
  25393. liveui: false,
  25394. // Included control sets
  25395. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  25396. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  25397. // locales and their language translations
  25398. languages: {},
  25399. // Default message to show when a video cannot be played.
  25400. notSupportedMessage: 'No compatible source was found for this media.',
  25401. normalizeAutoplay: false,
  25402. fullscreen: {
  25403. options: {
  25404. navigationUI: 'hide'
  25405. }
  25406. },
  25407. breakpoints: {},
  25408. responsive: false,
  25409. audioOnlyMode: false,
  25410. audioPosterMode: false,
  25411. spatialNavigation: {
  25412. enabled: false,
  25413. horizontalSeek: false
  25414. },
  25415. // Default smooth seeking to false
  25416. enableSmoothSeeking: false,
  25417. disableSeekWhileScrubbingOnMobile: false
  25418. };
  25419. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  25420. Player.prototype[`handleTech${toTitleCase(event)}_`] = function () {
  25421. return this.trigger(event);
  25422. };
  25423. });
  25424. /**
  25425. * Fired when the player has initial duration and dimension information
  25426. *
  25427. * @event Player#loadedmetadata
  25428. * @type {Event}
  25429. */
  25430. /**
  25431. * Fired when the player has downloaded data at the current playback position
  25432. *
  25433. * @event Player#loadeddata
  25434. * @type {Event}
  25435. */
  25436. /**
  25437. * Fired when the current playback position has changed *
  25438. * During playback this is fired every 15-250 milliseconds, depending on the
  25439. * playback technology in use.
  25440. *
  25441. * @event Player#timeupdate
  25442. * @type {Event}
  25443. */
  25444. /**
  25445. * Fired when the volume changes
  25446. *
  25447. * @event Player#volumechange
  25448. * @type {Event}
  25449. */
  25450. Component.registerComponent('Player', Player);
  25451. /**
  25452. * @file plugin.js
  25453. */
  25454. /**
  25455. * The base plugin name.
  25456. *
  25457. * @private
  25458. * @constant
  25459. * @type {string}
  25460. */
  25461. const BASE_PLUGIN_NAME = 'plugin';
  25462. /**
  25463. * The key on which a player's active plugins cache is stored.
  25464. *
  25465. * @private
  25466. * @constant
  25467. * @type {string}
  25468. */
  25469. const PLUGIN_CACHE_KEY = 'activePlugins_';
  25470. /**
  25471. * Stores registered plugins in a private space.
  25472. *
  25473. * @private
  25474. * @type {Object}
  25475. */
  25476. const pluginStorage = {};
  25477. /**
  25478. * Reports whether or not a plugin has been registered.
  25479. *
  25480. * @private
  25481. * @param {string} name
  25482. * The name of a plugin.
  25483. *
  25484. * @return {boolean}
  25485. * Whether or not the plugin has been registered.
  25486. */
  25487. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  25488. /**
  25489. * Get a single registered plugin by name.
  25490. *
  25491. * @private
  25492. * @param {string} name
  25493. * The name of a plugin.
  25494. *
  25495. * @return {typeof Plugin|Function|undefined}
  25496. * The plugin (or undefined).
  25497. */
  25498. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  25499. /**
  25500. * Marks a plugin as "active" on a player.
  25501. *
  25502. * Also, ensures that the player has an object for tracking active plugins.
  25503. *
  25504. * @private
  25505. * @param {Player} player
  25506. * A Video.js player instance.
  25507. *
  25508. * @param {string} name
  25509. * The name of a plugin.
  25510. */
  25511. const markPluginAsActive = (player, name) => {
  25512. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  25513. player[PLUGIN_CACHE_KEY][name] = true;
  25514. };
  25515. /**
  25516. * Triggers a pair of plugin setup events.
  25517. *
  25518. * @private
  25519. * @param {Player} player
  25520. * A Video.js player instance.
  25521. *
  25522. * @param {PluginEventHash} hash
  25523. * A plugin event hash.
  25524. *
  25525. * @param {boolean} [before]
  25526. * If true, prefixes the event name with "before". In other words,
  25527. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  25528. */
  25529. const triggerSetupEvent = (player, hash, before) => {
  25530. const eventName = (before ? 'before' : '') + 'pluginsetup';
  25531. player.trigger(eventName, hash);
  25532. player.trigger(eventName + ':' + hash.name, hash);
  25533. };
  25534. /**
  25535. * Takes a basic plugin function and returns a wrapper function which marks
  25536. * on the player that the plugin has been activated.
  25537. *
  25538. * @private
  25539. * @param {string} name
  25540. * The name of the plugin.
  25541. *
  25542. * @param {Function} plugin
  25543. * The basic plugin.
  25544. *
  25545. * @return {Function}
  25546. * A wrapper function for the given plugin.
  25547. */
  25548. const createBasicPlugin = function (name, plugin) {
  25549. const basicPluginWrapper = function () {
  25550. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  25551. // regardless, but we want the hash to be consistent with the hash provided
  25552. // for advanced plugins.
  25553. //
  25554. // The only potentially counter-intuitive thing here is the `instance` in
  25555. // the "pluginsetup" event is the value returned by the `plugin` function.
  25556. triggerSetupEvent(this, {
  25557. name,
  25558. plugin,
  25559. instance: null
  25560. }, true);
  25561. const instance = plugin.apply(this, arguments);
  25562. markPluginAsActive(this, name);
  25563. triggerSetupEvent(this, {
  25564. name,
  25565. plugin,
  25566. instance
  25567. });
  25568. return instance;
  25569. };
  25570. Object.keys(plugin).forEach(function (prop) {
  25571. basicPluginWrapper[prop] = plugin[prop];
  25572. });
  25573. return basicPluginWrapper;
  25574. };
  25575. /**
  25576. * Takes a plugin sub-class and returns a factory function for generating
  25577. * instances of it.
  25578. *
  25579. * This factory function will replace itself with an instance of the requested
  25580. * sub-class of Plugin.
  25581. *
  25582. * @private
  25583. * @param {string} name
  25584. * The name of the plugin.
  25585. *
  25586. * @param {Plugin} PluginSubClass
  25587. * The advanced plugin.
  25588. *
  25589. * @return {Function}
  25590. */
  25591. const createPluginFactory = (name, PluginSubClass) => {
  25592. // Add a `name` property to the plugin prototype so that each plugin can
  25593. // refer to itself by name.
  25594. PluginSubClass.prototype.name = name;
  25595. return function (...args) {
  25596. triggerSetupEvent(this, {
  25597. name,
  25598. plugin: PluginSubClass,
  25599. instance: null
  25600. }, true);
  25601. const instance = new PluginSubClass(...[this, ...args]);
  25602. // The plugin is replaced by a function that returns the current instance.
  25603. this[name] = () => instance;
  25604. triggerSetupEvent(this, instance.getEventHash());
  25605. return instance;
  25606. };
  25607. };
  25608. /**
  25609. * Parent class for all advanced plugins.
  25610. *
  25611. * @mixes module:evented~EventedMixin
  25612. * @mixes module:stateful~StatefulMixin
  25613. * @fires Player#beforepluginsetup
  25614. * @fires Player#beforepluginsetup:$name
  25615. * @fires Player#pluginsetup
  25616. * @fires Player#pluginsetup:$name
  25617. * @listens Player#dispose
  25618. * @throws {Error}
  25619. * If attempting to instantiate the base {@link Plugin} class
  25620. * directly instead of via a sub-class.
  25621. */
  25622. class Plugin {
  25623. /**
  25624. * Creates an instance of this class.
  25625. *
  25626. * Sub-classes should call `super` to ensure plugins are properly initialized.
  25627. *
  25628. * @param {Player} player
  25629. * A Video.js player instance.
  25630. */
  25631. constructor(player) {
  25632. if (this.constructor === Plugin) {
  25633. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  25634. }
  25635. this.player = player;
  25636. if (!this.log) {
  25637. this.log = this.player.log.createLogger(this.name);
  25638. }
  25639. // Make this object evented, but remove the added `trigger` method so we
  25640. // use the prototype version instead.
  25641. evented(this);
  25642. delete this.trigger;
  25643. stateful(this, this.constructor.defaultState);
  25644. markPluginAsActive(player, this.name);
  25645. // Auto-bind the dispose method so we can use it as a listener and unbind
  25646. // it later easily.
  25647. this.dispose = this.dispose.bind(this);
  25648. // If the player is disposed, dispose the plugin.
  25649. player.on('dispose', this.dispose);
  25650. }
  25651. /**
  25652. * Get the version of the plugin that was set on <pluginName>.VERSION
  25653. */
  25654. version() {
  25655. return this.constructor.VERSION;
  25656. }
  25657. /**
  25658. * Each event triggered by plugins includes a hash of additional data with
  25659. * conventional properties.
  25660. *
  25661. * This returns that object or mutates an existing hash.
  25662. *
  25663. * @param {Object} [hash={}]
  25664. * An object to be used as event an event hash.
  25665. *
  25666. * @return {PluginEventHash}
  25667. * An event hash object with provided properties mixed-in.
  25668. */
  25669. getEventHash(hash = {}) {
  25670. hash.name = this.name;
  25671. hash.plugin = this.constructor;
  25672. hash.instance = this;
  25673. return hash;
  25674. }
  25675. /**
  25676. * Triggers an event on the plugin object and overrides
  25677. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  25678. *
  25679. * @param {string|Object} event
  25680. * An event type or an object with a type property.
  25681. *
  25682. * @param {Object} [hash={}]
  25683. * Additional data hash to merge with a
  25684. * {@link PluginEventHash|PluginEventHash}.
  25685. *
  25686. * @return {boolean}
  25687. * Whether or not default was prevented.
  25688. */
  25689. trigger(event, hash = {}) {
  25690. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  25691. }
  25692. /**
  25693. * Handles "statechanged" events on the plugin. No-op by default, override by
  25694. * subclassing.
  25695. *
  25696. * @abstract
  25697. * @param {Event} e
  25698. * An event object provided by a "statechanged" event.
  25699. *
  25700. * @param {Object} e.changes
  25701. * An object describing changes that occurred with the "statechanged"
  25702. * event.
  25703. */
  25704. handleStateChanged(e) {}
  25705. /**
  25706. * Disposes a plugin.
  25707. *
  25708. * Subclasses can override this if they want, but for the sake of safety,
  25709. * it's probably best to subscribe the "dispose" event.
  25710. *
  25711. * @fires Plugin#dispose
  25712. */
  25713. dispose() {
  25714. const {
  25715. name,
  25716. player
  25717. } = this;
  25718. /**
  25719. * Signals that a advanced plugin is about to be disposed.
  25720. *
  25721. * @event Plugin#dispose
  25722. * @type {Event}
  25723. */
  25724. this.trigger('dispose');
  25725. this.off();
  25726. player.off('dispose', this.dispose);
  25727. // Eliminate any possible sources of leaking memory by clearing up
  25728. // references between the player and the plugin instance and nulling out
  25729. // the plugin's state and replacing methods with a function that throws.
  25730. player[PLUGIN_CACHE_KEY][name] = false;
  25731. this.player = this.state = null;
  25732. // Finally, replace the plugin name on the player with a new factory
  25733. // function, so that the plugin is ready to be set up again.
  25734. player[name] = createPluginFactory(name, pluginStorage[name]);
  25735. }
  25736. /**
  25737. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  25738. *
  25739. * @param {string|Function} plugin
  25740. * If a string, matches the name of a plugin. If a function, will be
  25741. * tested directly.
  25742. *
  25743. * @return {boolean}
  25744. * Whether or not a plugin is a basic plugin.
  25745. */
  25746. static isBasic(plugin) {
  25747. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  25748. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  25749. }
  25750. /**
  25751. * Register a Video.js plugin.
  25752. *
  25753. * @param {string} name
  25754. * The name of the plugin to be registered. Must be a string and
  25755. * must not match an existing plugin or a method on the `Player`
  25756. * prototype.
  25757. *
  25758. * @param {typeof Plugin|Function} plugin
  25759. * A sub-class of `Plugin` or a function for basic plugins.
  25760. *
  25761. * @return {typeof Plugin|Function}
  25762. * For advanced plugins, a factory function for that plugin. For
  25763. * basic plugins, a wrapper function that initializes the plugin.
  25764. */
  25765. static registerPlugin(name, plugin) {
  25766. if (typeof name !== 'string') {
  25767. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  25768. }
  25769. if (pluginExists(name)) {
  25770. log.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  25771. } else if (Player.prototype.hasOwnProperty(name)) {
  25772. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  25773. }
  25774. if (typeof plugin !== 'function') {
  25775. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  25776. }
  25777. pluginStorage[name] = plugin;
  25778. // Add a player prototype method for all sub-classed plugins (but not for
  25779. // the base Plugin class).
  25780. if (name !== BASE_PLUGIN_NAME) {
  25781. if (Plugin.isBasic(plugin)) {
  25782. Player.prototype[name] = createBasicPlugin(name, plugin);
  25783. } else {
  25784. Player.prototype[name] = createPluginFactory(name, plugin);
  25785. }
  25786. }
  25787. return plugin;
  25788. }
  25789. /**
  25790. * De-register a Video.js plugin.
  25791. *
  25792. * @param {string} name
  25793. * The name of the plugin to be de-registered. Must be a string that
  25794. * matches an existing plugin.
  25795. *
  25796. * @throws {Error}
  25797. * If an attempt is made to de-register the base plugin.
  25798. */
  25799. static deregisterPlugin(name) {
  25800. if (name === BASE_PLUGIN_NAME) {
  25801. throw new Error('Cannot de-register base plugin.');
  25802. }
  25803. if (pluginExists(name)) {
  25804. delete pluginStorage[name];
  25805. delete Player.prototype[name];
  25806. }
  25807. }
  25808. /**
  25809. * Gets an object containing multiple Video.js plugins.
  25810. *
  25811. * @param {Array} [names]
  25812. * If provided, should be an array of plugin names. Defaults to _all_
  25813. * plugin names.
  25814. *
  25815. * @return {Object|undefined}
  25816. * An object containing plugin(s) associated with their name(s) or
  25817. * `undefined` if no matching plugins exist).
  25818. */
  25819. static getPlugins(names = Object.keys(pluginStorage)) {
  25820. let result;
  25821. names.forEach(name => {
  25822. const plugin = getPlugin(name);
  25823. if (plugin) {
  25824. result = result || {};
  25825. result[name] = plugin;
  25826. }
  25827. });
  25828. return result;
  25829. }
  25830. /**
  25831. * Gets a plugin's version, if available
  25832. *
  25833. * @param {string} name
  25834. * The name of a plugin.
  25835. *
  25836. * @return {string}
  25837. * The plugin's version or an empty string.
  25838. */
  25839. static getPluginVersion(name) {
  25840. const plugin = getPlugin(name);
  25841. return plugin && plugin.VERSION || '';
  25842. }
  25843. }
  25844. /**
  25845. * Gets a plugin by name if it exists.
  25846. *
  25847. * @static
  25848. * @method getPlugin
  25849. * @memberOf Plugin
  25850. * @param {string} name
  25851. * The name of a plugin.
  25852. *
  25853. * @returns {typeof Plugin|Function|undefined}
  25854. * The plugin (or `undefined`).
  25855. */
  25856. Plugin.getPlugin = getPlugin;
  25857. /**
  25858. * The name of the base plugin class as it is registered.
  25859. *
  25860. * @type {string}
  25861. */
  25862. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  25863. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  25864. /**
  25865. * Documented in player.js
  25866. *
  25867. * @ignore
  25868. */
  25869. Player.prototype.usingPlugin = function (name) {
  25870. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  25871. };
  25872. /**
  25873. * Documented in player.js
  25874. *
  25875. * @ignore
  25876. */
  25877. Player.prototype.hasPlugin = function (name) {
  25878. return !!pluginExists(name);
  25879. };
  25880. /**
  25881. * Signals that a plugin is about to be set up on a player.
  25882. *
  25883. * @event Player#beforepluginsetup
  25884. * @type {PluginEventHash}
  25885. */
  25886. /**
  25887. * Signals that a plugin is about to be set up on a player - by name. The name
  25888. * is the name of the plugin.
  25889. *
  25890. * @event Player#beforepluginsetup:$name
  25891. * @type {PluginEventHash}
  25892. */
  25893. /**
  25894. * Signals that a plugin has just been set up on a player.
  25895. *
  25896. * @event Player#pluginsetup
  25897. * @type {PluginEventHash}
  25898. */
  25899. /**
  25900. * Signals that a plugin has just been set up on a player - by name. The name
  25901. * is the name of the plugin.
  25902. *
  25903. * @event Player#pluginsetup:$name
  25904. * @type {PluginEventHash}
  25905. */
  25906. /**
  25907. * @typedef {Object} PluginEventHash
  25908. *
  25909. * @property {string} instance
  25910. * For basic plugins, the return value of the plugin function. For
  25911. * advanced plugins, the plugin instance on which the event is fired.
  25912. *
  25913. * @property {string} name
  25914. * The name of the plugin.
  25915. *
  25916. * @property {string} plugin
  25917. * For basic plugins, the plugin function. For advanced plugins, the
  25918. * plugin class/constructor.
  25919. */
  25920. /**
  25921. * @file deprecate.js
  25922. * @module deprecate
  25923. */
  25924. /**
  25925. * Decorate a function with a deprecation message the first time it is called.
  25926. *
  25927. * @param {string} message
  25928. * A deprecation message to log the first time the returned function
  25929. * is called.
  25930. *
  25931. * @param {Function} fn
  25932. * The function to be deprecated.
  25933. *
  25934. * @return {Function}
  25935. * A wrapper function that will log a deprecation warning the first
  25936. * time it is called. The return value will be the return value of
  25937. * the wrapped function.
  25938. */
  25939. function deprecate(message, fn) {
  25940. let warned = false;
  25941. return function (...args) {
  25942. if (!warned) {
  25943. log.warn(message);
  25944. }
  25945. warned = true;
  25946. return fn.apply(this, args);
  25947. };
  25948. }
  25949. /**
  25950. * Internal function used to mark a function as deprecated in the next major
  25951. * version with consistent messaging.
  25952. *
  25953. * @param {number} major The major version where it will be removed
  25954. * @param {string} oldName The old function name
  25955. * @param {string} newName The new function name
  25956. * @param {Function} fn The function to deprecate
  25957. * @return {Function} The decorated function
  25958. */
  25959. function deprecateForMajor(major, oldName, newName, fn) {
  25960. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  25961. }
  25962. var VjsErrors = {
  25963. NetworkBadStatus: 'networkbadstatus',
  25964. NetworkRequestFailed: 'networkrequestfailed',
  25965. NetworkRequestAborted: 'networkrequestaborted',
  25966. NetworkRequestTimeout: 'networkrequesttimeout',
  25967. NetworkBodyParserFailed: 'networkbodyparserfailed',
  25968. StreamingHlsPlaylistParserError: 'streaminghlsplaylistparsererror',
  25969. StreamingDashManifestParserError: 'streamingdashmanifestparsererror',
  25970. StreamingContentSteeringParserError: 'streamingcontentsteeringparsererror',
  25971. StreamingVttParserError: 'streamingvttparsererror',
  25972. StreamingFailedToSelectNextSegment: 'streamingfailedtoselectnextsegment',
  25973. StreamingFailedToDecryptSegment: 'streamingfailedtodecryptsegment',
  25974. StreamingFailedToTransmuxSegment: 'streamingfailedtotransmuxsegment',
  25975. StreamingFailedToAppendSegment: 'streamingfailedtoappendsegment',
  25976. StreamingCodecsChangeError: 'streamingcodecschangeerror'
  25977. };
  25978. /**
  25979. * @file video.js
  25980. * @module videojs
  25981. */
  25982. /** @import { PlayerReadyCallback } from './player' */
  25983. /**
  25984. * Normalize an `id` value by trimming off a leading `#`
  25985. *
  25986. * @private
  25987. * @param {string} id
  25988. * A string, maybe with a leading `#`.
  25989. *
  25990. * @return {string}
  25991. * The string, without any leading `#`.
  25992. */
  25993. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  25994. /**
  25995. * The `videojs()` function doubles as the main function for users to create a
  25996. * {@link Player} instance as well as the main library namespace.
  25997. *
  25998. * It can also be used as a getter for a pre-existing {@link Player} instance.
  25999. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  26000. * purpose because it avoids any potential for unintended initialization.
  26001. *
  26002. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  26003. * of our JSDoc template, we cannot properly document this as both a function
  26004. * and a namespace, so its function signature is documented here.
  26005. *
  26006. * #### Arguments
  26007. * ##### id
  26008. * string|Element, **required**
  26009. *
  26010. * Video element or video element ID.
  26011. *
  26012. * ##### options
  26013. * Object, optional
  26014. *
  26015. * Options object for providing settings.
  26016. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  26017. *
  26018. * ##### ready
  26019. * {@link Component~ReadyCallback}, optional
  26020. *
  26021. * A function to be called when the {@link Player} and {@link Tech} are ready.
  26022. *
  26023. * #### Return Value
  26024. *
  26025. * The `videojs()` function returns a {@link Player} instance.
  26026. *
  26027. * @namespace
  26028. *
  26029. * @borrows AudioTrack as AudioTrack
  26030. * @borrows Component.getComponent as getComponent
  26031. * @borrows module:events.on as on
  26032. * @borrows module:events.one as one
  26033. * @borrows module:events.off as off
  26034. * @borrows module:events.trigger as trigger
  26035. * @borrows EventTarget as EventTarget
  26036. * @borrows module:middleware.use as use
  26037. * @borrows Player.players as players
  26038. * @borrows Plugin.registerPlugin as registerPlugin
  26039. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  26040. * @borrows Plugin.getPlugins as getPlugins
  26041. * @borrows Plugin.getPlugin as getPlugin
  26042. * @borrows Plugin.getPluginVersion as getPluginVersion
  26043. * @borrows Tech.getTech as getTech
  26044. * @borrows Tech.registerTech as registerTech
  26045. * @borrows TextTrack as TextTrack
  26046. * @borrows VideoTrack as VideoTrack
  26047. *
  26048. * @param {string|Element} id
  26049. * Video element or video element ID.
  26050. *
  26051. * @param {Object} [options]
  26052. * Options object for providing settings.
  26053. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  26054. *
  26055. * @param {PlayerReadyCallback} [ready]
  26056. * A function to be called when the {@link Player} and {@link Tech} are
  26057. * ready.
  26058. *
  26059. * @return {Player}
  26060. * The `videojs()` function returns a {@link Player|Player} instance.
  26061. */
  26062. function videojs(id, options, ready) {
  26063. let player = videojs.getPlayer(id);
  26064. if (player) {
  26065. if (options) {
  26066. log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  26067. }
  26068. if (ready) {
  26069. player.ready(ready);
  26070. }
  26071. return player;
  26072. }
  26073. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  26074. if (!isEl(el)) {
  26075. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  26076. }
  26077. // document.body.contains(el) will only check if el is contained within that one document.
  26078. // This causes problems for elements in iframes.
  26079. // Instead, use the element's ownerDocument instead of the global document.
  26080. // This will make sure that the element is indeed in the dom of that document.
  26081. // Additionally, check that the document in question has a default view.
  26082. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  26083. // If element is inside Shadow DOM (e.g. is part of a Custom element), ownerDocument.body
  26084. // always returns false. Instead, use the Shadow DOM root.
  26085. const inShadowDom = 'getRootNode' in el ? el.getRootNode() instanceof window.ShadowRoot : false;
  26086. const rootNode = inShadowDom ? el.getRootNode() : el.ownerDocument.body;
  26087. if (!el.ownerDocument.defaultView || !rootNode.contains(el)) {
  26088. log.warn('The element supplied is not included in the DOM');
  26089. }
  26090. options = options || {};
  26091. // Store a copy of the el before modification, if it is to be restored in destroy()
  26092. // If div ingest, store the parent div
  26093. if (options.restoreEl === true) {
  26094. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  26095. }
  26096. hooks('beforesetup').forEach(hookFunction => {
  26097. const opts = hookFunction(el, merge(options));
  26098. if (!isObject(opts) || Array.isArray(opts)) {
  26099. log.error('please return an object in beforesetup hooks');
  26100. return;
  26101. }
  26102. options = merge(options, opts);
  26103. });
  26104. // We get the current "Player" component here in case an integration has
  26105. // replaced it with a custom player.
  26106. const PlayerComponent = Component.getComponent('Player');
  26107. player = new PlayerComponent(el, options, ready);
  26108. hooks('setup').forEach(hookFunction => hookFunction(player));
  26109. return player;
  26110. }
  26111. videojs.hooks_ = hooks_;
  26112. videojs.hooks = hooks;
  26113. videojs.hook = hook;
  26114. videojs.hookOnce = hookOnce;
  26115. videojs.removeHook = removeHook;
  26116. // Add default styles
  26117. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  26118. let style = $('.vjs-styles-defaults');
  26119. if (!style) {
  26120. style = createStyleElement('vjs-styles-defaults');
  26121. const head = $('head');
  26122. if (head) {
  26123. head.insertBefore(style, head.firstChild);
  26124. }
  26125. setTextContent(style, `
  26126. .video-js {
  26127. width: 300px;
  26128. height: 150px;
  26129. }
  26130. .vjs-fluid:not(.vjs-audio-only-mode) {
  26131. padding-top: 56.25%
  26132. }
  26133. `);
  26134. }
  26135. }
  26136. // Run Auto-load players
  26137. // You have to wait at least once in case this script is loaded after your
  26138. // video in the DOM (weird behavior only with minified version)
  26139. autoSetupTimeout(1, videojs);
  26140. /**
  26141. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  26142. *
  26143. * @type {string}
  26144. */
  26145. videojs.VERSION = version;
  26146. /**
  26147. * The global options object. These are the settings that take effect
  26148. * if no overrides are specified when the player is created.
  26149. *
  26150. * @type {Object}
  26151. */
  26152. videojs.options = Player.prototype.options_;
  26153. /**
  26154. * Get an object with the currently created players, keyed by player ID
  26155. *
  26156. * @return {Object}
  26157. * The created players
  26158. */
  26159. videojs.getPlayers = () => Player.players;
  26160. /**
  26161. * Get a single player based on an ID or DOM element.
  26162. *
  26163. * This is useful if you want to check if an element or ID has an associated
  26164. * Video.js player, but not create one if it doesn't.
  26165. *
  26166. * @param {string|Element} id
  26167. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  26168. * or a string matching the `id` of such an element.
  26169. *
  26170. * @return {Player|undefined}
  26171. * A player instance or `undefined` if there is no player instance
  26172. * matching the argument.
  26173. */
  26174. videojs.getPlayer = id => {
  26175. const players = Player.players;
  26176. let tag;
  26177. if (typeof id === 'string') {
  26178. const nId = normalizeId(id);
  26179. const player = players[nId];
  26180. if (player) {
  26181. return player;
  26182. }
  26183. tag = $('#' + nId);
  26184. } else {
  26185. tag = id;
  26186. }
  26187. if (isEl(tag)) {
  26188. const {
  26189. player,
  26190. playerId
  26191. } = tag;
  26192. // Element may have a `player` property referring to an already created
  26193. // player instance. If so, return that.
  26194. if (player || players[playerId]) {
  26195. return player || players[playerId];
  26196. }
  26197. }
  26198. };
  26199. /**
  26200. * Returns an array of all current players.
  26201. *
  26202. * @return {Array}
  26203. * An array of all players. The array will be in the order that
  26204. * `Object.keys` provides, which could potentially vary between
  26205. * JavaScript engines.
  26206. *
  26207. */
  26208. videojs.getAllPlayers = () =>
  26209. // Disposed players leave a key with a `null` value, so we need to make sure
  26210. // we filter those out.
  26211. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  26212. videojs.players = Player.players;
  26213. videojs.getComponent = Component.getComponent;
  26214. /**
  26215. * Register a component so it can referred to by name. Used when adding to other
  26216. * components, either through addChild `component.addChild('myComponent')` or through
  26217. * default children options `{ children: ['myComponent'] }`.
  26218. *
  26219. * > NOTE: You could also just initialize the component before adding.
  26220. * `component.addChild(new MyComponent());`
  26221. *
  26222. * @param {string} name
  26223. * The class name of the component
  26224. *
  26225. * @param {typeof Component} comp
  26226. * The component class
  26227. *
  26228. * @return {typeof Component}
  26229. * The newly registered component
  26230. */
  26231. videojs.registerComponent = (name, comp) => {
  26232. if (Tech.isTech(comp)) {
  26233. log.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  26234. }
  26235. return Component.registerComponent.call(Component, name, comp);
  26236. };
  26237. videojs.getTech = Tech.getTech;
  26238. videojs.registerTech = Tech.registerTech;
  26239. videojs.use = use;
  26240. /**
  26241. * An object that can be returned by a middleware to signify
  26242. * that the middleware is being terminated.
  26243. *
  26244. * @type {object}
  26245. * @property {object} middleware.TERMINATOR
  26246. */
  26247. Object.defineProperty(videojs, 'middleware', {
  26248. value: {},
  26249. writeable: false,
  26250. enumerable: true
  26251. });
  26252. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  26253. value: TERMINATOR,
  26254. writeable: false,
  26255. enumerable: true
  26256. });
  26257. /**
  26258. * A reference to the {@link module:browser|browser utility module} as an object.
  26259. *
  26260. * @type {Object}
  26261. * @see {@link module:browser|browser}
  26262. */
  26263. videojs.browser = browser;
  26264. /**
  26265. * A reference to the {@link module:obj|obj utility module} as an object.
  26266. *
  26267. * @type {Object}
  26268. * @see {@link module:obj|obj}
  26269. */
  26270. videojs.obj = Obj;
  26271. /**
  26272. * Deprecated reference to the {@link module:obj.merge|merge function}
  26273. *
  26274. * @type {Function}
  26275. * @see {@link module:obj.merge|merge}
  26276. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  26277. */
  26278. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge);
  26279. /**
  26280. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  26281. *
  26282. * @type {Function}
  26283. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  26284. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  26285. */
  26286. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  26287. /**
  26288. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  26289. *
  26290. * @type {Function}
  26291. * @see {@link module:fn.bind_|fn.bind_}
  26292. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  26293. */
  26294. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  26295. videojs.registerPlugin = Plugin.registerPlugin;
  26296. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  26297. /**
  26298. * Deprecated method to register a plugin with Video.js
  26299. *
  26300. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  26301. *
  26302. * @param {string} name
  26303. * The plugin name
  26304. *
  26305. * @param {typeof Plugin|Function} plugin
  26306. * The plugin sub-class or function
  26307. *
  26308. * @return {typeof Plugin|Function}
  26309. */
  26310. videojs.plugin = (name, plugin) => {
  26311. log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  26312. return Plugin.registerPlugin(name, plugin);
  26313. };
  26314. videojs.getPlugins = Plugin.getPlugins;
  26315. videojs.getPlugin = Plugin.getPlugin;
  26316. videojs.getPluginVersion = Plugin.getPluginVersion;
  26317. /**
  26318. * Adding languages so that they're available to all players.
  26319. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  26320. *
  26321. * @param {string} code
  26322. * The language code or dictionary property
  26323. *
  26324. * @param {Object} data
  26325. * The data values to be translated
  26326. *
  26327. * @return {Object}
  26328. * The resulting language dictionary object
  26329. */
  26330. videojs.addLanguage = function (code, data) {
  26331. code = ('' + code).toLowerCase();
  26332. videojs.options.languages = merge(videojs.options.languages, {
  26333. [code]: data
  26334. });
  26335. return videojs.options.languages[code];
  26336. };
  26337. /**
  26338. * A reference to the {@link module:log|log utility module} as an object.
  26339. *
  26340. * @type {Function}
  26341. * @see {@link module:log|log}
  26342. */
  26343. videojs.log = log;
  26344. videojs.createLogger = createLogger;
  26345. /**
  26346. * A reference to the {@link module:time|time utility module} as an object.
  26347. *
  26348. * @type {Object}
  26349. * @see {@link module:time|time}
  26350. */
  26351. videojs.time = Time;
  26352. /**
  26353. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  26354. *
  26355. * @type {Function}
  26356. * @see {@link module:time.createTimeRanges|createTimeRanges}
  26357. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  26358. */
  26359. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges);
  26360. /**
  26361. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  26362. *
  26363. * @type {Function}
  26364. * @see {@link module:time.createTimeRanges|createTimeRanges}
  26365. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  26366. */
  26367. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges);
  26368. /**
  26369. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  26370. *
  26371. * @type {Function}
  26372. * @see {@link module:time.formatTime|formatTime}
  26373. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  26374. */
  26375. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  26376. /**
  26377. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  26378. *
  26379. * @type {Function}
  26380. * @see {@link module:time.setFormatTime|setFormatTime}
  26381. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  26382. */
  26383. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  26384. /**
  26385. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  26386. *
  26387. * @type {Function}
  26388. * @see {@link module:time.resetFormatTime|resetFormatTime}
  26389. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  26390. */
  26391. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  26392. /**
  26393. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  26394. *
  26395. * @type {Function}
  26396. * @see {@link module:url.parseUrl|parseUrl}
  26397. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  26398. */
  26399. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  26400. /**
  26401. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  26402. *
  26403. * @type {Function}
  26404. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  26405. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  26406. */
  26407. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  26408. videojs.EventTarget = EventTarget;
  26409. videojs.any = any;
  26410. videojs.on = on;
  26411. videojs.one = one;
  26412. videojs.off = off;
  26413. videojs.trigger = trigger;
  26414. /**
  26415. * A cross-browser XMLHttpRequest wrapper.
  26416. *
  26417. * @function
  26418. * @param {Object} options
  26419. * Settings for the request.
  26420. *
  26421. * @return {XMLHttpRequest|XDomainRequest}
  26422. * The request object.
  26423. *
  26424. * @see https://github.com/Raynos/xhr
  26425. */
  26426. videojs.xhr = lib;
  26427. videojs.TextTrack = TextTrack;
  26428. videojs.AudioTrack = AudioTrack;
  26429. videojs.VideoTrack = VideoTrack;
  26430. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  26431. videojs[k] = function () {
  26432. log.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  26433. return Dom[k].apply(null, arguments);
  26434. };
  26435. });
  26436. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  26437. /**
  26438. * A reference to the {@link module:dom|DOM utility module} as an object.
  26439. *
  26440. * @type {Object}
  26441. * @see {@link module:dom|dom}
  26442. */
  26443. videojs.dom = Dom;
  26444. /**
  26445. * A reference to the {@link module:fn|fn utility module} as an object.
  26446. *
  26447. * @type {Object}
  26448. * @see {@link module:fn|fn}
  26449. */
  26450. videojs.fn = Fn;
  26451. /**
  26452. * A reference to the {@link module:num|num utility module} as an object.
  26453. *
  26454. * @type {Object}
  26455. * @see {@link module:num|num}
  26456. */
  26457. videojs.num = Num;
  26458. /**
  26459. * A reference to the {@link module:str|str utility module} as an object.
  26460. *
  26461. * @type {Object}
  26462. * @see {@link module:str|str}
  26463. */
  26464. videojs.str = Str;
  26465. /**
  26466. * A reference to the {@link module:url|URL utility module} as an object.
  26467. *
  26468. * @type {Object}
  26469. * @see {@link module:url|url}
  26470. */
  26471. videojs.url = Url;
  26472. // The list of possible error types to occur in video.js
  26473. videojs.Error = VjsErrors;
  26474. return videojs;
  26475. }));